// Home screen — ported (session S-D): real data via lib/parkhub-data.js.
// Deleted per spec §5.1: getParkDetail("Mount Rainier") hardcoded feature,
// USER_PROGRESS fabricated stats, decorative fake pin-scatter map, PERSONAS
// import from data.jsx (persona list is now inline — small, static, and not
// user data, so it stays a constant here rather than another network call).

const PERSONAS = {
  solo:      { label: "Solo",       sub: "Quiet mornings, long trails" },
  family:    { label: "Family",     sub: "Short hikes, big wow moments" },
  glamper:   { label: "Glamper",    sub: "Canvas tents, chef pairings" },
  thruhiker: { label: "Thru-hiker", sub: "Permit windows, resupply" },
};

function PersonaGlyph({ kind }) {
  const c = 'var(--ink)';
  const wrap = (children) => (
    <div style={{
      width: 38, height: 38, borderRadius: '50%',
      border: '1px solid var(--line)', background: 'var(--bg)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
    }}>{children}</div>
  );
  if (kind === 'solo')      return wrap(<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.4" strokeLinecap="round"><circle cx="12" cy="8" r="3.2"/><path d="M6 20c0-3 3-5 6-5s6 2 6 5"/></svg>);
  if (kind === 'family')    return wrap(<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.3" strokeLinecap="round"><circle cx="9" cy="9" r="2.5"/><circle cx="16" cy="9" r="2"/><path d="M5 19c0-2.5 1.8-4.5 4-4.5s4 2 4 4.5M13 19c0-2 1.5-3.5 3-3.5s3 1.5 3 3.5"/></svg>);
  if (kind === 'glamper')   return wrap(<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"><path d="M3 19l9-13 9 13H3z"/><path d="M12 6v13M9 19l3-3 3 3"/><circle cx="12" cy="11" r="1.5"/></svg>);
  if (kind === 'thruhiker') return wrap(<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={c} strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"><path d="M3 20l5-9 4 5 3-4 6 8H3z"/><path d="M9 8l1-4 2 1"/></svg>);
  return null;
}

function PersonaDropdown({ persona, setPersona }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, [open]);
  const current = PERSONAS[persona] || PERSONAS.solo;
  return (
    <div ref={ref} style={{ position: 'relative', margin: '22px 22px 0', zIndex: 30 }}>
      <button onClick={() => setOpen(o => !o)} style={{
        width: '100%', padding: '12px 16px',
        border: open ? '1px solid var(--ink)' : '1px solid var(--line)', borderRadius: 2,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'var(--paper)', cursor: 'pointer', textAlign: 'left',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <PersonaGlyph kind={persona}/>
          <div>
            <Caps s={9}>Exploring as</Caps>
            <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 19, lineHeight: 1.1, marginTop: 2, color: 'var(--ink)' }}>{current.label}</div>
            <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 12, color: 'var(--ink-2)', marginTop: 2 }}>{current.sub}</div>
          </div>
        </div>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--ink-2)" strokeWidth="1.6" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 200ms' }}><path d="M6 9l6 6 6-6"/></svg>
      </button>
      {open && (
        <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, background: 'var(--paper)', border: '1px solid var(--ink)', borderRadius: 2, boxShadow: '0 18px 40px rgba(var(--shadow-color),0.18)', zIndex: 50, overflow: 'hidden' }}>
          <div style={{ padding: '10px 16px 6px', borderBottom: '1px solid var(--line)' }}><Caps s={9}>Choose your explorer</Caps></div>
          {Object.entries(PERSONAS).map(([k, v]) => {
            const active = k === persona;
            return (
              <button key={k} onClick={() => { setPersona(k); setOpen(false); }} style={{
                width: '100%', padding: '12px 16px', background: active ? 'var(--paper-2)' : 'transparent',
                border: 'none', cursor: 'pointer', textAlign: 'left', display: 'flex', alignItems: 'center', gap: 12,
                borderBottom: '1px solid var(--line)',
              }}>
                <PersonaGlyph kind={k}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 17, lineHeight: 1.1, color: 'var(--ink)', fontWeight: active ? 600 : 500 }}>{v.label}</div>
                  <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 12, color: 'var(--ink-2)', marginTop: 3 }}>{v.sub}</div>
                </div>
                {active && <div style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{I.check('var(--bg)')}</div>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function HomeScreen({ go, persona, setPersona, openPark }) {
  const [loading, setLoading] = React.useState(true);
  const [parkIndex, setParkIndex] = React.useState([]);
  const [visits, setVisits] = React.useState([]);
  const [trips, setTrips] = React.useState([]);
  const [journalStats, setJournalStats] = React.useState({ entries: 0, photos: 0, parks: 0 });
  const [nextTrip, setNextTrip] = React.useState(null);   // {trip, park, items}

  React.useEffect(() => {
    (async () => {
      try {
        const [idx, v, tr, journal] = await Promise.all([
          window.PH.getParkIndex(),
          window.PH.listVisits(),
          window.PH.listTrips({ status: undefined }),
          window.PH.listJournal({ limit: 100 }),
        ]);
        setParkIndex(idx);
        setVisits(v);
        setTrips(tr);
        const photos = journal.reduce((a, e) => a + (e.photos ? e.photos.length : 0), 0);
        const parks = new Set(journal.map(e => e.park_slug)).size;
        setJournalStats({ entries: journal.length, photos, parks });

        const active = tr.filter(t => t.status !== 'completed').sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0];
        if (active) {
          const [{ items }, parkData] = await Promise.all([
            window.PH.getTrip(active.id),
            window.PH.getPark(active.park_slug),
          ]);
          setNextTrip({ trip: active, items, park: parkData });
        }
      } finally { setLoading(false); }
    })();
  }, []);

  if (loading) return <div className="loading" style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--ink-3)', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Loading your fieldbook…</div>;

  const visitedCount = visits.length;
  const pct = Math.round(visitedCount / 63 * 100);
  const totals = nextTrip ? window.PH.tripTotals(nextTrip.items) : null;

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%', paddingBottom: 110 }}>
      <div style={{ padding: '58px 22px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 56, height: 56, flexShrink: 0, borderRadius: '50%', background: 'var(--paper)', border: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 20, color: 'var(--accent)' }}>PH</div>
            <div>
              <Caps s={9} style={{ display: 'block', marginBottom: 3 }}>My National Parks</Caps>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 22, lineHeight: 0.95, color: 'var(--ink)', letterSpacing: '-0.02em' }}>Adventure</div>
            </div>
          </div>
          <button onClick={() => go('badges')} style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--ink)', color: 'var(--bg)', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, flexShrink: 0 }} title="Your stamps">{visitedCount}</button>
        </div>
        <h1 style={{ margin: '24px 0 0', fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 38, lineHeight: 0.95, color: 'var(--ink)', letterSpacing: '-0.02em' }}>Good to see you,<br/>wanderer.</h1>
        <Caps s={9} style={{ display: 'block', marginTop: 10 }}>63 · U.S. National Parks · Est. 1872</Caps>
      </div>

      <PersonaDropdown persona={persona} setPersona={setPersona}/>

      {/* Passport summary card — real map, real counts (spec §2.5) */}
      <div style={{ padding: '20px 22px 0' }}>
        <PassportMap mode="card" onOpen={() => go('badges')}/>
        <div style={{ marginTop: 18 }}>
          <ProgressBar pct={pct} label={`${visitedCount} of 63 collected`} right={`${pct}%`} showPct={false} height={6}/>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginTop: 20, paddingTop: 20, borderTop: '1px solid var(--line)' }}>
          <Metric n={totals ? totals.miles : 0} l="Trail miles"/>
          <Metric n={journalStats.photos} l="Photos saved"/>
          <Metric n={journalStats.entries} l="Journal entries"/>
        </div>
      </div>

      {/* Next trip — the actual most-recently-updated non-completed trip, or an empty state */}
      {nextTrip ? (
        <>
          <SectionHead eyebrow="Next Expedition" title={nextTrip.park.name}/>
          <div style={{ padding: '0 22px' }}>
            <button onClick={() => openPark(nextTrip.park.slug, 'trip')} style={{ width: '100%', padding: 0, border: 'none', background: 'none', cursor: 'pointer', textAlign: 'left' }}>
              <div style={{ position: 'relative', borderRadius: 4, overflow: 'hidden', height: 240, background: 'var(--ink)' }}>
                {nextTrip.park.photos && nextTrip.park.photos.hero && (
                  <img src={nextTrip.park.photos.hero} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', filter: 'brightness(0.75)' }}/>
                )}
                <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, rgba(30,24,20,0.1) 40%, rgba(30,24,20,0.85))' }}/>
                <div style={{ position: 'absolute', top: 16, left: 16, right: 16, display: 'flex', justifyContent: 'space-between' }}>
                  <Caps s={9} c="rgba(242,236,223,0.85)">{nextTrip.park.state}</Caps>
                </div>
                <div style={{ position: 'absolute', bottom: 16, left: 16, right: 16, color: 'var(--bg)' }}>
                  <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 36, lineHeight: 0.95, letterSpacing: '-0.01em' }}>{nextTrip.park.name}</div>
                  {nextTrip.trip.goals && <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 15, color: 'rgba(242,236,223,0.75)', marginTop: 4 }}>{nextTrip.trip.goals}</div>}
                </div>
              </div>
            </button>
            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '16px 4px 0', borderBottom: '1px solid var(--line)', paddingBottom: 16 }}>
              <div><Caps s={9}>Items</Caps><div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, marginTop: 2 }}>{nextTrip.items.length}</div></div>
              <div><Caps s={9}>Trail mi</Caps><div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, marginTop: 2 }}>{totals.miles}</div></div>
              <div><Caps s={9}>Ascent</Caps><div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, marginTop: 2 }}>{totals.ascent_ft}′</div></div>
              <div><Caps s={9}>Status</Caps><div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, marginTop: 2, textTransform: 'capitalize' }}>{nextTrip.trip.status}</div></div>
            </div>
          </div>
        </>
      ) : (
        <>
          <SectionHead eyebrow="Next Expedition" title="Nothing planned yet"/>
          <div style={{ padding: '0 22px 4px' }}>
            <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.4, marginBottom: 14 }}>Open any park and tap the + on a hike, stay, or gear item to start a trip.</div>
            <button onClick={() => go('explore')} style={{ padding: '12px 20px', background: 'var(--ink)', color: 'var(--bg)', border: 'none', borderRadius: 100, cursor: 'pointer', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Browse the 63 parks</button>
          </div>
        </>
      )}

      {/* Recommended — top parks by real visitation, not a fake "for your persona" list */}
      <SectionHead eyebrow="Worth a Look" title="Popular right now" meta={`${parkIndex.length} parks`}/>
      <div style={{ display: 'flex', gap: 14, padding: '0 22px', overflowX: 'auto', paddingBottom: 6, scrollbarWidth: 'none' }}>
        {parkIndex.slice(0, 6).map(p => (
          <button key={p.slug} onClick={() => openPark(p.slug)} style={{ flex: '0 0 210px', border: '1px solid var(--line)', borderRadius: 3, background: 'var(--paper)', padding: 0, cursor: 'pointer', textAlign: 'left', overflow: 'hidden' }}>
            <div style={{ height: 140, background: 'var(--paper-2)', position: 'relative', overflow: 'hidden' }}>
              {p.hero_img && <img src={p.hero_img} style={{ width: '100%', height: '100%', objectFit: 'cover', filter: 'saturate(0.85)' }}/>}
            </div>
            <div style={{ padding: '12px 14px 14px' }}>
              <Caps s={9}>{p.state} · National Park</Caps>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 22, lineHeight: 1.05, marginTop: 3, color: 'var(--ink)' }}>{p.name}</div>
            </div>
          </button>
        ))}
      </div>

      {/* Journal preview */}
      <SectionHead eyebrow="Field Notes" title="From the journal"/>
      <div style={{ padding: '0 22px' }}>
        <div style={{ border: '1px solid var(--line)', borderRadius: 3, padding: '18px 20px', background: 'var(--paper)' }}>
          <Caps s={9}>{journalStats.entries} entr{journalStats.entries === 1 ? 'y' : 'ies'} · {journalStats.parks} park{journalStats.parks === 1 ? '' : 's'}</Caps>
          <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 20, lineHeight: 1.3, marginTop: 8, color: 'var(--ink)' }}>
            {journalStats.entries === 0 ? "Your first entry is the hardest one. Start after your next hike." : "Keep the streak going — write down what you saw today."}
          </div>
          <button onClick={() => go('journal')} style={{ marginTop: 14, border: 'none', background: 'none', padding: 0, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, color: 'var(--accent)', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase' }}>Open the journal {I.chev('var(--accent)')}</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen });
