// Explore screen — ported (session S-D). ALL_PARKS deleted, replaced by
// getParkIndex(). "Visited"/"Planned" filters now read real park_visits and
// wishlist rows instead of the hardcoded USER_PROGRESS demo object. The
// biome-based filters ("desert" etc.) are gone — parks_data has no biome
// field for the real 63; region filters below are derived honestly from
// each park's real `state` field, not invented.

const REGION_STATES = {
  west: new Set(["CA","OR","WA","NV","UT","AZ","CO","NM","WY","MT","ID"]),
  alaska: new Set(["AK"]),
  south: new Set(["TX","AR","SC","FL","VA","WV","NC","TN"]),
  midwest: new Set(["OH","IN","MI","MN","SD","ND"]),
  islands: new Set(["HI","AS","VI"]),
};
function regionOf(stateStr) {
  const codes = (stateStr || "").split(/[\/,]/).map(s => s.trim());
  for (const [region, set] of Object.entries(REGION_STATES)) {
    if (codes.some(c => set.has(c))) return region;
  }
  return "other";
}

function ExploreScreen({ go, openPark }) {
  const [query, setQuery] = React.useState('');
  const [filter, setFilter] = React.useState('all');
  const [loading, setLoading] = React.useState(true);
  const [parks, setParks] = React.useState([]);
  const [visitedSlugs, setVisitedSlugs] = React.useState(new Set());
  const [wishSlugs, setWishSlugs] = React.useState(new Set());

  React.useEffect(() => {
    (async () => {
      try {
        const [idx, visits, wish] = await Promise.all([
          window.PH.getParkIndex(),
          window.PH.listVisits(),
          window.PH.listWishlist(),
        ]);
        setParks(idx);
        setVisitedSlugs(new Set(visits.map(v => v.park_slug)));
        setWishSlugs(new Set(wish.map(w => w.park_slug)));
      } finally { setLoading(false); }
    })();
  }, []);

  const filters = [
    { k: 'all', l: 'All 63' },
    { k: 'visited', l: 'Visited' },
    { k: 'wishlist', l: 'Wishlist' },
    { k: 'west', l: 'West' },
    { k: 'alaska', l: 'Alaska' },
    { k: 'islands', l: 'Islands' },
  ];

  const filtered = parks.filter(p => {
    if (query && !p.name.toLowerCase().includes(query.toLowerCase()) && !(p.state || '').toLowerCase().includes(query.toLowerCase())) return false;
    if (filter === 'visited') return visitedSlugs.has(p.slug);
    if (filter === 'wishlist') return wishSlugs.has(p.slug);
    if (filter !== 'all') return regionOf(p.state) === filter;
    return true;
  }).sort((a, b) => a.stamp_no - b.stamp_no);

  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 the index…</div>;

  return (
    <div style={{ background: 'var(--bg)', minHeight: '100%', paddingBottom: 110 }}>
      <div style={{ padding: '58px 22px 0' }}>
        <Caps s={10} c="var(--accent)">The Index</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)' }}>Sixty-three<br/>kept places.</h1>
      </div>

      <div style={{ padding: '20px 22px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', border: '1px solid var(--line)', borderRadius: 2, background: 'var(--paper)' }}>
          {I.search('var(--ink-3)')}
          <input placeholder="Search parks or states" value={query} onChange={e => setQuery(e.target.value)}
            style={{ flex: 1, border: 'none', background: 'none', outline: 'none', fontFamily: 'DM Sans, sans-serif', fontSize: 14, color: 'var(--ink)' }}/>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, padding: '14px 22px 0', overflowX: 'auto', scrollbarWidth: 'none' }}>
        {filters.map(f => <Chip key={f.k} active={filter === f.k} onClick={() => setFilter(f.k)}>{f.l}</Chip>)}
      </div>

      <div style={{ padding: '22px 22px 10px', display: 'flex', justifyContent: 'space-between' }}>
        <Caps s={9}>Showing · {filtered.length}</Caps>
        <Caps s={9}>Sorted by stamp order</Caps>
      </div>

      <div style={{ padding: '0 22px' }}>
        {filtered.map((p) => {
          const visited = visitedSlugs.has(p.slug);
          const wished = wishSlugs.has(p.slug);
          return (
            <button key={p.slug} onClick={() => openPark(p.slug)} style={{
              width: '100%', padding: '14px 0', background: 'none', border: 'none',
              borderTop: '1px solid var(--line)', cursor: 'pointer', textAlign: 'left',
              display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: 12, alignItems: 'baseline',
            }}>
              <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--ink-3)', letterSpacing: '0.05em' }}>{String(p.stamp_no).padStart(2, '0')}</span>
              <div>
                <div style={{ fontFamily: 'Space Grotesk, sans-serif', fontWeight: 700, fontSize: 20, lineHeight: 1.1, color: 'var(--ink)', letterSpacing: '-0.02em' }}>{p.name}</div>
                <div style={{ marginTop: 3, display: 'flex', gap: 8, alignItems: 'center' }}>
                  <Caps s={9}>{p.state}</Caps>
                  {visited && <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.1em', color: 'var(--accent)', textTransform: 'uppercase' }}>· Collected</span>}
                  {wished && !visited && <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 9, letterSpacing: '0.1em', color: 'var(--olive)', textTransform: 'uppercase' }}>· Wishlist</span>}
                </div>
              </div>
              <span style={{ color: 'var(--ink-3)' }}>{I.chev()}</span>
            </button>
          );
        })}
        <div style={{ borderTop: '1px solid var(--line)' }}/>
      </div>
    </div>
  );
}

Object.assign(window, { ExploreScreen });
