// Investments — the combined page (replaces the old Companies + Ideas pages).
//
//   Existing Investments
//     · Public investments   (publicly-traded positions)
//     · Private investments  (privately-held positions)
//   Ideas
//     · Prospective investments (under evaluation) + my thinking / essays
//
// Each public/private name is a logo tile; clicking it expands into a case
// study below the grid, with the company's documents (PDFs) embedded inline.
// Documents are fetched per-ticker from Supabase Storage + investment_documents
// so files can be added over time without a code change (see INVESTMENT-DOCS-SETUP.md).

// Company logo — Clearbit by domain, falling back to a colored ticker badge.
const Logo = ({ domain, ticker, color, size = 46 }) => {
  const [ok, setOk] = React.useState(!!domain);
  if (domain && ok) {
    return (
      <img
        src={`https://logo.clearbit.com/${domain}`}
        alt={ticker}
        onError={() => setOk(false)}
        style={{ width: size, height: size, objectFit: 'contain', borderRadius: '8px', background: '#fff', border: `1px solid ${tokens.inkLine}`, padding: '5px', flexShrink: 0 }}
      />
    );
  }
  return (
    <div style={{ width: size, height: size, borderRadius: '8px', background: color || tokens.ink, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: fontMono, fontSize: '13px', letterSpacing: '0.04em', flexShrink: 0 }}>
      {ticker.slice(0, 2)}
    </div>
  );
};

// Pill showing which firm an investment is tagged to.
const EmployerTag = ({ id, subtle }) => {
  const e = (window.employers || {})[id];
  if (!e) return null;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '7px', fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.1em', color: tokens.inkMute, border: `1px solid ${tokens.inkLine}`, borderRadius: '999px', padding: '4px 11px', textTransform: 'uppercase', background: subtle ? 'transparent' : tokens.paper, whiteSpace: 'nowrap' }}>
      <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: e.color }}></span>
      {e.name}
    </span>
  );
};

// Inline-embedded case-study documents for one ticker. Lazy: only fetches when
// mounted (i.e. when a tile is expanded).
const InvestmentDocs = ({ ticker, accent }) => {
  const isMobile = useIsMobile();
  const [docs, setDocs] = React.useState(null); // null = loading
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    let cancelled = false;
    const client = window._supabaseClient;
    if (!client) { setDocs([]); return; }
    (async () => {
      const { data, error } = await client
        .from('investment_documents')
        .select('name, url, doc_type, sort_order')
        .eq('ticker', ticker)
        .order('sort_order', { ascending: true });
      if (cancelled) return;
      if (error) { setErr(error.message || 'Could not load documents'); setDocs([]); }
      else setDocs(data || []);
    })();
    return () => { cancelled = true; };
  }, [ticker]);

  const heading = (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', borderTop: `1px solid ${tokens.ink}`, paddingTop: '16px', marginBottom: '24px' }}>
      <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.18em' }}>CASE-STUDY DOCUMENTS</div>
      <div style={{ fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.06em', color: tokens.inkMute }}>{docs ? `${docs.length} FILE${docs.length === 1 ? '' : 'S'}` : ''}</div>
    </div>
  );

  if (docs === null) {
    return <div>{heading}<div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.1em', color: tokens.inkMute }}>Loading documents…</div></div>;
  }

  if (docs.length === 0) {
    return (
      <div>
        {heading}
        <div style={{ border: `1px dashed ${tokens.inkLine}`, borderRadius: '6px', padding: '28px', textAlign: 'center', fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.08em', color: tokens.inkMute, lineHeight: 1.7 }}>
          {err ? `COULDN'T LOAD DOCUMENTS — ${err.toUpperCase()}` : 'NO DOCUMENTS YET'}
          <div style={{ marginTop: '8px', textTransform: 'none', letterSpacing: 0 }}>
            Upload a PDF to the <code>investment-docs/{ticker}/</code> bucket and add a row in <code>investment_documents</code> to have it appear here.
          </div>
        </div>
      </div>
    );
  }

  return (
    <div>
      {heading}
      <div style={{ display: 'flex', flexDirection: 'column', gap: '32px' }}>
        {docs.map((d, i) => {
          const type = (d.doc_type || (/\.pdf($|\?)/i.test(d.url) ? 'pdf' : /\.(png|jpe?g|gif|webp|svg)($|\?)/i.test(d.url) ? 'image' : 'link')).toLowerCase();
          return (
            <figure key={i} style={{ margin: 0 }}>
              <figcaption style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '10px', gap: '16px' }}>
                <span style={{ fontSize: '15px', letterSpacing: '-0.01em', fontWeight: 500 }}>
                  <span style={{ fontFamily: fontMono, fontSize: '11px', color: tokens.inkMute, marginRight: '10px' }}>{String(i + 1).padStart(2, '0')}</span>
                  {d.name}
                </span>
                <a href={d.url} target="_blank" rel="noopener noreferrer" style={{ fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.08em', color: accent, whiteSpace: 'nowrap', borderBottom: `1px solid ${tokens.inkLine}`, paddingBottom: '2px' }}>OPEN ↗</a>
              </figcaption>
              {type === 'pdf' && (
                <iframe
                  src={`${d.url}#view=FitH`}
                  title={d.name}
                  style={{ width: '100%', height: isMobile ? '70vh' : '760px', border: `1px solid ${tokens.inkLine}`, borderRadius: '4px', background: tokens.paper, display: 'block' }}
                />
              )}
              {type === 'image' && (
                <img src={d.url} alt={d.name} style={{ width: '100%', border: `1px solid ${tokens.inkLine}`, borderRadius: '4px', display: 'block' }} />
              )}
              {type === 'link' && (
                <a href={d.url} target="_blank" rel="noopener noreferrer" style={{ display: 'block', border: `1px solid ${tokens.inkLine}`, borderRadius: '4px', padding: '20px', background: tokens.paper, fontSize: '14px', color: tokens.ink }}>
                  {d.url} ↗
                </a>
              )}
            </figure>
          );
        })}
      </div>
    </div>
  );
};

// The expanded case study shown below the grid for the selected investment.
const InvestmentCaseStudy = ({ item, onClose }) => {
  const isMobile = useIsMobile();
  const accent = item.color || tokens.ink;
  const ref = React.useRef(null);

  React.useEffect(() => {
    if (ref.current) ref.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }, [item.slug]);

  return (
    <div ref={ref} style={{ border: `1px solid ${tokens.ink}`, borderTop: `4px solid ${accent}`, borderRadius: '4px', background: tokens.paper, marginTop: '24px', overflow: 'hidden' }}>
      {/* header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px', padding: isMobile ? '20px' : '28px 32px', borderBottom: `1px solid ${tokens.inkLine}`, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <Logo domain={item.domain} ticker={item.ticker} color={item.color} size={52} />
          <div>
            <div style={{ fontSize: isMobile ? '26px' : '34px', letterSpacing: '-0.03em', lineHeight: 1.05 }}>{item.name}</div>
            <div style={{ fontFamily: fontMono, fontSize: '11px', color: tokens.inkMute, letterSpacing: '0.08em', marginTop: '6px' }}>{item.ticker} · {item.sector.toUpperCase()}</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px', flexWrap: 'wrap' }}>
          <EmployerTag id={item.employer} />
          <button onClick={onClose} style={{ background: 'none', border: `1px solid ${tokens.inkLine}`, borderRadius: '999px', cursor: 'pointer', fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.1em', color: tokens.inkMute, padding: '6px 12px' }}>
            CLOSE ▲
          </button>
        </div>
      </div>

      {/* body */}
      <div style={{ padding: isMobile ? '24px 20px' : '40px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.7fr 1fr', gap: isMobile ? '32px' : '56px' }}>
          <div>
            <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.18em', color: tokens.inkMute, marginBottom: '16px' }}>THESIS</div>
            <p style={{ fontSize: isMobile ? '17px' : '20px', lineHeight: 1.5, letterSpacing: '-0.01em', color: tokens.ink, margin: 0, marginBottom: '32px' }}>{item.summary}</p>
            {item.bullets && item.bullets.length > 0 && (
              <div style={{ borderTop: `1px solid ${tokens.ink}`, paddingTop: '20px' }}>
                <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.18em', color: tokens.inkMute, marginBottom: '16px' }}>THE WORK</div>
                <ol style={{ margin: 0, padding: 0, listStyle: 'none' }}>
                  {item.bullets.map((b, i) => (
                    <li key={i} style={{ display: 'grid', gridTemplateColumns: '34px 1fr', gap: '16px', padding: '14px 0', borderBottom: `1px solid ${tokens.inkLineSoft}`, alignItems: 'baseline' }}>
                      <span style={{ fontFamily: fontMono, fontSize: '11px', color: tokens.inkMute }}>{String(i + 1).padStart(2, '0')}</span>
                      <span style={{ fontSize: '15px', lineHeight: 1.5, letterSpacing: '-0.005em' }}>{b}</span>
                    </li>
                  ))}
                </ol>
              </div>
            )}
          </div>

          {/* stats rail */}
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '24px 32px', borderTop: `1px solid ${tokens.ink}`, paddingTop: '20px' }}>
              {item.stats.map(([k, v]) => (
                <div key={k}>
                  <div style={{ fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.14em', color: tokens.inkMute, marginBottom: '8px' }}>{k.toUpperCase()}</div>
                  <div style={{ fontSize: '22px', letterSpacing: '-0.02em', fontFamily: fontDisplay }}>{v}</div>
                </div>
              ))}
            </div>
            <div style={{ marginTop: '24px', display: 'flex', alignItems: 'center', gap: '8px', fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.06em', color: tokens.inkMute, textTransform: 'uppercase' }}>
              ● {item.status}
            </div>
          </div>
        </div>

        {/* embedded documents */}
        <div style={{ marginTop: '48px' }}>
          <InvestmentDocs ticker={item.ticker} accent={accent} />
        </div>
      </div>
    </div>
  );
};

// Collapsed logo tile.
const InvestmentTile = ({ item, active, onToggle }) => {
  const accent = item.color || tokens.ink;
  return (
    <div
      onClick={onToggle}
      className="case-row"
      style={{
        background: tokens.paper,
        border: `1px solid ${active ? accent : tokens.inkLine}`,
        boxShadow: active ? `inset 0 0 0 1px ${accent}` : 'none',
        borderRadius: '6px',
        padding: '24px',
        cursor: 'pointer',
        display: 'flex',
        flexDirection: 'column',
        gap: '18px',
        minHeight: '170px',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '14px' }}>
        <Logo domain={item.domain} ticker={item.ticker} color={item.color} />
        <span style={{ fontFamily: fontMono, fontSize: '10px', letterSpacing: '0.1em', color: tokens.inkMute, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>● {item.status}</span>
      </div>
      <div>
        <div style={{ fontSize: '23px', letterSpacing: '-0.025em', lineHeight: 1.1 }}>{item.name}</div>
        <div style={{ fontFamily: fontMono, fontSize: '10px', color: tokens.inkMute, letterSpacing: '0.08em', marginTop: '6px' }}>{item.ticker} · {item.sector.toUpperCase()}</div>
      </div>
      <div style={{ fontSize: '14px', color: tokens.inkSoft, lineHeight: 1.5, letterSpacing: '-0.005em', flexGrow: 1 }}>{item.thesis}</div>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px' }}>
        <EmployerTag id={item.employer} subtle />
        <span style={{ fontFamily: fontMono, fontSize: '12px', color: accent }}>{active ? '▲' : 'CASE STUDY →'}</span>
      </div>
    </div>
  );
};

// A grid of tiles + the expanded case study below it. One open at a time.
const InvestmentGrid = ({ items }) => {
  const isMobile = useIsMobile();
  const [openSlug, setOpenSlug] = React.useState(null);
  const open = items.find(it => it.slug === openSlug) || null;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: '20px' }}>
        {items.map(it => (
          <InvestmentTile key={it.slug} item={it} active={it.slug === openSlug} onToggle={() => setOpenSlug(s => s === it.slug ? null : it.slug)} />
        ))}
      </div>
      {open && <InvestmentCaseStudy item={open} onClose={() => setOpenSlug(null)} />}
    </div>
  );
};

// Normalize the raw `cases` / `prospects` records into the tile/case-study shape.
const normCase = (slug, c) => ({
  slug,
  ticker: c.ticker,
  name: c.name,
  sector: c.sector,
  thesis: c.thesis,
  status: c.status,
  employer: c.employer,
  domain: c.domain,
  color: c.color,
  summary: c.summary,
  bullets: c.bullets || [],
  stats: [
    ['Position', c.ownership],
    ['Initiated', c.invested],
    [c.kind === 'private' ? 'Return' : 'IRR', c.irr],
    ['Mkt cap', c.mcap],
  ],
});

const normProspect = (p) => {
  const meta = (window.stageMeta || {})[p.stage] || { label: p.stage };
  return {
    slug: p.slug,
    ticker: p.ticker,
    name: p.name,
    sector: p.sector,
    thesis: p.note,
    status: meta.label,
    employer: p.employer,
    domain: p.domain,
    color: p.color,
    summary: p.note,
    bullets: [],
    stats: [
      ['Price', p.px],
      ['Mkt cap', p.mcap],
      ['Stage', meta.label],
    ],
  };
};

const Investments = () => {
  const all = Object.entries(window.cases || {});
  const publics = all.filter(([, c]) => (c.kind || 'public') === 'public').map(([s, c]) => normCase(s, c));
  const privates = all.filter(([, c]) => c.kind === 'private').map(([s, c]) => normCase(s, c));
  const ideas = (window.prospects || []).map(normProspect);

  const SubHead = ({ n, label, sub }) => (
    <div style={{ marginBottom: '32px' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: '14px', borderTop: `1px solid ${tokens.ink}`, paddingTop: '16px' }}>
        <span style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.12em', color: tokens.inkMute }}>{n}</span>
        <h3 style={{ fontSize: '26px', letterSpacing: '-0.03em', fontWeight: 400, margin: 0 }}>{label}</h3>
      </div>
      {sub && <p style={{ fontSize: '15px', color: tokens.inkSoft, lineHeight: 1.5, marginTop: '12px', maxWidth: '720px' }}>{sub}</p>}
    </div>
  );

  return (
    <div>
      {/* HERO */}
      <section style={{ padding: '80px 56px', borderBottom: `1px solid ${tokens.inkLine}` }}>
        <div style={{ fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.18em', color: tokens.inkMute, marginBottom: '24px' }}>02 · INVESTMENTS</div>
        <h1 style={{ fontSize: '88px', lineHeight: 0.92, letterSpacing: '-0.05em', fontWeight: 400, margin: 0, marginBottom: '32px' }}>Investments.</h1>
        <p style={{ fontSize: '22px', lineHeight: 1.45, letterSpacing: '-0.015em', color: tokens.inkSoft, maxWidth: '820px' }}>
          Where the capital is — public and private — and where it might go next. Click any name to open its case study, with the underlying work embedded inline. Each position is tagged to the firm it was made at.
        </p>
      </section>

      {/* EXISTING INVESTMENTS */}
      <Section label="2.1 · Existing Investments" title="Where the capital is." sub="Concentrated, patient, and engaged — across both public and private markets.">
        <SubHead n="PUBLIC" label="Selected public investments." sub="A selection of publicly-traded engagements. Click a logo to open the thesis, the work, and the case-study documents." />
        <InvestmentGrid items={publics} />

        <div style={{ height: '72px' }}></div>

        <SubHead n="PRIVATE" label="Selected private investments." sub="A selection of privately-held positions from across my career — not a complete picture. Click any tile to open the thesis and case-study documents." />
        <InvestmentGrid items={privates} />
      </Section>

      {/* IDEAS */}
      <Section label="2.2 · Ideas" title="What we're working on next." sub="Prospective names under active evaluation, plus the broader thinking that informs them." style={{ background: tokens.bgAlt }}>
        <SubHead n="PROSPECTS" label="Prospective investments." sub="Names in the funnel. Click any to open the working notes and any supporting documents." />
        <InvestmentGrid items={ideas} />

        <div style={{ height: '72px' }}></div>
        <SubHead n="THINKING" label="Notes & essays." sub="The longer-form thinking — essays, the live thread, and the outside reading that informs the work." />
      </Section>

      {/* preserved Ideas body (featured thesis, essays, Twitter, press) */}
      <IdeasBody />

      {/* DISCLOSURE */}
      <section style={{ padding: '40px 56px', textAlign: 'center', fontFamily: fontMono, fontSize: '11px', letterSpacing: '0.06em', color: tokens.inkMute }}>
        DISCLOSURE · POSITIONS UPDATED QUARTERLY · PROSPECTIVE NAMES NOT POSITIONS · NOT INVESTMENT ADVICE
      </section>
    </div>
  );
};

window.Investments = Investments;
