// Insights — listing + in-site article reader
// (pvAbs / pvAbsHtml — root-absolute asset URLs — live in components.jsx)

function ArticleView({ a, back, setPage }) {
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: 'instant' }); }, [a.slug]);
  const cat = (a.category === 'Investments' || a.slug.startsWith('why-we-invested')) ? 'Why we invested' : a.category;
  const nav = (
    <div className="art-nav">
      <button className="art-back" onClick={back}>← All insights</button>
      {a.slug.startsWith('why-we-invested') && setPage && <button className="art-back" onClick={() => setPage('portfolio')}>← All Explorers</button>}
    </div>
  );
  return (
    <div className="art shell">
      {nav}
      <div className="art-meta">
        <span>{cat}</span>
        {a.author && <span>{a.author}</span>}
        {a.date && <span>{a.date}</span>}
      </div>
      <h1>{a.title}</h1>
      {a.subtitle && <p className="art-sub">{a.subtitle}</p>}
      {a.thumb && <div className="art-hero">{a.thumbType === 'video'
        ? <video src={pvAbs(a.thumb)} autoPlay muted loop playsInline preload="metadata" ref={el => { if (el) { el.muted = true; el.defaultMuted = true; el.volume = 0; el.play().catch(() => {}); } }}></video>
        : <img src={pvAbs(a.hero || a.thumb)} alt={a.thumbAlt || ''} />}
        {a.thumbAlt && <div className="art-cap">{a.thumbAlt}</div>}</div>}
      {a.html
        ? <div className="art-body" dangerouslySetInnerHTML={{ __html: pvAbsHtml(a.html) }}></div>
        : <div className="art-body">{(a.body || []).map((p, i) => <p key={i}>{p}</p>)}</div>}
      {nav}
    </div>
  );
}

function InsightsPage({ setPage }) {
  const [filter, setFilter] = React.useState('All');
  const [q, setQ] = React.useState('');
  const [slug, setSlug] = React.useState(() => { const s = window.PV_OPEN_ARTICLE || null; window.PV_OPEN_ARTICLE = null; return s; });
  // Keep the URL in sync with the article being read (/articles/<slug>)
  const openArticle = s => { setSlug(s); try { window.history.pushState({}, '', '/articles/' + encodeURIComponent(s)); } catch (e) {} };
  const closeArticle = () => { setSlug(null); try { window.history.pushState({}, '', '/insights'); } catch (e) {} };
  React.useEffect(() => {
    try { if (slug && !window.location.pathname.startsWith('/articles/')) window.history.replaceState({}, '', '/articles/' + encodeURIComponent(slug)); } catch (e) {}
    const onPop = () => { const m = window.location.pathname.match(/^\/articles\/(.+)$/); setSlug(m ? decodeURIComponent(m[1]) : null); };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);
  const all = window.PV_ARTICLES;
  const catOf = a => a.slug.startsWith('why-we-invested') ? 'Why we invested' : (a.category === 'Investments' ? 'Firm' : a.category);
  const cats = ['All', 'Health', 'Industrial', 'Why we invested'];
  const filteredCat = filter === 'All' ? all : all.filter(x => catOf(x) === filter);
  const corpus = React.useMemo(() => Object.fromEntries(all.map(a => [a.slug, (a.title + ' ' + (a.excerpt || '') + ' ' + (a.html || '').replace(/<[^>]+>/g, ' ')).toLowerCase()])), [all]);
  const ql = q.trim().toLowerCase();
  const filtered = ql ? filteredCat.filter(x => corpus[x.slug].includes(ql)) : filteredCat;
  const current = slug && all.find(x => x.slug === slug);
  if (current) return (
    <div>
      <ArticleView a={current} back={closeArticle} setPage={setPage} />
      <Footer setPage={setPage} />
    </div>
  );
  return (
    <div>
      <section className="hero shell" style={{ paddingBottom: 32 }}>
        <div className="hero-meta">
          <span className="dot"></span>
          <span>INSIGHTS</span>
          <span style={{ flex: 1 }}></span>
          <span>{all.length} ARTICLES</span>
        </div>
        <h1>We dive <em>deep.</em></h1>
      </section>
      <section className="shell" style={{ paddingBottom: 40 }}>
        <div className="portfolio-filter" style={{ marginTop: 0, marginBottom: 32 }}>
          {cats.map(c => (
            <button key={c}
              className={"chip m-hide" + (filter === c ? ' active' : '')}
              onClick={() => setFilter(c)}
              style={{
                borderColor: filter === c ? 'var(--fg)' : 'var(--line-c-strong)',
                background: filter === c ? 'var(--fg)' : 'transparent',
                color: filter === c ? 'var(--bg)' : 'var(--fg)'
              }}>
              {c} <span style={{ opacity: 0.6, marginLeft: 6 }}>
                {c === 'All' ? all.length : all.filter(x => catOf(x) === c).length}
              </span>
            </button>
          ))}
          <label className="m-sel m-only"><span className="lbl">Filter</span>
            <select value={filter} onChange={e => setFilter(e.target.value)}>
              {cats.map(c => <option key={c} value={c}>{c}{c !== 'All' ? ' (' + all.filter(x => catOf(x) === c).length + ')' : ''}</option>)}
            </select>
          </label>
          <input className="ins-search" type="search" placeholder="Search articles…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        {filtered.length === 0 ? <div className="ins-none">No articles match “{q}”.</div> : <div className="ins-grid">
          {filtered.map((a, i) => (
            <div className="ins-card" key={a.slug} onClick={() => openArticle(a.slug)} style={{ cursor: 'pointer' }}>
              <div className={"ins-thumb h" + ((i % 6) + 1)}>{a.thumb && (a.thumbType === 'video'
                ? <video src={pvAbs(a.thumb)} autoPlay muted loop playsInline preload="metadata" ref={el => { if (el) { el.muted = true; el.defaultMuted = true; el.volume = 0; el.play().catch(() => {}); } }}></video>
                : <img src={pvAbs(a.thumb)} alt="" loading="lazy" />)}</div>
              <div className="ins-meta">
                <span>{catOf(a)}</span>
                <span>Read →</span>
              </div>
              <div className="ins-title">{a.title}</div>
              <div className="ins-excerpt">{a.excerpt}</div>
            </div>
          ))}
        </div>}
      </section>
      <Footer setPage={setPage} />
    </div>
  );
}
window.InsightsPage = InsightsPage;
