/* TerminalPanels.jsx — the content panels (scrubber, theme, sections, feeds) */

/* ─────────── Week scrubber with tag filter ─────────── */
function WeekScrubber({ weeks, active, onPick, allTags, activeTags, toggleTag, clearTags }) {
  return (
    <Panel title="Timeline ▸ Archive" count={weeks.length}>
      <div className="eyebrow" style={{marginBottom:6}}>Weeks (newest first)</div>
      <div className="scrubber-list">
        {weeks.map(w=>(
          <button
            key={w.id}
            className={"scrubber-item "+(w.id===active?'active':'')}
            onClick={()=>onPick(w.id)}
          >
            <span className="w-label">{w.label}</span>
            <span className="w-tag">{w.dateRange} · {w.tag}</span>
          </button>
        ))}
      </div>

      <hr style={{margin:'14px 0 8px', border:0, borderTop:'1px dashed var(--paper-300)'}}/>
      <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:6}}>
        <span className="eyebrow">Filter by tag</span>
        {activeTags.length > 0 && (
          <button onClick={clearTags} style={{border:0, background:'transparent', color:'var(--amber-600)', fontFamily:'var(--font-mono)', fontSize:10, cursor:'pointer', textTransform:'uppercase', letterSpacing:'.1em'}}>
            clear ×
          </button>
        )}
      </div>
      <div className="tag-cloud">
        {allTags.map(t=>(
          <Chip key={t} btn on={activeTags.includes(t)} onClick={()=>toggleTag(t)}>
            {t}
          </Chip>
        ))}
      </div>
      <div style={{marginTop:10, fontFamily:'var(--font-mono)', fontSize:10, color:'var(--ink-600)', lineHeight:1.4}}>
        ↳ filter applies to tweets, companies, people, repos on this week.
      </div>
    </Panel>
  );
}

/* ─────────── Section nav (jump links) ─────────── */
function SectionNav({ items }) {
  if (!items || items.length === 0) return null;
  const handleClick = (e, id) => {
    const el = document.getElementById(id);
    if (el) {
      e.preventDefault();
      el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };
  return (
    <nav className="section-nav">
      {items.map(it => (
        <a key={it.id} href={`#${it.id}`} onClick={(e)=>handleClick(e, it.id)} className="section-nav-link">
          {it.label}
        </a>
      ))}
    </nav>
  );
}

/* ─────────── Headline + KPIs ─────────── */
function HeadlineStrip({ week, counts }) {
  return (
    <div className="headline-strip">
      <div className="main-title">
        <span className="meta-line">{week.label} · {week.dateRange}</span>
        <h1>{week.headline}</h1>
      </div>
      <div className="kpis">
        <div className="kpi">
          <span className="k-label">Tweets</span>
          <span className="k-value">{counts.tweets}</span>
        </div>
        <div className="kpi">
          <span className="k-label">Companies</span>
          <span className="k-value">{counts.companies}</span>
        </div>
        <div className="kpi">
          <span className="k-label">Repos</span>
          <span className="k-value">{counts.repos}</span>
        </div>
        <div className="kpi">
          <span className="k-label">$ Moves</span>
          <span className="k-value">{counts.funding}</span>
        </div>
      </div>
    </div>
  );
}

/* ─────────── Theme of week ─────────── */
function ThemePanel({ theme }) {
  const isInternal = theme.link && (theme.link.startsWith('?') || theme.link.startsWith('#') || theme.link.startsWith('/'));
  const linkProps = isInternal ? {} : { target: "_blank", rel: "noreferrer" };
  return (
    <div className="theme-panel">
      <h2>{theme.title}</h2>
      <p className="summary">{theme.summary}</p>
      <div className="tags">
        {theme.tags.map(t=><Chip key={t} amber>{t}</Chip>)}
      </div>
      {theme.link && <div className="theme-link"><a href={theme.link} {...linkProps}>→ {theme.linkLabel || 'view source'}</a></div>}
    </div>
  );
}

/* ─────────── Section block (Noticed, Trend) ─────────── */
function SectionBlock({ eyebrow, idx, title, summary, link, linkLabel, tags }) {
  const isInternal = link && (link.startsWith('?') || link.startsWith('#') || link.startsWith('/'));
  const linkProps = isInternal ? {} : { target: "_blank", rel: "noreferrer" };
  return (
    <div className="section-block">
      <div className="block-head">
        <span className="lbl">◆ {eyebrow}</span>
        <span className="idx">{idx}</span>
      </div>
      <h3>{title}</h3>
      <p>{summary}</p>
      {(tags && tags.length > 0) && (
        <div style={{display:'flex', gap:4, flexWrap:'wrap', marginTop:2}}>
          {tags.map(t=><Chip key={t}>{t}</Chip>)}
        </div>
      )}
      {link && <div className="src"><a href={link} {...linkProps}>→ {linkLabel || 'view source'}</a></div>}
    </div>
  );
}

/* ─────────── Companies ─────────── */
function Companies({ companies, activeTags }) {
  return (
    <div className="section-block" style={{minHeight:0}}>
      <div className="block-head">
        <span className="lbl">◆ Companies to watch</span>
        <span className="idx">{companies.length}</span>
      </div>
      <div style={{display:'flex', flexDirection:'column'}}>
        {companies.map(c=>{
          const dim = activeTags.length > 0 && !activeTags.includes(c.tag);
          return (
            <div key={c.name} className={"company-row "+(dim?'dim':'')}>
              <div>
                <div className="co-name">
                  <a href={c.url} target="_blank" rel="noreferrer">{c.name} ↗</a>
                </div>
                <div className="co-blurb">{c.blurb}</div>
              </div>
              <Chip>{c.tag}</Chip>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ─────────── Funding ─────────── */
const STAGE_WIDTHS = {
  'Growth': 100, 'Series C': 78, 'Series B': 55, 'Series A': 72,
  'Seed': 22, 'Pre-seed': 12, 'Fund': 92, 'Fund IX': 92
};
function FundingChart({ funding }) {
  if (!funding || funding.length === 0) return null;
  const max = funding.reduce((m,f)=>{
    const v = parseFloat((f.amount||'').replace(/[^0-9.]/g,'')) || 0;
    const isB = /B/i.test(f.amount);
    const mm = isB ? v*1000 : v;
    return Math.max(m, mm);
  }, 1);

  return (
    <div className="section-block" style={{minHeight:0}}>
      <div className="block-head">
        <span className="lbl">◆ Funding / M&A moves</span>
        <span className="idx">{funding.length}</span>
      </div>
      <div style={{display:'flex', flexDirection:'column', gap:2}}>
        {funding.map(f=>{
          const v = parseFloat((f.amount||'').replace(/[^0-9.]/g,'')) || 0;
          const isB = /B/i.test(f.amount);
          const mm = isB ? v*1000 : v;
          const pct = Math.min(100, (mm/max)*100);
          return (
            <div key={f.co} className="funding-row">
              <span className="f-co" title={f.co}>{f.co}</span>
              <span className="f-amount">{f.amount}</span>
              <div className="f-bar-track"><div className="f-bar-fill" style={{width:pct+'%'}}/></div>
              <span className="f-stage">{f.stage}{f.valuation && f.valuation !== '—' ? ' · '+f.valuation : ''}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ─────────── Tweet feed ─────────── */
function TweetsPanel({ tweets, activeTags }) {
  // tags on tweets optional; if present filter
  const filtered = activeTags.length === 0
    ? tweets
    : tweets.filter(t => !t.tags || t.tags.some(x=>activeTags.includes(x)));
  return (
    <Panel title="𝕏 Posts ▸ Live embed" count={filtered.length} bodyClass="no-pad">
      <div style={{padding:10}}>
        {filtered.length === 0
          ? <div style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--ink-600)'}}>No tweets match selected tags.</div>
          : filtered.map(t=><TweetEmbed key={t.url} url={t.url} handle={t.handle} quote={t.quote} text={t.text} media={t.media}/>)
        }
      </div>
    </Panel>
  );
}

/* ─────────── People panel ─────────── */
function PeoplePanel({ people }) {
  return (
    <Panel title="People ▸ to watch" count={people.length}>
      {people.map(p=>(
        <div key={p.handle} className="person-row">
          <div className="row-1">
            <span className="name">{p.name}</span>
            <a className="handle" href={`https://x.com/${p.handle.replace('@','')}`} target="_blank" rel="noreferrer" style={{border:0}}>{p.handle}</a>
          </div>
          <div className="why">{p.why}</div>
        </div>
      ))}
    </Panel>
  );
}

/* ─────────── Repos + Videos ─────────── */
function ReposVideosPanel({ repos, videos }) {
  if (!repos?.length && !videos?.length) return null;
  return (
    <Panel title="Repos · Demos reel" count={repos.length + videos.length}>
      <div className="eyebrow" style={{marginBottom:4}}>GitHub</div>
      {repos.map(r=>(
        <div key={r.name} className="repo-row">
          <a href={r.url} target="_blank" rel="noreferrer" className="path" style={{border:0}}>{r.name}</a>
          <div className="blurb">{r.blurb}</div>
        </div>
      ))}

      <div className="eyebrow" style={{marginTop:12, marginBottom:4}}>Videos / demos</div>
      <div className="video-grid">
        {videos.map(v=>(
          <a key={v.url} className="video-tile" href={v.url} target="_blank" rel="noreferrer">
            <span className="vid-label">{v.title}</span>
          </a>
        ))}
      </div>
    </Panel>
  );
}

window.WeekScrubber = WeekScrubber;
window.HeadlineStrip = HeadlineStrip;
window.ThemePanel = ThemePanel;
window.SectionNav = SectionNav;
window.SectionBlock = SectionBlock;
window.Companies = Companies;
window.FundingChart = FundingChart;
window.TweetsPanel = TweetsPanel;
window.PeoplePanel = PeoplePanel;
window.ReposVideosPanel = ReposVideosPanel;
