// Work pages — index, case study detail, portfolios
function WorkIndexPage() {
  const D = window.TSD_DATA;
  const [filter, setFilter] = useState('all');
  const filters = [
    { k: 'all', label: 'All' },
    { k: 'mail', label: 'Direct Mail' },
    { k: 'video', label: 'Digital' }
  ];
  const filtered = filter === 'all' ? D.cases : D.cases.filter(c => c.mediaKind === filter);

  return (
    <>
      <Nav />
      <PageHeader eyebrow="§ Work" title={<>Nine cycles. Nine wins worth <span style={{fontStyle:'italic'}}>showing.</span></>} intro="A selection of case studies across mail, digital, branding, and full-service strategy. Click through for the full story." />

      <section style={{ padding: '0 var(--gutter) 24px', background: 'var(--paper)' }}>
        <div className="shell" style={{ display: 'flex', gap: 8, alignItems: 'center', borderTop: '1px solid var(--ink-12)', paddingTop: 24 }}>
          <span className="eyebrow" style={{ marginRight: 16 }}>Filter</span>
          {filters.map(f => (
            <button key={f.k} onClick={() => setFilter(f.k)} className={f.k === filter ? 'btn btn-primary' : 'btn btn-ghost'} style={{ padding: '8px 16px', fontSize: 13 }}>
              {f.label}
            </button>
          ))}
        </div>
      </section>

      <section className="section">
        <div className="shell">
          <SectionIntro
            num="01"
            kicker="The portfolio"
            title={<>Nine featured cases.</>}
            sub="Each card is a full case study. Filter by medium above, or jump to the direct mail or digital archives at the bottom of the page."
          />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 32, rowGap: 80 }}>
            {filtered.map((c, i) => {
              const layouts = [
                { col: '1 / 7', aspect: '4/3' },
                { col: '8 / 13', aspect: '3/4' },
                { col: '1 / 5', aspect: '1/1' },
                { col: '6 / 13', aspect: '4/3' },
                { col: '1 / 8', aspect: '16/9' },
                { col: '9 / 13', aspect: '3/4' },
                { col: '1 / 7', aspect: '1/1' },
                { col: '8 / 13', aspect: '4/3' },
                { col: '1 / 13', aspect: '21/9' }
              ];
              const lo = layouts[i % layouts.length];
              return (
                <Reveal key={c.slug} delay={i*40} className="work-card" style={{ gridColumn: lo.col }}>
                  <Link to={`/work/${c.slug}`}>
                    <div className="work-card-media" style={{ aspectRatio: lo.aspect }}>
                      {c.mediaKind === 'mail' ? (
                        <MailPlaceholder piece={{ id: c.slug, client: c.client, race: c.race }} idx={i} />
                      ) : (
                        <div style={{ position: 'relative', width: '100%', height: '100%', background: 'var(--ink)', overflow: 'hidden' }}>
                          <img loading="lazy" src={`https://vumbnail.com/${c.videos[0].id}.jpg`} alt={c.client} style={{ width: '100%', height: '100%', objectFit: 'cover', opacity: 0.85 }} onError={(e)=>e.target.style.display='none'} />
                          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(14,14,18,0.2) 0%, rgba(14,14,18,0.7) 100%)' }}></div>
                          <div style={{ position: 'absolute', bottom: 20, left: 20, color: 'var(--paper)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.7 }}>▶ {c.videos.length} films</div>
                        </div>
                      )}
                    </div>
                    <div className="work-card-meta">
                      <div>
                        <div className="work-card-num">№ {String(i+1).padStart(2,'0')} · {c.year}</div>
                        <div className="work-card-title" style={{ marginTop: 6 }}>{c.client}</div>
                        <div style={{ fontSize: 13, color: 'var(--ink-60)', marginTop: 4 }}>{c.race}</div>
                      </div>
                      <div className="eyebrow">{c.classification.split(',')[0]}</div>
                    </div>
                    <p className="body" style={{ marginTop: 20, maxWidth: 580, color: 'var(--ink-60)' }}>{c.summary}</p>
                  </Link>
                </Reveal>
              );
            })}
          </div>

          <div style={{ marginTop: 120, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 32, borderTop: '1px solid var(--ink-12)', paddingTop: 64 }}>
            <Link to="/work/direct-mail" className="work-card" style={{ background: 'var(--paper-warm)', padding: 48 }}>
              <div className="eyebrow">Browse all 52 pieces</div>
              <div className="display-md" style={{ marginTop: 24 }}>Direct Mail Portfolio</div>
              <div className="link-arrow" style={{ marginTop: 32 }}>Open the archive</div>
            </Link>
            <Link to="/work/digital" className="work-card" style={{ background: 'var(--ink)', color: 'var(--paper)', padding: 48 }}>
              <div className="eyebrow eyebrow-light">Browse 46 films</div>
              <div className="display-md" style={{ marginTop: 24 }}>Digital Portfolio</div>
              <div className="link-arrow" style={{ marginTop: 32 }}>Watch the reel</div>
            </Link>
          </div>
        </div>
      </section>

      <Footer />
    </>
  );
}

function CaseStudyPage({ slug }) {
  const D = window.TSD_DATA;
  const c = D.cases.find(x => x.slug === slug);
  if (!c) return <NotFound />;

  const idx = D.cases.findIndex(x => x.slug === slug);
  const next = D.cases[(idx + 1) % D.cases.length];
  const others = D.cases.filter(x => x.slug !== slug);

  return (
    <>
      <Nav darkInitial={true} />

      {/* Hero */}
      <section style={{ minHeight: '90vh', background: 'var(--ink)', color: 'var(--paper)', display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', padding: '180px var(--gutter) 80px', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.4 }}>
          {c.mediaKind === 'video' ? (
            <img src={`https://vumbnail.com/${c.videos[0].id}_large.jpg`} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={(e)=>e.target.style.display='none'} />
          ) : (
            <div style={{ width: '100%', height: '100%' }}>
              <MailPlaceholder piece={{ id: c.slug + 'hero', client: c.client, race: c.race }} idx={0} />
            </div>
          )}
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(14,14,18,0.4) 0%, rgba(14,14,18,0.9) 100%)' }}></div>
        </div>
        <div className="shell" style={{ position: 'relative' }}>
          <div className="eyebrow eyebrow-light">Case Study № {String(idx+1).padStart(2,'0')} / 09 · {c.year}</div>
          <div style={{ marginTop: 24 }} className="body-lg">{c.client} <span style={{opacity:0.5}}>—</span> {c.race}</div>
          <h1 className="display-xl" style={{ marginTop: 32, maxWidth: 1200, fontStyle: 'italic', fontWeight: 300 }}>{c.headline}</h1>
        </div>
      </section>

      {/* Toplines */}
      <section className="section-tight" style={{ background: 'var(--paper-warm)' }}>
        <div className="shell">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0, borderTop: '1px solid var(--ink-12)', borderBottom: '1px solid var(--ink-12)' }}>
            {[
              { k: 'Classification', v: c.classification },
              { k: 'Objective', v: c.objective },
              { k: 'Year', v: c.year },
              { k: 'Outcome', v: c.outcome }
            ].map((t, i) => (
              <div key={i} style={{ padding: '40px 24px', borderRight: i < 3 ? '1px solid var(--ink-12)' : 'none' }}>
                <div className="eyebrow">{t.k}</div>
                <div style={{ marginTop: 16, fontFamily: 'var(--font-serif)', fontSize: 18, lineHeight: 1.3, letterSpacing: '-0.01em' }}>{t.v}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* Narrative */}
      <section className="section">
        <div className="shell" style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 80 }}>
          <Reveal>
            <div className="eyebrow">The Story</div>
          </Reveal>
          <div>
            {c.body.map((p, i) => (
              <Reveal key={i} delay={i*80}>
                <p className={i === 0 ? 'display-sm' : 'body-lg'} style={{ marginBottom: 32, fontWeight: 300, color: i === 0 ? 'var(--ink)' : 'var(--ink-60)', maxWidth: 720 }}>{p}</p>
              </Reveal>
            ))}
          </div>
        </div>
      </section>

      {/* Stat */}
      {c.stat && (
        <section style={{ padding: '120px var(--gutter)', background: 'var(--ink)', color: 'var(--paper)', textAlign: 'center' }}>
          <div className="shell">
            <Reveal><div className="display-xl" style={{ color: 'var(--accent-glow)' }}>{c.stat.value}</div></Reveal>
            <Reveal delay={100}><div className="eyebrow eyebrow-light" style={{ marginTop: 32 }}>{c.stat.label}</div></Reveal>
          </div>
        </section>
      )}

      {/* Work Showcase */}
      <section className="section-tight">
        <div className="shell">
          <Reveal><div className="eyebrow">The Work</div></Reveal>
          <Reveal delay={80}><h2 className="display-md" style={{ marginTop: 24, marginBottom: 64 }}>What it looked like.</h2></Reveal>

          {c.mediaKind === 'mail' || (c.pieces && c.pieces > 0) ? (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(12, 1fr)', gap: 24, rowGap: 48 }}>
              {Array.from({ length: c.pieces || 6 }).map((_, i) => {
                const cols = ['1/7', '7/13', '1/5', '5/9', '9/13', '1/7', '7/13', '1/13'];
                return (
                  <Reveal key={i} delay={i*40} style={{ gridColumn: cols[i % cols.length] }}>
                    <div style={{ aspectRatio: i % 3 === 0 ? '3/4' : '4/3' }}>
                      <MailPlaceholder piece={{ id: c.slug + '-p' + i, client: c.client, race: c.race }} idx={i+1} />
                    </div>
                    <div className="eyebrow" style={{ marginTop: 12 }}>Mail · No. {String(i+1).padStart(2,'0')}</div>
                  </Reveal>
                );
              })}
            </div>
          ) : null}

          {c.videos && c.videos.length > 0 && (
            <div style={{ marginTop: c.mediaKind === 'mail' ? 80 : 0, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 32, rowGap: 56 }}>
              {c.videos.map((v, i) => (
                <Reveal key={v.id} delay={i*60}>
                  <VideoEmbed id={v.id} title={v.title} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 16 }}>
                    <div>
                      <div className="work-card-title">{v.title}{v.lang ? <span style={{opacity:0.5, fontFamily:'var(--font-mono)', fontSize:11, marginLeft: 12}}>· {v.lang}</span> : ''}</div>
                      {v.caption && <div style={{ fontSize: 14, color: 'var(--ink-60)', marginTop: 4, maxWidth: 480 }}>{v.caption}</div>}
                    </div>
                    <div className="eyebrow">{v.length}</div>
                  </div>
                </Reveal>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* More work */}
      <section className="section section-paper-warm">
        <div className="shell">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 64 }}>
            <h2 className="display-md">More of our work.</h2>
            <Link to="/work" className="link-arrow">All case studies</Link>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24, rowGap: 56 }}>
            {others.slice(0, 8).map((o, i) => (
              <Link key={o.slug} to={`/work/${o.slug}`} className="work-card">
                <div className="work-card-media" style={{ aspectRatio: '4/5' }}>
                  {o.mediaKind === 'mail' ? <MailPlaceholder piece={{id:o.slug, client:o.client, race:o.race}} idx={i}/> : (
                    <img loading="lazy" src={`https://vumbnail.com/${o.videos[0].id}.jpg`} alt={o.client} style={{ width:'100%', height:'100%', objectFit:'cover' }} onError={(e)=>e.target.style.display='none'}/>
                  )}
                </div>
                <div className="work-card-title" style={{ marginTop: 12, fontSize: 16 }}>{o.client}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-60)', marginTop: 2 }}>{o.race}</div>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* Next */}
      <section style={{ background: 'var(--ink)', color: 'var(--paper)' }}>
        <Link to={`/work/${next.slug}`} style={{ display: 'block', padding: '120px var(--gutter)' }}>
          <div className="shell">
            <div className="eyebrow eyebrow-light">Next case study →</div>
            <h2 className="display-lg" style={{ marginTop: 24, fontStyle: 'italic', fontWeight: 300 }}>{next.client}</h2>
            <div style={{ marginTop: 16, opacity: 0.6 }}>{next.race} · {next.year}</div>
          </div>
        </Link>
      </section>

      <Footer />
    </>
  );
}

function MailPortfolioPage() {
  const D = window.TSD_DATA;
  const [filter, setFilter] = useState('all');
  const [lightbox, setLightbox] = useState(null);

  const tags = [
    { k: 'all', label: 'All' },
    { k: 'congressional', label: 'Congressional' },
    { k: 'mayoral', label: 'Mayoral' },
    { k: 'statewide', label: 'Statewide' },
    { k: 'state', label: 'State Leg.' },
    { k: 'local', label: 'Local' },
    { k: 'pac', label: 'PAC' },
    { k: 'advocacy', label: 'Advocacy' }
  ];
  const pieces = filter === 'all' ? D.mailPieces : D.mailPieces.filter(p => p.tag === filter);

  return (
    <>
      <Nav />
      <PageHeader
        eyebrow="§ Direct Mail Portfolio"
        title={<>A small sample, <span style={{fontStyle:'italic'}}>and that's just</span> a sample…</>}
        intro="Fifty-two pieces from across the country — congressional, mayoral, statewide, advocacy. The work is shown here at scale. Real artwork is being uploaded; placeholder cards represent layout and pacing." />

      <section style={{ padding: '0 var(--gutter) 24px' }}>
        <div className="shell" style={{ display: 'flex', flexWrap: 'wrap', gap: 8, paddingTop: 24, borderTop: '1px solid var(--ink-12)' }}>
          <span className="eyebrow" style={{ marginRight: 16, alignSelf: 'center' }}>Filter</span>
          {tags.map(t => (
            <button key={t.k} onClick={() => setFilter(t.k)} className={t.k === filter ? 'btn btn-primary' : 'btn btn-ghost'} style={{ padding: '8px 16px', fontSize: 13 }}>{t.label}</button>
          ))}
        </div>
      </section>

      <section className="section">
        <div className="shell">
          <div style={{ columnCount: 4, columnGap: 24 }}>
            {pieces.map((p, i) => {
              const tall = (i % 5 === 0 || i % 7 === 0);
              return (
                <button key={p.id + i} onClick={() => setLightbox(p)} style={{ display: 'block', width: '100%', breakInside: 'avoid', marginBottom: 24, padding: 0, textAlign: 'left', cursor: 'zoom-in' }}>
                  <div style={{ aspectRatio: tall ? '3/4' : '4/3', overflow: 'hidden' }}>
                    <MailPlaceholder piece={p} idx={i} />
                  </div>
                  <div className="work-card-meta" style={{ paddingTop: 10 }}>
                    <div>
                      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 14, fontWeight: 500 }}>{p.client}</div>
                      <div style={{ fontSize: 11, color: 'var(--ink-60)', marginTop: 2 }}>{p.race}</div>
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </section>

      {lightbox && (
        <div onClick={() => setLightbox(null)} style={{
          position: 'fixed', inset: 0, background: 'rgba(14,14,18,0.92)', backdropFilter: 'blur(20px)',
          zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 40, cursor: 'zoom-out'
        }}>
          <div style={{ maxWidth: '70vw', maxHeight: '85vh', width: 600, aspectRatio: '3/4', position: 'relative' }}>
            <MailPlaceholder piece={lightbox} idx={0} />
            <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, paddingTop: 24, color: 'var(--paper)', display: 'flex', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 22 }}>{lightbox.client}</div>
                <div style={{ opacity: 0.6, fontSize: 13, marginTop: 4 }}>{lightbox.race}</div>
              </div>
              {lightbox.case && <Link to={`/work/${lightbox.case}`} className="link-arrow" style={{ alignSelf: 'end' }}>Open case study</Link>}
            </div>
          </div>
          <button style={{ position: 'fixed', top: 32, right: 32, color: 'var(--paper)', fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.7 }}>Close ✕</button>
        </div>
      )}

      <Footer />
    </>
  );
}

function DigitalPortfolioPage() {
  const D = window.TSD_DATA;
  return (
    <>
      <Nav darkInitial />
      <section style={{ background: 'var(--ink)', color: 'var(--paper)', padding: '180px var(--gutter) 100px' }}>
        <div className="shell">
          <div className="eyebrow eyebrow-light">§ Digital Creative Portfolio</div>
          <h1 className="display-xl" style={{ marginTop: 32, maxWidth: 1300 }}>Next-level creative<br/>at an <span style={{ fontStyle: 'italic' }}>affordable</span> price point.</h1>
          <p className="body-lg" style={{ marginTop: 48, maxWidth: 720, opacity: 0.7 }}>
            A curated selection of work for clients big and small. We never sacrifice on production quality, and do all our creative in-house. Click any film to play with sound.
          </p>
        </div>
      </section>

      {D.videoGroups.map((group, gi) => (
        <section key={gi} style={{ padding: '80px var(--gutter)', borderTop: gi > 0 ? '1px solid var(--ink-12)' : 'none' }}>
          <div className="shell">
            <Reveal>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 48, flexWrap: 'wrap', gap: 24 }}>
                <div>
                  <div className="eyebrow">Chapter {String(gi+1).padStart(2,'0')}</div>
                  <h2 className="display-md" style={{ marginTop: 16 }}>{group.client}</h2>
                  <div style={{ color: 'var(--ink-60)', marginTop: 6 }}>{group.sub}</div>
                </div>
                {group.case && <Link to={`/work/${group.case}`} className="link-arrow">Read the case</Link>}
              </div>
            </Reveal>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(360px, 1fr))', gap: 24, rowGap: 56 }}>
              {group.vids.map((v, vi) => (
                <Reveal key={v.id} delay={vi*40}>
                  <VideoEmbed id={v.id} title={v.title} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12 }}>
                    <div>
                      <div className="work-card-title" style={{ fontSize: 16 }}>{v.title}</div>
                      {v.sub && <div style={{ fontSize: 12, color: 'var(--ink-60)', marginTop: 2 }}>{v.sub}</div>}
                    </div>
                    <div className="eyebrow">{v.year} · {v.length}</div>
                  </div>
                </Reveal>
              ))}
            </div>
          </div>
        </section>
      ))}

      <Footer />
    </>
  );
}

Object.assign(window, { WorkIndexPage, CaseStudyPage, MailPortfolioPage, DigitalPortfolioPage });
