// Browse All — full content library with lane/category filtering

const BROWSE_SB_URL = 'https://xkquhthyfqdcbktyigyu.supabase.co';
const BROWSE_SB_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhrcXVodGh5ZnFkY2JrdHlpZ3l1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY4MDEzMjcsImV4cCI6MjA5MjM3NzMyN30.N4faHMUv_gkRzJ_okqDIoGD4uBIdpSLQ9mwDdpdZAbE';

function browseLabel(slug) {
  return (slug || '').split('-').map(w => w ? w[0].toUpperCase() + w.slice(1) : '').join(' ');
}

function BrowseAll() {
  const [pages, setPages] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [lane, setLaneState] = React.useState(null);
  const [cat, setCatState] = React.useState(null);
  const [gridReady, setGridReady] = React.useState(false);

  // Read URL params on mount
  React.useEffect(() => {
    const p = new URLSearchParams(window.location.search);
    const l = p.get('lane');
    const c = p.get('sub');
    if (l === 'personal' || l === 'business') setLaneState(l);
    if (c) setCatState(c);
  }, []);

  // Fetch all English pages
  React.useEffect(() => {
    let active = true;
    (async () => {
      try {
        const all = [];
        let offset = 0;
        const limit = 1000;
        while (true) {
          const res = await fetch(
            `${BROWSE_SB_URL}/rest/v1/pages?select=slug,title,lane,category&language=eq.en&order=created_at.desc&limit=${limit}&offset=${offset}`,
            { headers: { apikey: BROWSE_SB_KEY, Authorization: `Bearer ${BROWSE_SB_KEY}` } }
          );
          if (!res.ok) throw new Error(`${res.status}`);
          const batch = await res.json();
          if (!batch || batch.length === 0) break;
          all.push(...batch);
          if (batch.length < limit) break;
          offset += limit;
        }
        if (!active) return;
        setPages(all);
        setLoading(false);
        // Double RAF ensures DOM is painted before fade-in triggers
        requestAnimationFrame(() => requestAnimationFrame(() => setGridReady(true)));
      } catch (e) {
        if (!active) return;
        setError(e.message);
        setLoading(false);
      }
    })();
    return () => { active = false; };
  }, []);

  // Live clock
  React.useEffect(() => {
    const tick = () => {
      const now = new Date();
      const h = String(now.getHours()).padStart(2, '0');
      const m = String(now.getMinutes()).padStart(2, '0');
      const s = String(now.getSeconds()).padStart(2, '0');
      const el = document.getElementById('tickerClock');
      if (el) el.textContent = `NYC · ${h}:${m}:${s}`;
      const fs = document.getElementById('fsess');
      if (fs) fs.textContent = `${h}${m}.${s}`;
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);

  function setLane(l) {
    setLaneState(l);
    setCatState(null);
    const p = new URLSearchParams();
    if (l) p.set('lane', l);
    const qs = p.toString();
    window.history.replaceState({}, '', '/browse/' + (qs ? '?' + qs : ''));
  }

  function setCat(c) {
    setCatState(c);
    const p = new URLSearchParams(window.location.search);
    if (c) p.set('sub', c); else p.delete('sub');
    const qs = p.toString();
    window.history.replaceState({}, '', '/browse/' + (qs ? '?' + qs : ''));
  }

  const categories = React.useMemo(() => {
    const src = lane ? pages.filter(p => p.lane === lane) : pages;
    return [...new Set(src.map(p => p.category).filter(Boolean))].sort();
  }, [pages, lane]);

  const filtered = React.useMemo(() =>
    pages.filter(p => (!lane || p.lane === lane) && (!cat || p.category === cat)),
    [pages, lane, cat]
  );

  return (
    <div className="site">
      <Ticker />
      <Nav lane={lane || 'personal'} setLane={() => {}} />

      <main className="browse">
        <div className="browse__head">
          <div className="browse__kicker">CONTENT LIBRARY · HOWTO: FINANCE EDITION</div>
          <h1 className="browse__h1">Every Guide.</h1>
          <p className="browse__tally">
            {loading
              ? <span className="browse__tally-dash">—</span>
              : <>{filtered.length.toLocaleString()} {filtered.length === 1 ? 'guide' : 'guides'}{lane ? ` · ${browseLabel(lane)}` : ' · All lanes'}{cat ? ` · ${browseLabel(cat)}` : ''}</>
            }
          </p>
        </div>

        <div className="browse__filters">
          <div className="browse__pills" role="group" aria-label="Filter by lane">
            {([null, 'personal', 'business']).map((l) => (
              <button
                key={String(l)}
                className={`browse__pill${lane === l ? ' is-active' : ''}`}
                onClick={() => setLane(l)}
                aria-pressed={lane === l}
              >
                {l === null ? 'All' : l === 'personal' ? '01 Personal' : '02 Business'}
              </button>
            ))}
          </div>

          {categories.length > 0 && (
            <div className="browse__pills browse__pills--sub" role="group" aria-label="Filter by category">
              <button
                className={`browse__pill browse__pill--sm${!cat ? ' is-active' : ''}`}
                onClick={() => setCat(null)}
                aria-pressed={!cat}
              >All</button>
              {categories.map(c => (
                <button
                  key={c}
                  className={`browse__pill browse__pill--sm${cat === c ? ' is-active' : ''}`}
                  onClick={() => setCat(c)}
                  aria-pressed={cat === c}
                >{browseLabel(c)}</button>
              ))}
            </div>
          )}
        </div>

        {loading && (
          <div className="browse__state">
            <span className="browse__state-text">Loading library…</span>
          </div>
        )}
        {error && (
          <div className="browse__state">
            <span className="browse__state-text">Could not reach the library. Try refreshing.</span>
          </div>
        )}
        {!loading && !error && filtered.length === 0 && (
          <div className="browse__state">
            <span className="browse__state-text">No guides match this filter.</span>
          </div>
        )}

        {!loading && !error && filtered.length > 0 && (
          <div className={`browse__grid${gridReady ? ' is-loaded' : ''}`}>
            {filtered.map(page => {
              const href = page.slug.startsWith('/') ? page.slug : `/${page.slug}`;
              return (
                <a key={page.slug} href={href} className={`browse__card browse__card--${page.lane}`}>
                  <div className="browse__card-meta">
                    <span className="browse__card-num">{page.lane === 'personal' ? '01' : '02'}</span>
                    <span className="browse__card-sep">·</span>
                    <span className="browse__card-cat">{browseLabel(page.category)}</span>
                  </div>
                  <h2 className="browse__card-title">{page.title}</h2>
                </a>
              );
            })}
          </div>
        )}
      </main>

      <NetworkBand />
      <Footer />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<BrowseAll />);
