// PortfolioV4.jsx — the centerpiece. One continuous dark surface + rich panel.
// Shared by the homepage preview and the Portfolio page.

// One distinct, real image per photographed company (no repeats anywhere).
const PF_PHOTO = {
  'privateer-space':   'privateer.png',
  'jetzero':           'jetzero-hangar.jpg',
  'claros':            'claros-chip.jpg',
  'seasats':           'seasats-fleet.webp',
  'asylon-robotics':   'asylon-drone.jpg',
  'wilder-systems':    'wilder-systems.jpg',
  'safire-technology': 'safire-technology.png',
  'starfish-space':    'starfish-mira.jpg',
  'whisper-aero':      'whisper-aero.jpg',
  'exyn-technologies': 'exyn-technologies.jpg',
  'cyvl':              'cyvl.jpg',
  'zeromark':          'zeromark-operator.avif',
  'scylla':            'scylla-detect.webp',
  'vermeer':           'vermeer-airframe.png',
  'outpost-space':     'outpost-container.jpg',
  'edgecortix':        'edgecortix-sakura.webp',
  'istari-digital':    'istari-aircraft.avif',
};
const PF_POS = {
  'privateer-space': 'center 32%', 'jetzero': 'center 42%', 'claros': 'center 58%',
  'seasats': 'center 52%', 'asylon-robotics': 'center 42%', 'wilder-systems': 'center 48%',
  'safire-technology': 'center 50%', 'starfish-space': 'center 42%',
  'whisper-aero': 'center 46%', 'exyn-technologies': 'center 30%', 'cyvl': 'center 38%',
  'zeromark': 'center 42%', 'scylla': 'center 40%', 'vermeer': 'center 40%', 'outpost-space': 'center 55%', 'edgecortix': 'center 45%', 'istari-digital': 'center 50%',
};
// Companies shown by logo only (real photography not yet sourced).
const PF_LOGO_ONLY = [];
// Curated homepage teaser (photographed companies; excludes Claros — reserved
// for the Sectors chip so no image scene repeats on the homepage).
const PF_PREVIEW = ['jetzero', 'seasats', 'privateer-space', 'wilder-systems', 'asylon-robotics', 'starfish-space'];
// Large tiles in mosaic mode.
const PF_FEATURE = new Set(['jetzero', 'claros']);
// Per-logo render height (px) to normalize optical weight.
const LOGO_H = {
  'privateer-space': 34, 'starfish-space': 32, 'whisper-aero': 30, 'exyn-technologies': 32,
  'edgecortix': 20, 'istari-digital': 24, 'zeromark': 40, 'scylla': 30, 'wilder-systems': 34,
  'vermeer': 22, 'jetzero': 22, 'outpost-space': 38, 'claros': 26, 'asylon-robotics': 28,
  'seasats': 20, 'safire-technology': 30, 'cyvl': 24,
};

// Every company has a wordmark logo except Safire (photo-only).
const NO_LOGO = new Set(['safire-technology']);
const photoUrl = (slug) => PF_PHOTO[slug] ? window.R('assets/portfolio/' + PF_PHOTO[slug]) : null;
const hasLogo = (slug) => !NO_LOGO.has(slug);
const logoUrl = (slug) => window.R('assets/logos/portfolio/' + slug + '.png');
const hideOnError = (e) => { e.currentTarget.style.visibility = 'hidden'; };
const isLead = (c) => /^led\b/i.test(((c.axv_role && c.axv_role[0]) || '').trim());

const PF_FILTERS = [
  { key: 'all', label: 'All' },
  { key: 'autonomy', label: 'Autonomy' },
  { key: 'ai', label: 'Artificial Intelligence' },
  { key: 'robotics', label: 'Robotics' },
  { key: 'aviation', label: 'Aviation & Aerospace' },
  { key: 'space', label: 'Space Infrastructure' },
];

// ============================================================
// Tile
// ============================================================
function PfTile({ c, feature, onOpen }) {
  const url = photoUrl(c.slug);
  const lead = isLead(c);
  return (
    <button className="pf-tile" data-feature={feature ? 'true' : undefined} data-plate={url ? undefined : 'true'}
      onClick={() => onOpen(c.slug)} aria-label={`Open ${c.co}`}>
      {url
        ? <img src={url} alt={`${c.co} — ${c.short}`} loading="lazy" style={{ objectPosition: PF_POS[c.slug] || 'center' }} />
        : <span className="pf-tile-plate">
            {hasLogo(c.slug)
              ? <img src={logoUrl(c.slug)} alt="" loading="lazy" onError={hideOnError} style={{ maxHeight: LOGO_H[c.slug] || 26 }} />
              : <span className="pf-tile-mono">{c.initials}</span>}
          </span>}
      <div className="pf-tile-top">
        <span className="pf-badge">{c.stage}</span>
      </div>
      <div className="pf-tile-body">
        <div className="pf-tile-co">{c.co}</div>
        <div className="pf-tile-sector">{c.sector}</div>
        <p className="pf-tile-line">{c.short}</p>
        <span className="pf-tile-open">View <span aria-hidden="true">→</span></span>
      </div>
    </button>
  );
}

// ============================================================
// Detail panel (slide-over)
// ============================================================
function PfPanel({ company, list, index, onClose, onGo }) {
  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.body.style.overflow = prev; };
  }, []);
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft' && index > 0) onGo(list[index - 1].slug);
      else if (e.key === 'ArrowRight' && index < list.length - 1) onGo(list[index + 1].slug);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [index, list, onClose, onGo]);

  if (!company) return null;
  const c = company;
  const url = photoUrl(c.slug);
  const lead = isLead(c);
  const hasPrev = index > 0, hasNext = index < list.length - 1;
  const gallery = (c.gallery || []).filter(g => !PF_PHOTO[c.slug] || !g.src.endsWith(PF_PHOTO[c.slug]));

  return (
    <div className="panel-root" role="dialog" aria-modal="true" aria-label={`${c.co} detail`}>
      <div className="panel-scrim" onClick={onClose} />
      <aside className="panel" key={c.slug}>
        <div className="panel-chrome">
          <div className="panel-crumb">Portfolio&nbsp;&nbsp;/&nbsp;&nbsp;<b>{c.co}</b></div>
          <div className="panel-chrome-r">
            <button className="panel-nav" onClick={() => onGo(list[index - 1].slug)} disabled={!hasPrev} aria-label="Previous">←</button>
            <button className="panel-nav" onClick={() => onGo(list[index + 1].slug)} disabled={!hasNext} aria-label="Next">→</button>
            <button className="panel-close" onClick={onClose} aria-label="Close">×</button>
          </div>
        </div>

        <div className="panel-body">
          <figure className={`panel-hero ${url ? '' : 'is-plate'}`}>
            {url
              ? <img src={url} alt={c.co} style={{ objectPosition: PF_POS[c.slug] || 'center' }} />
              : hasLogo(c.slug)
                ? <img src={logoUrl(c.slug)} alt={c.co} onError={hideOnError} />
                : <span className="panel-hero-mono">{c.initials}</span>}
          </figure>

          <div className="panel-in">
            <header>
              <div className="panel-head-top">
                {hasLogo(c.slug)
                  ? <span className="panel-logo"><img src={logoUrl(c.slug)} alt={c.co} onError={hideOnError} style={{ maxHeight: Math.min(34, (LOGO_H[c.slug] || 26) + 6) }} /></span>
                  : <span className="panel-logo" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.14em', color: 'var(--platinum-400)' }}>{c.initials}</span>}
                {lead && <span className="panel-lead">AXV-Led</span>}
              </div>
              <h2 className="panel-co">{c.co}</h2>
              <div className="panel-sector">{c.sector}</div>
            </header>

            <dl className="panel-spec">
              <div><dt>Stage</dt><dd>{c.stage}</dd></div>
              <div><dt>AXV role</dt><dd>{lead ? 'Lead Investor' : 'Co-Investor'}</dd></div>
              {c.vehicle && <div><dt>Vehicle</dt><dd>{c.vehicle}</dd></div>}
              <div><dt>Headquarters</dt><dd>{c.hq || '—'}</dd></div>
              <div><dt>Founded</dt><dd>{c.founded || '—'}</dd></div>
              {c.website && (
                <div style={{ gridColumn: '1 / -1' }}>
                  <dt>Website</dt>
                  <dd><a href={`https://${c.website.replace(/^https?:\/\//, '')}`} target="_blank" rel="noopener">{c.website} <span className="ext">↗</span></a></dd>
                </div>
              )}
            </dl>

            {c.thesis && (
              <section>
                <div className="panel-lbl">Why AXV invested</div>
                <p className="panel-thesis">{c.thesis}</p>
              </section>
            )}

            {c.building && c.building.length > 0 && (
              <section>
                <div className="panel-lbl">What they're building</div>
                <div className="panel-prose">{c.building.map((p, i) => <p key={i}>{p}</p>)}</div>
              </section>
            )}

            {gallery.length > 0 && (
              <section className="panel-gallery">
                <div className="panel-lbl">In the field</div>
                <div className="panel-gallery-grid">
                  {gallery.map((g, i) => (
                    <figure key={i}>
                      <div className="panel-gallery-frame" style={{ aspectRatio: g.aspect || '16 / 9' }}>
                        <img src={window.R(g.src)} alt={g.caption || c.co} loading="lazy" />
                      </div>
                      {g.caption && <figcaption className="panel-gallery-cap"><span className="n">{String(i + 1).padStart(2, '0')}</span><span>{g.caption}</span></figcaption>}
                    </figure>
                  ))}
                </div>
              </section>
            )}

            {c.founders && c.founders.length > 0 && (
              <section>
                <div className="panel-lbl">Founders</div>
                <ul className="panel-founders">
                  {c.founders.map((f, i) => <li key={i}><span className="n">{f.name}</span><span className="r">{f.role}</span></li>)}
                </ul>
              </section>
            )}

            {c.axv_role && c.axv_role.length > 0 && (
              <section>
                <div className="panel-lbl">AXV engagement</div>
                <ul className="panel-list">{c.axv_role.map((l, i) => <li key={i}>{l}</li>)}</ul>
              </section>
            )}


            <div className="panel-foot"><span>Aero X Ventures</span><span>§ {c.slug}</span></div>
          </div>
        </div>
      </aside>
    </div>
  );
}

// ============================================================
// Surface (grid + logo row + panel)
// ============================================================
function PortfolioSurface({ preview = false, layout = 'gallery', setPage }) {
  const rows = window.PORTFOLIO_DATA || [];
  const [filter, setFilter] = React.useState('all');
  const [openSlug, setOpenSlug] = React.useState(null);

  const bySlug = React.useMemo(() => Object.fromEntries(rows.map(r => [r.slug, r])), [rows]);
  const photoRows = rows.filter(r => PF_PHOTO[r.slug]);
  const plateRows = rows.filter(r => !PF_PHOTO[r.slug]);

  // Photographed companies lead; the rest follow on logo plates. Every company is in the grid.
  const orderedAll = [...photoRows, ...plateRows];

  const previewRows = PF_PREVIEW.map(s => bySlug[s]).filter(Boolean);
  const gridSource = preview ? previewRows : (filter === 'all' ? orderedAll : orderedAll.filter(r => r.sectorKey === filter));
  const eff = preview ? 'gallery' : layout;

  const panelList = orderedAll;
  const openIndex = panelList.findIndex(r => r.slug === openSlug);
  const openCompany = openIndex >= 0 ? panelList[openIndex] : null;
  const counts = React.useMemo(() => {
    const m = { all: rows.length };
    for (const r of rows) m[r.sectorKey] = (m[r.sectorKey] || 0) + 1;
    return m;
  }, [rows]);

  return (
    <section className={`pf ${preview ? 'pf--preview' : 'pf--page'}`} data-theme="dark" id="portfolio">
      <div className="pf-hd">
        <div>
          <span className="sec-eyebrow">{preview ? 'Portfolio' : 'Portfolio · Index'}</span>
          <h2>{preview ? 'The companies we back.' : 'Every company AXV stands behind.'}</h2>
        </div>
        <div className="pf-hd-r">
          <span className="pf-count">{rows.length} companies</span>
        </div>
      </div>

      {!preview && eff !== 'index' && (
        <div className="pf-filters" role="tablist" aria-label="Filter by sector">
          {PF_FILTERS.map(f => {
            const n = counts[f.key] || 0;
            if (f.key !== 'all' && n === 0) return null;
            return (
              <button key={f.key} className="pf-filter" role="tab" aria-selected={filter === f.key}
                data-on={filter === f.key} onClick={() => setFilter(f.key)}>
                {f.label}<span className="n">{n}</span>
              </button>
            );
          })}
        </div>
      )}

      {eff === 'index' ? (
        <div className="pf-index">
          {(filter === 'all' ? orderedAll : orderedAll.filter(r => r.sectorKey === filter)).map(c => (
            <button className="pf-row" key={c.slug} onClick={() => setOpenSlug(c.slug)} aria-label={`Open ${c.co}`}>
              <span className={`pf-row-thumb ${photoUrl(c.slug) ? '' : 'is-mono'}`}>
                {photoUrl(c.slug) ? <img src={photoUrl(c.slug)} alt="" style={{ objectPosition: PF_POS[c.slug] || 'center' }} /> : c.initials}
              </span>
              <span className="pf-row-co">{c.co}<span className="st">{c.sector}</span></span>
              <span className="pf-row-line">{c.short}</span>
              <span className="pf-row-stage">{isLead(c) ? 'Led · ' : ''}{c.stage}</span>
              <span className="pf-row-arr">→</span>
            </button>
          ))}
        </div>
      ) : (
        <div className="pf-surface">
          <div className={`pf-grid ${eff === 'mosaic' ? 'pf-grid--mosaic' : ''}`}>
            {gridSource.map(c => (
              <PfTile key={c.slug} c={c} feature={eff === 'mosaic' && filter === 'all' && PF_FEATURE.has(c.slug)} onOpen={setOpenSlug} />
            ))}
          </div>
        </div>
      )}

      {preview && (
        <div className="pf-more">
          <button onClick={() => setPage && setPage('portfolio')}>View full portfolio <span className="arr">→</span></button>
        </div>
      )}

      {openCompany && (
        <PfPanel company={openCompany} list={panelList} index={openIndex}
          onClose={() => setOpenSlug(null)} onGo={(s) => setOpenSlug(s)} />
      )}
    </section>
  );
}
window.PortfolioSurface = PortfolioSurface;
