// Badges / Collection screen — ported (session S-D). Hardcoded earned/locked
// demo arrays replaced by badgeProgress() (badge_defs seeded in session S-B:
// first-stamp, ten-stamps, utah-mighty-five, desert-rat, pacific-crest,
// all-63). Icon assignment is a small fixed lookup by badge key since
// badge_defs has no icon column — not fabricated data, just a display choice.

const BADGE_ICONS = {
  'first-stamp': 'tree', 'ten-stamps': 'mtn', 'utah-mighty-five': 'sun',
  'desert-rat': 'sun', 'pacific-crest': 'mtn', 'all-63': 'lake',
};

function BadgeGlyph({ kind }) {
  const col = 'var(--accent)';
  if (kind === 'tree') return (<svg width="42" height="42" viewBox="0 0 40 40" fill="none" stroke={col} strokeWidth="1.3"><path d="M20 6L12 18h5L10 28h7l-3 6h12l-3-6h7l-7-10h5z"/><line x1="20" y1="28" x2="20" y2="36"/></svg>);
  if (kind === 'mtn') return (<svg width="42" height="42" viewBox="0 0 40 40" fill="none" stroke={col} strokeWidth="1.3"><path d="M4 32l10-16 6 10 5-8 11 14z"/><path d="M14 16l-3-5"/></svg>);
  if (kind === 'sun') return (<svg width="42" height="42" viewBox="0 0 40 40" fill="none" stroke={col} strokeWidth="1.3"><circle cx="20" cy="20" r="7"/>{[0,1,2,3,4,5,6,7].map(i => { const a = i * Math.PI / 4; const x1 = 20 + Math.cos(a) * 11, y1 = 20 + Math.sin(a) * 11; const x2 = 20 + Math.cos(a) * 15, y2 = 20 + Math.sin(a) * 15; return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}/>; })}</svg>);
  if (kind === 'lake') return (<svg width="42" height="42" viewBox="0 0 40 40" fill="none" stroke={col} strokeWidth="1.3"><path d="M6 22q4-3 8 0t8 0 8 0 4 0"/><path d="M6 28q4-3 8 0t8 0 8 0 4 0"/><path d="M12 18l4-6 4 6"/><path d="M22 18l3-4 3 4"/></svg>);
  if (kind === 'book') return (<svg width="42" height="42" viewBox="0 0 40 40" fill="none" stroke={col} strokeWidth="1.3"><path d="M8 10h10a4 4 0 0 1 4 4v16a3 3 0 0 0-3-3H8z"/><path d="M32 10H22a4 4 0 0 0-4 4v16a3 3 0 0 1 3-3h11z"/></svg>);
  return null;
}

function ThemeToggle() {
  const [pref, setPref] = React.useState('auto');
  React.useEffect(() => {
    setPref(window.phGetTheme ? window.phGetTheme() : 'auto');
    const onChange = () => setPref(window.phGetTheme ? window.phGetTheme() : 'auto');
    window.addEventListener('ph-theme-change', onChange);
    return () => window.removeEventListener('ph-theme-change', onChange);
  }, []);
  const opts = [['auto', 'Auto'], ['light', 'Day'], ['dark', 'Night']];
  return (
    <div style={{ display: 'flex', border: '1px solid var(--line)', borderRadius: 100, padding: 3 }}>
      {opts.map(([k, l]) => {
        const active = pref === k;
        return (
          <button key={k} onClick={() => window.phSetTheme && window.phSetTheme(k)} style={{
            flex: 1, padding: '8px 0', border: 'none', borderRadius: 100, cursor: 'pointer',
            background: active ? 'var(--ink)' : 'transparent', color: active ? 'var(--bg)' : 'var(--ink-3)',
            fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
          }}>{l}</button>
        );
      })}
    </div>
  );
}

function ProfileBlock({ go, openPark }) {
  const [loading, setLoading] = React.useState(true);
  const [user, setUser] = React.useState(null);
  const [persona, setPersona] = React.useState(null);
  const [stats, setStats] = React.useState({ trips: 0, saved: 0, journal: 0 });
  const [nextTripSlug, setNextTripSlug] = React.useState(null);

  React.useEffect(() => {
    (async () => {
      try {
        const [u, trips, items, journal] = await Promise.all([
          window.PH.getUser(), window.PH.listTrips({ status: undefined }),
          window.PH.listAllTripItems(), window.PH.listJournal({ limit: 100 }),
        ]);
        setUser(u);
        try { const prof = await window.PH.getProfile(); setPersona(prof && prof.persona); } catch (e) {}
        setStats({ trips: trips.length, saved: items.length, journal: journal.length });
        const active = trips.filter(t => t.status !== 'completed').sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))[0];
        if (active) setNextTripSlug(active.park_slug);
      } finally { setLoading(false); }
    })();
  }, []);

  const signOut = async () => { try { await window.PH.signOut(); } catch (e) {} };

  return (
    <>
      <SectionHead eyebrow="Field Settings" title="Profile"/>
      <div style={{ padding: '0 22px' }}>
        <div style={{ border: '1px solid var(--line)', borderRadius: 3, padding: '18px 20px', background: 'var(--paper)' }}>
          {!loading && user && (
            <>
              <Caps s={9}>Signed in as</Caps>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 18, color: 'var(--ink)', marginTop: 3 }}>{user.email}</div>
              <a href="/account.html" style={{ display: 'inline-block', marginTop: 6, color: 'var(--accent)', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', textDecoration: 'none' }}>Edit on the website →</a>
            </>
          )}
          {persona && (
            <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <Caps s={9}>Exploring as</Caps>
                <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 16, color: 'var(--ink)', marginTop: 2, textTransform: 'capitalize' }}>{persona}</div>
              </div>
              <button onClick={() => go('home')} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--ink-3)', fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Change on Home</button>
            </div>
          )}
          <div style={{ marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
            <Caps s={9} style={{ display: 'block', marginBottom: 8 }}>Display · day or night</Caps>
            <ThemeToggle/>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 18, paddingTop: 18, borderTop: '1px solid var(--line)' }}>
            <button onClick={() => nextTripSlug ? openPark(nextTripSlug, 'trip') : go('explore')} style={{ textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer', padding: 0 }}>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 22, color: 'var(--ink)' }}>{stats.trips}</div>
              <Caps s={9} style={{ display: 'block', marginTop: 2 }}>Trips</Caps>
            </button>
            <button onClick={() => go('saved')} style={{ textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer', padding: 0 }}>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 22, color: 'var(--ink)' }}>{stats.saved}</div>
              <Caps s={9} style={{ display: 'block', marginTop: 2 }}>Saved</Caps>
            </button>
            <button onClick={() => go('journal')} style={{ textAlign: 'left', border: 'none', background: 'none', cursor: 'pointer', padding: 0 }}>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 22, color: 'var(--ink)' }}>{stats.journal}</div>
              <Caps s={9} style={{ display: 'block', marginTop: 2 }}>Journal</Caps>
            </button>
          </div>
          <button onClick={signOut} style={{ marginTop: 18, width: '100%', padding: '11px 0', border: '1px solid var(--line)', borderRadius: 100, background: 'transparent', color: 'var(--ink-2)', cursor: 'pointer', fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Sign out</button>
        </div>
      </div>
    </>
  );
}

function BadgesScreen({ go, openPark }) {
  const [loading, setLoading] = React.useState(true);
  const [progress, setProgress] = React.useState([]);

  React.useEffect(() => {
    (async () => { try { setProgress(await window.PH.badgeProgress()); } finally { setLoading(false); } })();
  }, []);

  if (loading) return <div 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 stamps…</div>;

  const earned = progress.filter(b => b.earned);
  const inProgress = progress.filter(b => !b.earned);

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%', paddingBottom: 110 }}>
      <div style={{ padding: '58px 22px 0' }}>
        <Caps s={10} c="var(--accent)">The Passport</Caps>
        <h1 style={{ margin: '6px 0 0', fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 44, lineHeight: 0.95, letterSpacing: '-0.02em', color: 'var(--ink)' }}>Stamps in the<br/>passport.</h1>
        <div style={{ fontFamily: 'Space Grotesk, sans-serif', color: 'var(--ink-2)', fontSize: 16, marginTop: 12, lineHeight: 1.4, maxWidth: 320 }}>A quiet record of what you have seen — not trophies, but reasons to remember.</div>
      </div>

      <div style={{ marginTop: 24 }}>
        <PassportMap mode="full"/>
      </div>

      <div style={{ margin: '28px 22px 0', padding: '20px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        <Metric n={earned.length} l="Earned"/>
        <Metric n={inProgress.length} l="In progress"/>
        <Metric n={progress.length ? `${Math.round(earned.length / progress.length * 100)}%` : '0%'} l="Complete"/>
      </div>

      <SectionHead eyebrow="Earned" title="The record" meta={earned.length}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, padding: '0 22px' }}>
        {earned.length === 0 && (
          <div style={{ gridColumn: '1 / -1', fontFamily: 'Space Grotesk, sans-serif', fontStyle: 'italic', color: 'var(--ink-3)', padding: '10px 0' }}>Stamp your first park to start earning badges.</div>
        )}
        {earned.map((b, i) => (
          <div key={b.key} style={{ border: '1px solid var(--line)', borderRadius: 3, padding: '18px 14px 14px', background: 'var(--paper)', position: 'relative', aspectRatio: '0.82', display: 'flex', flexDirection: 'column' }}>
            <CornerMarks c="var(--ink-3)" pad={6} len={8} w={1}/>
            <Caps s={9} c="var(--accent)" style={{ display: 'block' }}>№{String(i + 1).padStart(3, '0')}</Caps>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '12px 0' }}>
              <div style={{ width: 110, height: 110, borderRadius: '50%', border: '1.5px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative' }}>
                <div style={{ width: 94, height: 94, borderRadius: '50%', border: '1px dashed var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
                  <BadgeGlyph kind={BADGE_ICONS[b.key] || 'tree'}/>
                </div>
              </div>
            </div>
            <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 18, color: 'var(--ink)', lineHeight: 1.1 }}>{b.name}</div>
            <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 12, color: 'var(--ink-2)', marginTop: 3, lineHeight: 1.3 }}>{b.description}</div>
          </div>
        ))}
      </div>

      <SectionHead eyebrow="In Pursuit" title="Still ahead" meta={inProgress.length}/>
      <div style={{ padding: '0 22px' }}>
        {inProgress.map((b) => (
          <div key={b.key} style={{ padding: '18px 0', borderTop: '1px solid var(--line)', display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 16, alignItems: 'center' }}>
            <div style={{ width: 60, height: 60, borderRadius: '50%', border: '1px dashed var(--ink-3)', opacity: 0.5, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--ink-3)" strokeWidth="1.4"><rect x="5" y="11" width="14" height="10" rx="1"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>
            </div>
            <div>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 19, color: 'var(--ink)', lineHeight: 1.1 }}>{b.name}</div>
              <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontSize: 13, color: 'var(--ink-2)', marginTop: 3 }}>{b.description}</div>
              <div style={{ marginTop: 8, display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ flex: 1, maxWidth: 140, height: 3, background: 'var(--paper-2)', borderRadius: 2, overflow: 'hidden' }}>
                  <div style={{ width: b.pct + '%', height: '100%', background: 'var(--accent)' }}/>
                </div>
                <Caps s={9}>{b.have}/{b.need}</Caps>
              </div>
            </div>
          </div>
        ))}
        <div style={{ borderTop: '1px solid var(--line)' }}/>
      </div>

      <div style={{ marginTop: 24 }}>
        <ProfileBlock go={go} openPark={openPark}/>
      </div>
    </div>
  );
}

Object.assign(window, { BadgesScreen });
