// Direction 2 — "EDITORIAL DOSSIER"
// Newspaper of record. Refined serif headlines, two-column flow,
// numbered chapters, cream paper, single ink accent.

const D2 = {
  paper: '#f4f0e8',
  paper2: '#ebe5d8',
  ink: '#1a1814',
  ink2: '#3a342c',
  rule: '#cabfa8',
  rule2: '#a89b80',
  accent: '#9a3a1c',  // deep terracotta
  serif: '"Cormorant Garamond", "EB Garamond", Georgia, serif',
  display: '"Cormorant Garamond", Georgia, serif',
  sans: '"Inter", -apple-system, system-ui, sans-serif',
  mono: '"JetBrains Mono", ui-monospace, monospace',
};

function D2Frame({ children }) {
  return (
    <div style={{
      width: '100%', height: '100%', background: D2.paper, color: D2.ink,
      fontFamily: D2.serif, position: 'relative', overflow: 'hidden',
    }}>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400&display=swap" />
      {children}
    </div>
  );
}

function D2Mast({ active, onNav }) {
  const mobile = useIsMobile();
  return (
    <div style={{
      position: 'absolute', left: 0, right: 0, top: 0, height: 60,
      borderBottom: `1px solid ${D2.rule2}`, background: D2.paper,
      display: 'flex', alignItems: 'center',
      padding: mobile ? '0 12px' : '0 200px 0 40px', zIndex: 5, gap: 12,
    }}>
      <div style={{ fontFamily: D2.display,
        fontSize: mobile ? 14 : 22,
        letterSpacing: -0.3, fontWeight: 600, flexShrink: 0,
      }}>
        {mobile ? <>F<span style={{ color: D2.accent, fontStyle: 'italic' }}>&</span>Co.</> : <>Finsterbusch <span style={{ color: D2.accent, fontStyle: 'italic' }}>&</span> Co.</>}
      </div>
      <div style={{ flex: 1 }} />
      <div style={{
        display: 'flex', gap: mobile ? 12 : 28,
        fontFamily: D2.sans, fontSize: mobile ? 9 : 11, letterSpacing: mobile ? 1 : 2,
        overflowX: 'auto', flexShrink: 1, minWidth: 0,
      }}>
        {['HOME','INTRO','HISTORY','PORTFOLIO','CONTACT'].map(it => (
          <div key={it} onClick={() => onNav(it)} style={{
            cursor: 'pointer', textTransform: 'uppercase', paddingBottom: 4,
            color: active === it ? D2.accent : D2.ink2,
            borderBottom: `1px solid ${active === it ? D2.accent : 'transparent'}`,
            flexShrink: 0,
          }}>{it}</div>
        ))}
      </div>
    </div>
  );
}

function D2Home({ data, onNav }) {
  const mobile = useIsMobile();
  return (
    <div style={{ position: 'absolute', inset: '60px 0 0 0', padding: mobile ? '20px 16px' : '40px 60px 40px', overflow: 'auto' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.ink2, textTransform: 'uppercase' }}>
        <span>Vol. XX</span><span style={{ color: D2.rule2 }}>·</span>
        <span>Gothenburg</span><span style={{ color: D2.rule2 }}>·</span>
        <span>2026 Edition</span><span style={{ color: D2.rule2 }}>·</span>
        <span style={{ color: D2.accent }}>A Personal Dossier</span>
      </div>
      <div style={{ borderTop: `2px solid ${D2.ink}`, marginTop: 14, paddingTop: 18 }} />

      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1.4fr 1fr', gap: mobile ? 28 : 50 }}>
        <div>
          {data.heroUrl && (
            <div style={{ position: 'relative', marginBottom: 28, aspectRatio: '16 / 9', overflow: 'hidden' }}>
              <img src={data.heroUrl} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              <div style={{
                position: 'absolute', left: 0, right: 0, bottom: 0,
                padding: '14px 18px', background: 'linear-gradient(to top, rgba(0,0,0,0.55), transparent)',
                color: D2.paper, fontFamily: D2.sans, fontSize: 10, letterSpacing: 3,
              }}>№ 00 · A PERSONAL DOSSIER · 2026</div>
            </div>
          )}
          <div style={{
            fontFamily: D2.display, fontSize: mobile ? 52 : 96, lineHeight: 0.95, letterSpacing: mobile ? -1.5 : -2.5, fontWeight: 500,
          }}>
            Thirty years<br/>
            of <span style={{ fontStyle: 'italic', color: D2.accent }}>shipping</span><br/>
            the difficult<br/>
            things.
          </div>
          <div style={{ marginTop: mobile ? 20 : 28, fontFamily: D2.sans, fontSize: 13, color: D2.ink2, lineHeight: 1.7, maxWidth: 520, columnCount: mobile ? 1 : 2, columnGap: 28 }}>
            Nicolas Jens Finsterbusch is an AI technology consultant and delivery leader based in Gothenburg. His practice sits at the intersection of business strategy, programme delivery, and applied AI architecture: RAG, vector databases, LLM integration, and the structured systems that make AI safe to ship in regulated industries.
          </div>
        </div>

        <div style={{ borderLeft: mobile ? 'none' : `1px solid ${D2.rule}`, borderTop: mobile ? `1px solid ${D2.rule}` : 'none', paddingLeft: mobile ? 0 : 36, paddingTop: mobile ? 20 : 0 }}>
          <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.ink2, textTransform: 'uppercase', marginBottom: 12 }}>In this issue</div>
          {[
            ['I.',   'Intro',     'A short letter from the desk',         'INTRO'],
            ['II.',  'History',   'Buenos Aires → London → Gothenburg',   'HISTORY'],
            ['III.', 'Portfolio', 'Six dispatches from recent work',      'PORTFOLIO'],
            ['IV.',  'Contact',   'Correspondence & enquiry',             'CONTACT'],
          ].map(([n, t, s, target]) => (
            <div key={n} onClick={() => onNav && onNav(target)}
              style={{ display: 'flex', gap: 14, padding: '14px 0', borderTop: `1px solid ${D2.rule}`, cursor: 'pointer' }}>
              <div style={{ fontFamily: D2.display, fontStyle: 'italic', fontSize: 22, color: D2.accent, width: 36 }}>{n}</div>
              <div>
                <div style={{ fontFamily: D2.display, fontSize: 22, lineHeight: 1.1 }}>{t}</div>
                <div style={{ fontFamily: D2.sans, fontSize: 11, color: D2.ink2, marginTop: 2 }}>{s}</div>
              </div>
            </div>
          ))}

          <div style={{ marginTop: 28, padding: 18, background: D2.paper2, fontFamily: D2.sans, fontSize: 11, lineHeight: 1.6, color: D2.ink2 }}>
            <div style={{ letterSpacing: 2.5, fontSize: 9, color: D2.accent, marginBottom: 6 }}>NOTICE TO READERS</div>
            A nanobot lives at the bottom-right of this dossier. It speaks in the first person, as Nicolas, and will fetch things you ask for.
          </div>
        </div>
      </div>

      <div style={{
        marginTop: mobile ? 30 : 50, paddingTop: 24, borderTop: `1px solid ${D2.rule}`,
        display: 'grid', gridTemplateColumns: mobile ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: mobile ? 18 : 30,
      }}>
        {[
          ['30+', 'YEARS DELIVERING'],
          ['15', 'MARKETS LAUNCHED'],
          ['10–20', 'TYPICAL TEAM'],
          ['3', 'CONTINENTS LIVED IN'],
        ].map(([v, k]) => (
          <div key={k}>
            <div style={{ fontFamily: D2.display, fontSize: mobile ? 36 : 56, lineHeight: 1, color: D2.accent, fontWeight: 500 }}>{v}</div>
            <div style={{ fontFamily: D2.sans, fontSize: 9, letterSpacing: 2.5, color: D2.ink2, marginTop: 6 }}>{k}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function D2Intro({ data }) {
  const mobile = useIsMobile();
  return (
    <div style={{ position: 'absolute', inset: '60px 0 0 0', padding: mobile ? '24px 16px' : '50px 80px', overflow: 'auto' }}>
      <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.accent, marginBottom: 8 }}>CHAPTER I</div>
      <div style={{ fontFamily: D2.display, fontSize: mobile ? 36 : 64, lineHeight: 1.05, fontWeight: 500, letterSpacing: -1, maxWidth: 820 }}>
        A short <span style={{ fontStyle: 'italic' }}>letter</span> from<br/>the desk of Nicolas.
      </div>
      <div style={{ height: 1, background: D2.rule, margin: '24px 0' }} />

      <div style={{ display: 'grid',
        gridTemplateColumns: mobile ? '1fr' : (data.portraitUrl ? '240px 1fr 1fr' : '1fr 1fr'),
        gap: mobile ? 20 : 40,
        fontFamily: D2.serif, fontSize: mobile ? 15 : 17, lineHeight: 1.55, color: D2.ink2, alignItems: 'start' }}>
        {data.portraitUrl && (
          <figure onClick={() => window.NJF_LIGHTBOX.openSingle(data.portraitUrl, 'Nicolas, photographed in Gothenburg')}
            style={{ margin: 0, cursor: 'zoom-in' }}>
            <div style={{ aspectRatio: '4 / 5', overflow: 'hidden', background: D2.paper2 }}>
              <img src={data.portraitUrl} alt="Nicolas Finsterbusch"
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', filter: 'grayscale(0.15) contrast(1.02)' }} />
            </div>
            <figcaption style={{ marginTop: 10, fontFamily: D2.sans, fontSize: 10, letterSpacing: 2, color: D2.ink2, textTransform: 'uppercase' }}>
              Nicolas, photographed in Gothenburg
            </figcaption>
          </figure>
        )}
        <div>
          <span style={{ fontFamily: D2.display, fontSize: mobile ? 48 : 64, float: 'left', lineHeight: 0.85, marginRight: 8, marginTop: 6, color: D2.accent, fontWeight: 600 }}>I</span>
          {data.intro[0]}
        </div>
        <div>{data.intro[1]}</div>
      </div>
      <div style={{ marginTop: 24, fontFamily: D2.serif, fontSize: mobile ? 15 : 17, lineHeight: 1.55, color: D2.ink2, maxWidth: 820 }}>
        <span style={{ fontFamily: D2.display, fontStyle: 'italic', color: D2.accent }}>—</span> {data.intro[2]}
      </div>

      <div style={{ marginTop: mobile ? 32 : 48, paddingTop: 28, borderTop: `1px solid ${D2.rule}` }}>
        <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.ink2, marginBottom: 18 }}>FOUR PRACTICES</div>
        <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : 'repeat(4,1fr)', gap: mobile ? 22 : 28 }}>
          {data.pillars.map(p => (
            <div key={p.tag}>
              <div style={{ fontFamily: D2.display, fontSize: 36, color: D2.accent, fontStyle: 'italic', fontWeight: 500 }}>{p.tag}</div>
              <div style={{ fontFamily: D2.display, fontSize: 22, marginTop: 4, lineHeight: 1.15 }}>{p.title}</div>
              <div style={{ fontFamily: D2.sans, fontSize: 12, color: D2.ink2, marginTop: 10, lineHeight: 1.6 }}>{p.body}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function D2History({ data }) {
  const mobile = useIsMobile();
  return (
    <div style={{ position: 'absolute', inset: '60px 0 0 0', padding: mobile ? '24px 16px' : '50px 80px', overflow: 'auto' }}>
      <div style={{ display: mobile ? 'block' : 'flex', alignItems: 'flex-start', gap: 32 }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.accent, marginBottom: 8 }}>CHAPTER II</div>
          <div style={{ fontFamily: D2.display, fontSize: mobile ? 36 : 64, lineHeight: 1.05, fontWeight: 500, letterSpacing: -1 }}>
            A timeline, in <span style={{ fontStyle: 'italic' }}>chapters.</span>
          </div>
          <div style={{ fontFamily: D2.sans, fontSize: 12, color: D2.ink2, marginTop: 12 }}>
            Buenos Aires <span style={{ color: D2.accent }}>→</span> London <span style={{ color: D2.accent }}>→</span> Gothenburg.
          </div>
        </div>
        <a href={'https://' + data.linkedin} target="_blank" rel="noopener noreferrer" style={{
          fontFamily: D2.sans, fontSize: 10, letterSpacing: 2.5, color: D2.accent,
          textDecoration: 'none', whiteSpace: 'nowrap', textTransform: 'uppercase',
          borderBottom: `1px solid ${D2.accent}`, paddingBottom: 2, marginTop: 14,
          display: mobile ? 'inline-block' : undefined,
        }}>The full record on LinkedIn ↗</a>
      </div>

      <div style={{ marginTop: mobile ? 24 : 36, borderTop: `2px solid ${D2.ink}` }}>
        {data.history.map((h, i) => (
          <div key={i} style={{
            display: 'grid',
            gridTemplateColumns: mobile ? '90px 1fr' : '120px 1fr 1.6fr',
            gap: mobile ? 14 : 32,
            padding: mobile ? '16px 0' : '22px 0', borderBottom: `1px solid ${D2.rule}`,
          }}>
            <div style={{ fontFamily: D2.mono, fontSize: 11, color: D2.accent, paddingTop: 4 }}>{h.year}</div>
            <div>
              <div style={{ fontFamily: D2.display, fontSize: mobile ? 19 : 26, lineHeight: 1.1 }}>{h.role}</div>
              <div style={{ fontFamily: D2.sans, fontSize: 11, color: D2.ink2, marginTop: 4, letterSpacing: 1 }}>
                {h.org.toUpperCase()} · {h.place}
              </div>
              {mobile && <div style={{ fontFamily: D2.serif, fontSize: 14, lineHeight: 1.55, color: D2.ink2, marginTop: 8 }}>{h.note}</div>}
            </div>
            {!mobile && <div style={{ fontFamily: D2.serif, fontSize: 15, lineHeight: 1.55, color: D2.ink2 }}>{h.note}</div>}
          </div>
        ))}
      </div>
    </div>
  );
}

function D2Portfolio({ data }) {
  const [sel, setSel] = React.useState(null);
  const mobile = useIsMobile();
  if (sel !== null) {
    const p = data.projects[sel];
    return (
      <div style={{ position: 'absolute', inset: '60px 0 0 0', overflow: 'auto' }}>
        <div onClick={() => setSel(null)} style={{
          padding: mobile ? '14px 16px' : '20px 80px', fontFamily: D2.sans, fontSize: 11, letterSpacing: 2,
          color: D2.accent, cursor: 'pointer',
        }}>← BACK TO INDEX</div>
        <div style={{ padding: mobile ? '8px 16px 40px' : '20px 80px 60px', maxWidth: 980 }}>
          <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.ink2 }}>
            № {p.n} · {p.sector.toUpperCase()} · {p.year}
          </div>
          <div style={{ fontFamily: D2.display, fontSize: mobile ? 40 : 80, lineHeight: 1, fontWeight: 500, letterSpacing: mobile ? -0.8 : -1.5, marginTop: 12 }}>
            {p.title}
          </div>
          <div style={{ fontFamily: D2.display, fontStyle: 'italic', fontSize: 26, color: D2.accent, marginTop: 6 }}>
            {p.kicker}
          </div>
          {(p.live_url || p.liveUrl) && (
            <a href={p.live_url || p.liveUrl} target="_blank" rel="noopener noreferrer" style={{
              display: 'inline-block', marginTop: 16, fontFamily: D2.sans, fontSize: 11,
              letterSpacing: 2.5, color: D2.accent, textDecoration: 'none',
              borderBottom: `1px solid ${D2.accent}`, paddingBottom: 3,
              textTransform: 'uppercase',
            }}>Read live at {(p.live_url || p.liveUrl).replace(/^https?:\/\//, '').replace(/\/$/, '')} ↗</a>
          )}
          <div style={{ height: 1, background: D2.rule, margin: mobile ? '20px 0' : '32px 0' }} />
          <div style={{
            display: 'grid',
            gridTemplateColumns: mobile ? '1fr' : '1.4fr 1fr',
            gap: mobile ? 28 : 50,
          }}>
            <div>
              {p.cover_url && (
                <div onClick={() => window.NJF_LIGHTBOX.openProject(p, 0)} style={{
                  marginBottom: 28, position: 'relative', overflow: 'hidden',
                  aspectRatio: p.legacy ? '4 / 3' : '16 / 9',
                  background: D2.paper2, border: `1px solid ${D2.rule}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  cursor: 'zoom-in',
                }}>
                  <img src={p.cover_url} alt={p.title} style={{
                    width: '100%', height: '100%',
                    objectFit: p.legacy ? 'contain' : 'cover',
                    display: 'block',
                  }} />
                  <div style={{
                    position: 'absolute', left: 0, right: 0, bottom: 0,
                    padding: '12px 18px', background: 'linear-gradient(to top, rgba(0,0,0,0.6), transparent)',
                    color: D2.paper, fontFamily: D2.sans, fontSize: 9, letterSpacing: 2.5,
                  }}>FIG. № {p.n} · {p.title.toUpperCase()}</div>
                </div>
              )}
              <div style={{ fontFamily: D2.serif, fontSize: mobile ? 17 : 22, lineHeight: 1.5, color: D2.ink, marginBottom: 24 }}>
                <span style={{ fontFamily: D2.display, fontSize: mobile ? 48 : 64, float: 'left', lineHeight: 0.85, marginRight: 10, marginTop: 4, color: D2.accent, fontWeight: 600 }}>{p.summary[0]}</span>
                {p.summary.slice(1)}
              </div>
              <div style={{ fontFamily: D2.serif, fontSize: mobile ? 14 : 16, lineHeight: 1.7, color: D2.ink2 }}>{p.body}</div>

              {Array.isArray(p.gallery) && p.gallery.length > 0 && (
                <div style={{ marginTop: 32, paddingTop: 20, borderTop: `1px solid ${D2.rule}` }}>
                  <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.ink2, marginBottom: 14, textTransform: 'uppercase' }}>
                    Plates ({p.gallery.length})
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
                    {p.gallery.map((g, i) => {
                      const url = typeof g === 'string' ? g : g.url;
                      const cap = typeof g === 'string' ? null : g.caption;
                      const startIdx = (p.cover_url ? 1 : 0) + i;
                      return (
                        <figure key={i} onClick={() => window.NJF_LIGHTBOX.openProject(p, startIdx)}
                          style={{ margin: 0, cursor: 'zoom-in' }}>
                          <div style={{ aspectRatio: p.legacy ? '4 / 3' : '4 / 3', overflow: 'hidden', background: D2.paper2 }}>
                            <img src={url} alt={cap || ''} style={{ width: '100%', height: '100%', objectFit: p.legacy ? 'contain' : 'cover', display: 'block' }} />
                          </div>
                          {cap && <figcaption style={{ marginTop: 8, fontFamily: D2.serif, fontStyle: 'italic', fontSize: 12, color: D2.ink2 }}>{cap}</figcaption>}
                        </figure>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
            <div>
              {p.metrics.map((m, i) => (
                <div key={i} style={{ padding: '20px 0', borderBottom: `1px solid ${D2.rule}` }}>
                  <div style={{ fontFamily: D2.display, fontSize: 44, lineHeight: 1, color: D2.accent, fontWeight: 500 }}>{m.v}</div>
                  <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 2, color: D2.ink2, marginTop: 6, textTransform: 'uppercase' }}>{m.k}</div>
                </div>
              ))}
              <div style={{ marginTop: 18, display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {p.tags.map(t => (
                  <span key={t} style={{
                    fontFamily: D2.sans, fontSize: 10, padding: '4px 10px',
                    border: `1px solid ${D2.rule2}`, color: D2.ink2,
                  }}>{t}</span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const sectors = React.useMemo(
    () => ['All', ...Array.from(new Set(data.projects.map(p => p.sector).filter(Boolean)))],
    [data.projects]
  );
  const [filter, setFilter] = React.useState('All');
  const filtered = React.useMemo(
    () => filter === 'All' ? data.projects : data.projects.filter(p => p.sector === filter),
    [data.projects, filter]
  );
  const yearRange = React.useMemo(() => {
    const years = data.projects.map(p => parseInt((p.year || '').match(/\d{4}/g)?.[0] || 0)).filter(Boolean);
    if (!years.length) return '';
    const min = Math.min(...years), max = Math.max(...years);
    return min === max ? String(min) : `${min} — ${max}`;
  }, [data.projects]);
  const countWord = (n) => {
    const words = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Eleven','Twelve'];
    return words[n] || String(n);
  };

  return (
    <div style={{ position: 'absolute', inset: '60px 0 0 0', padding: mobile ? '24px 16px' : '50px 80px', overflow: 'auto' }}>
      <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.accent, marginBottom: 8 }}>CHAPTER III</div>
      <div style={{ fontFamily: D2.display, fontSize: mobile ? 36 : 64, lineHeight: 1.05, fontWeight: 500, letterSpacing: -1 }}>
        {countWord(data.projects.length)} <span style={{ fontStyle: 'italic' }}>dispatches.</span>
      </div>
      <div style={{ fontFamily: D2.sans, fontSize: 12, color: D2.ink2, marginTop: 12 }}>
        Selected work{yearRange ? `, ${yearRange}` : ''}. Click a dispatch to read.
      </div>

      <div style={{ marginTop: 28, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {sectors.map(s => (
          <div key={s} onClick={() => setFilter(s)} style={{
            fontFamily: D2.sans, fontSize: 10, letterSpacing: 2, padding: '6px 12px',
            cursor: 'pointer', textTransform: 'uppercase',
            border: `1px solid ${filter === s ? D2.accent : D2.rule2}`,
            color: filter === s ? D2.accent : D2.ink2,
            background: filter === s ? 'rgba(201,112,80,0.06)' : 'transparent',
          }}>{s}{filter === s && filter !== 'All' ? ` · ${filtered.length}` : ''}</div>
        ))}
      </div>

      {filtered.length === 0 && (
        <div style={{ marginTop: 40, fontFamily: D2.serif, fontStyle: 'italic', color: D2.ink2 }}>
          No dispatches in this filter.
        </div>
      )}

      <div style={{ marginTop: 28, borderTop: `2px solid ${D2.ink}` }}>
        {filtered.map((p) => {
          const i = data.projects.indexOf(p);
          return (
          <div key={p.id} onClick={() => setSel(i)} style={{
            display: 'grid',
            gridTemplateColumns: mobile ? '40px 1fr' : '60px 1fr 200px 100px',
            gap: mobile ? 12 : 24, padding: mobile ? '18px 0' : '26px 0', borderBottom: `1px solid ${D2.rule}`,
            cursor: 'pointer', alignItems: 'baseline',
          }}>
            <div style={{ fontFamily: D2.display, fontStyle: 'italic', fontSize: mobile ? 24 : 36, color: D2.accent, fontWeight: 500 }}>{p.n}</div>
            <div>
              <div style={{ fontFamily: D2.display, fontSize: mobile ? 22 : 32, lineHeight: 1.1, fontWeight: 500 }}>{p.title}</div>
              <div style={{ fontFamily: D2.serif, fontSize: mobile ? 13 : 14, color: D2.ink2, marginTop: 6, lineHeight: 1.5, maxWidth: 600 }}>
                <span style={{ fontStyle: 'italic', color: D2.accent }}>{p.kicker}.</span> {p.summary}
              </div>
              {mobile && <div style={{ marginTop: 6, fontFamily: D2.sans, fontSize: 10, letterSpacing: 1, color: D2.ink2 }}>
                {p.sector.toUpperCase()} · {p.year}
              </div>}
            </div>
            {!mobile && <div style={{ fontFamily: D2.sans, fontSize: 11, color: D2.ink2, letterSpacing: 1 }}>{p.sector.toUpperCase()}</div>}
            {!mobile && <div style={{ fontFamily: D2.mono, fontSize: 12, color: D2.ink2, textAlign: 'right' }}>{p.year} →</div>}
          </div>
          );
        })}
      </div>
    </div>
  );
}

function D2Contact({ data }) {
  const mobile = useIsMobile();
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [subject, setSubject] = React.useState('');
  const [message, setMessage] = React.useState('');
  const [status, setStatus] = React.useState('idle');

  const submit = async () => {
    if (!name.trim() || !email.trim() || !message.trim() || status === 'sending') return;
    setStatus('sending');
    const composed = subject.trim() ? `Subject: ${subject.trim()}\n\n${message.trim()}` : message.trim();
    const ok = window.NJF_NANOBOT && await window.NJF_NANOBOT.submitContact({
      name: name.trim(), email: email.trim(), message: composed,
      variant: window.NJF_AB && window.NJF_AB.getVariant(),
      referrer: document.referrer || null,
    });
    if (ok) {
      window.NJF_AB && window.NJF_AB.logEvent('contact', { source: 'form' });
      setStatus('sent'); setName(''); setEmail(''); setSubject(''); setMessage('');
    } else {
      setStatus('error');
    }
  };

  return (
    <div style={{ position: 'absolute', inset: '60px 0 0 0', padding: mobile ? '24px 16px' : '60px 80px', overflow: 'auto' }}>
      <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.accent, marginBottom: 8 }}>CHAPTER IV</div>
      <div style={{ fontFamily: D2.display, fontSize: mobile ? 40 : 80, lineHeight: 1, fontWeight: 500, letterSpacing: mobile ? -0.8 : -1.5, maxWidth: 900 }}>
        For <span style={{ fontStyle: 'italic' }}>correspondence</span><br/>
        & enquiry.
      </div>
      <div style={{ height: 1, background: D2.rule, margin: mobile ? '20px 0' : '36px 0' }} />

      <div style={{ display: 'grid', gridTemplateColumns: mobile ? '1fr' : '1fr 1fr', gap: mobile ? 32 : 60 }}>
        <div>
          <div style={{ fontFamily: D2.serif, fontSize: 18, lineHeight: 1.6, color: D2.ink2, marginBottom: 28 }}>
            I take on a small number of engagements per year. Typically applied AI architecture, governance-aware deployments, or fractional delivery leadership for regulated programmes. Write with what you're trying to ship.
          </div>
          {[
            ['Email', data.email],
            ['Telephone', data.phone],
            ['LinkedIn', '/in/nicolasfinsterbusch'],
            ['Studio', 'Gothenburg, Sweden'],
          ].map(([k, v]) => (
            <div key={k} style={{ padding: '14px 0', borderTop: `1px solid ${D2.rule}`, display: 'flex', alignItems: 'baseline' }}>
              <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 2.5, color: D2.ink2, width: 120, textTransform: 'uppercase' }}>{k}</div>
              <div style={{ fontFamily: D2.display, fontSize: 22, fontStyle: k==='Studio'?'italic':'normal' }}>{v}</div>
            </div>
          ))}
        </div>

        <div style={{ background: D2.paper2, padding: 32 }}>
          <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 3, color: D2.accent, marginBottom: 14 }}>SEND A NOTE</div>
          <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" style={d2Input} />
          <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" placeholder="Your email" style={d2Input} />
          <input value={subject} onChange={(e) => setSubject(e.target.value)} placeholder="Subject" style={d2Input} />
          <textarea value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Tell me what you're trying to ship..." style={{ ...d2Input, height: 120, resize: 'none' }} />
          <button onClick={submit} disabled={status === 'sending'} style={{
            marginTop: 6, padding: '14px 28px',
            background: status === 'sent' ? D2.accent : D2.ink, color: D2.paper,
            border: 'none', fontFamily: D2.sans, fontSize: 11, letterSpacing: 2.5,
            cursor: status === 'sending' ? 'wait' : 'pointer', opacity: status === 'sending' ? 0.6 : 1,
          }}>{
            status === 'sending' ? 'SENDING…' :
            status === 'sent'    ? '✓ NOTE RECEIVED' :
            status === 'error'   ? 'RETRY (DELIVERY FAILED)' :
                                   'SEND NOTE →'
          }</button>
          {status === 'error' && (
            <div style={{ marginTop: 12, fontSize: 12, color: D2.ink2, fontStyle: 'italic' }}>
              The post is delayed. Try email directly at {data.email}.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
const d2Input = {
  width: '100%', padding: '12px 0', background: 'transparent',
  border: 'none', borderBottom: `1px solid ${D2.rule2}`,
  fontFamily: D2.serif, fontSize: 16, color: D2.ink, outline: 'none',
  marginBottom: 14, display: 'block',
};

function D2Thinking({ color }) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setN(x => (x + 1) % 4), 350);
    return () => clearInterval(id);
  }, []);
  return <span style={{ color, opacity: 0.7, fontStyle: 'italic' }}>{'.'.repeat(n).padEnd(3, ' ')}</span>;
}

function D2Nanobot({ data, onNav }) {
  const mobile = useIsMobile();
  const [open, setOpen] = React.useState(!mobile);
  const [messages, setMessages] = React.useState([
    { from: 'bot', text: "Good day. I'm Nicolas. Well, a small version of him. Ask me anything about the dossier." },
  ]);
  const [input, setInput] = React.useState('');
  const ref = React.useRef(null);
  React.useEffect(() => { if (ref.current) ref.current.scrollTop = ref.current.scrollHeight; }, [messages]);

  const localRespond = (q) => {
    const lower = q.toLowerCase();
    let reply = "Nanobot is offline. Best to email nfinsterbusch@gmail.com.";
    if (/xc40/.test(lower)) reply = "The XC40 reveal (at AKQA, 2018) was the highest-performing digital launch in Volvo Cars history at the time. 4.77M sessions in 7 days.";
    else if (/clinical/.test(lower)) reply = "The clinical screening tool moved primary diagnostic accuracy from 47% to 84%, with full scoring trace and ICD codes. It abstains rather than fabricate.";
    else if (/history|career/.test(lower)) { reply = "Buenos Aires, London, Gothenburg. Thirty years. Turning to Chapter II."; setTimeout(() => onNav('HISTORY'), 600); }
    else if (/contact|reach|email/.test(lower)) { reply = "Best by email: nfinsterbusch@gmail.com. Turning to Chapter IV."; setTimeout(() => onNav('CONTACT'), 600); }
    else if (/portfolio|work|project/.test(lower)) { reply = "Six dispatches. Opening the index."; setTimeout(() => onNav('PORTFOLIO'), 600); }
    return reply;
  };

  const send = async () => {
    if (!input.trim()) return;
    const q = input.trim();
    const historyAtSend = messages;
    const pendingId = 'p_' + Date.now();
    setMessages(m => [...m, { from: 'me', text: q }, { from: 'bot', text: '', pending: true, id: pendingId }]);
    setInput('');
    let reply = null;
    if (window.NJF_NANOBOT) {
      reply = await window.NJF_NANOBOT.ask({
        message: q, history: historyAtSend, onNav,
        onChunk: (_chunk, full) => {
          setMessages(m => m.map(x => x.id === pendingId ? { ...x, text: full, pending: false } : x));
        },
      });
    }
    if (!reply) {
      reply = localRespond(q);
      setMessages(m => m.map(x => x.id === pendingId ? { from: 'bot', text: reply } : x));
    } else {
      setMessages(m => m.map(x => x.id === pendingId ? { from: 'bot', text: reply } : x));
    }
  };

  if (!open) {
    return (
      <div onClick={() => setOpen(true)} style={{
        position: 'absolute', right: 24, bottom: 24, width: 52, height: 52,
        background: D2.ink, color: D2.paper, cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontFamily: D2.display, fontSize: 22, fontStyle: 'italic',
        boxShadow: '0 8px 30px rgba(0,0,0,0.25)',
      }}>nf</div>
    );
  }

  return (
    <div style={mobile ? {
      position: 'fixed', left: 0, right: 0, bottom: 0, height: '70vh',
      background: D2.paper, borderTop: `1px solid ${D2.ink}`,
      display: 'flex', flexDirection: 'column', zIndex: 50,
      boxShadow: '0 -10px 40px rgba(0,0,0,0.2)',
    } : {
      position: 'absolute', right: 24, bottom: 24, width: 320, height: 380,
      background: D2.paper, border: `1px solid ${D2.ink}`,
      display: 'flex', flexDirection: 'column',
      boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
    }}>
      <div style={{
        padding: '12px 16px', borderBottom: `1px solid ${D2.rule}`,
        display: 'flex', alignItems: 'baseline', background: D2.ink, color: D2.paper,
      }}>
        <div style={{ fontFamily: D2.display, fontStyle: 'italic', fontSize: 18 }}>nf</div>
        <div style={{ fontFamily: D2.sans, fontSize: 10, letterSpacing: 2, marginLeft: 10 }}>NANOBOT</div>
        <div style={{ flex: 1 }} />
        <span onClick={() => setOpen(false)} style={{ cursor: 'pointer', fontSize: 14 }}>×</span>
      </div>

      <div ref={ref} style={{ flex: 1, overflow: 'auto', padding: 16, fontFamily: D2.serif, fontSize: 14, lineHeight: 1.5 }}>
        {messages.map((m, i) => (
          <div key={m.id || i} style={{ marginBottom: 12, color: m.from === 'bot' ? D2.ink : D2.ink2 }}>
            {m.from === 'bot' ? (
              <div style={{ whiteSpace: 'pre-wrap' }}>
                <span style={{ fontFamily: D2.display, fontStyle: 'italic', color: D2.accent, marginRight: 6 }}>—</span>
                {m.pending ? <D2Thinking color={D2.accent} /> : m.text}
              </div>
            ) : (
              <div style={{ fontFamily: D2.sans, fontSize: 12, color: D2.ink2, whiteSpace: 'pre-wrap' }}>You: {m.text}</div>
            )}
          </div>
        ))}
      </div>

      <div style={{ borderTop: `1px solid ${D2.rule}`, padding: 12, display: 'flex' }}>
        <input
          value={input} onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && send()}
          placeholder="Pose a question..."
          style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none',
            fontFamily: D2.serif, fontSize: 14, fontStyle: 'italic', color: D2.ink }}
        />
      </div>
    </div>
  );
}

function Direction2({ data }) {
  const [section, setSection] = React.useState('HOME');
  const sec = {
    HOME: <D2Home data={data} onNav={setSection} />, INTRO: <D2Intro data={data} />,
    HISTORY: <D2History data={data} />, PORTFOLIO: <D2Portfolio data={data} />,
    CONTACT: <D2Contact data={data} />,
  }[section];
  return (
    <D2Frame>
      <D2Mast active={section} onNav={setSection} />
      {sec}
      <D2Nanobot data={data} onNav={setSection} />
    </D2Frame>
  );
}

window.Direction2 = Direction2;
