/* Page components */

var ARTICLES = window.UTM_DATA.ARTICLES;
var PRESS = window.UTM_DATA.PRESS;
var NOTEBOOK = window.UTM_DATA.NOTEBOOK;
var TOPICS = window.UTM_DATA.TOPICS;
var INFOGRAPHICS = window.UTM_DATA.INFOGRAPHICS;

/* ---------- HOME ---------- */
function HomePage({ navigate }) {
  const featured = ARTICLES[0];
  const sideFeatured = ARTICLES.slice(1, 4);
  const latest = ARTICLES.slice(4);

  return (
    <div className="page">
      {/* HERO */}
      <section className="hero">
        <div className="hero-grid-bg"></div>
        <div className="container" style={{ position: 'relative' }}>
          <div className="hero-eyebrow">
            <span className="pulse"></span>
            <span className="mono" style={{ color: 'var(--ink-soft)' }}>Issue 042 · Published Friday</span>
          </div>
          <h1 className="hero-title">
            Science, looked at <em>up&nbsp;close</em> — and explained slowly.
          </h1>
          <p className="hero-lede">
            Field notes from a working scientist on regenerative medicine, science policy, open access, and the small surprising parts of research that the press release leaves out. New writing every Friday.
          </p>
          <div className="hero-actions">
            <button className="btn btn-primary" onClick={() => navigate('article', { article: featured.id })}>
              Read this week's piece
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14M13 6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <button className="btn btn-ghost" onClick={() => navigate('home', { scrollTo: 'newsletter' })}>
              Get the newsletter
            </button>
          </div>
          <div className="hero-meta-row">
            <div className="hero-stat"><div className="num">42</div><div className="label">Essays Published</div></div>
            <div className="hero-stat"><div className="num">8.4k</div><div className="label">Readers · Monthly</div></div>
            <div className="hero-stat"><div className="num">2.4k</div><div className="label">Newsletter Subs</div></div>
            <div className="hero-stat"><div className="num">9yr</div><div className="label">In the Lab</div></div>
          </div>
        </div>
      </section>

      {/* FEATURED */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">— Editor's Pick</div>
              <h2 className="section-title">This week, on the bench.</h2>
            </div>
            <a className="section-link" onClick={() => navigate('in-focus')}>Browse all essays →</a>
          </div>
          <div className="featured-grid">
            <article className="feat-hero" onClick={() => navigate('article', { article: featured.id })}>
              <div className="feat-cover">
                <CoverArt palette={featured.palette} motif={featured.motif} label={`#${featured.id}`} />
              </div>
              <div className="feat-meta">
                <span className="feat-cat">{featured.cat}</span>
                <span className="feat-time">{featured.readTime} min read · {featured.date}</span>
              </div>
              <h2 className="feat-title">{featured.title}</h2>
              <p className="feat-excerpt">{featured.deck}</p>
              <div className="byline"><span className="avatar"></span> Nathan Holwell · ACL Tissue Engineering Lab</div>
            </article>
            <div className="feat-side">
              {sideFeatured.map(a => (
                <article key={a.id} className="feat-mini" onClick={() => navigate('article', { article: a.id })}>
                  <div className="feat-mini-cover">
                    <CoverArt palette={a.palette} motif={a.motif} />
                  </div>
                  <div>
                    <div className="feat-meta" style={{ marginBottom: 6 }}>
                      <span className="mono" style={{ color: 'var(--accent-ink)' }}>{a.topic}</span>
                      <span className="feat-time">{a.readTime} min</span>
                    </div>
                    <h3>{a.title}</h3>
                    <p style={{ color: 'var(--ink-mute)', fontSize: 13.5, margin: 0 }}>{a.date}</p>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* LAB NOTEBOOK */}
      <section className="section" id="notebook">
        <div className="container">
          <div className="notebook">
            <div>
              <h4>The Lab Notebook</h4>
              <p className="nb-title">Quick notes, between essays.</p>
              <p className="muted" style={{ fontSize: 14, marginTop: 16 }}>One-line dispatches from the bench. Ugly truths, small wins, the occasional lab-coffee opinion.</p>
            </div>
            <div className="nb-entries">
              {NOTEBOOK.map((e, i) => (
                <div className="nb-entry" key={i}>
                  <span className="nb-date">{e.date}</span>
                  <span>{e.text}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* LATEST GRID */}
      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">— More From the Archive</div>
              <h2 className="section-title">Recent essays.</h2>
            </div>
            <a className="section-link" onClick={() => navigate('in-focus')}>See all →</a>
          </div>
          <div className="cards">
            {latest.map(a => (
              <article key={a.id} className="card" onClick={() => navigate('article', { article: a.id })}>
                <div className="card-cover"><CoverArt palette={a.palette} motif={a.motif} /></div>
                <div className="feat-meta">
                  <span className="feat-cat" style={{ background: 'var(--paper-2)', color: 'var(--ink)' }}>{a.topic}</span>
                  <span className="feat-time">{a.readTime} min · {a.date}</span>
                </div>
                <h3>{a.title}</h3>
                <p>{a.excerpt}</p>
              </article>
            ))}
          </div>
        </div>
      </section>

      {/* NEWSLETTER */}
      <section className="section" style={{ borderBottom: 0 }}>
        <div className="container">
          <Newsletter id="newsletter" />
        </div>
      </section>
    </div>
  );
}

/* ---------- IN FOCUS / BEYOND archive ---------- */
function ArchivePage({ navigate, filter }) {
  const [topic, setTopic] = React.useState('All');
  const [query, setQuery] = React.useState('');
  let articles = filter === 'beyond'
    ? ARTICLES.filter(a => a.cat === 'Beyond The Scope')
    : filter === 'in-focus' ? ARTICLES.filter(a => a.cat === 'In Focus') : ARTICLES;
  if (topic !== 'All') articles = articles.filter(a => a.topic === topic);
  if (query) articles = articles.filter(a => (a.title + a.deck + a.excerpt).toLowerCase().includes(query.toLowerCase()));
  const heading = filter === 'beyond' ? 'Beyond the Scope' : 'In Focus';
  const sub = filter === 'beyond'
    ? 'Long-form interviews and reporting that wander out of the lab.'
    : 'Essays on science policy, open access, regen-med, and the day-to-day weirdness of research.';

  return (
    <div className="page">
      <section style={{ padding: '64px 0 36px', borderBottom: '1px solid var(--rule)' }}>
        <div className="container">
          <div className="mono muted" style={{ marginBottom: 16 }}>— Archive · {articles.length} essays</div>
          <h1 className="hero-title" style={{ fontSize: 'clamp(48px, 6vw, 88px)', maxWidth: '20ch' }}>{heading}.</h1>
          <p className="hero-lede" style={{ marginBottom: 28 }}>{sub}</p>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
            <input
              placeholder="Search essays…"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              style={{
                padding: '12px 18px', borderRadius: 999, border: '1px solid var(--rule)',
                fontFamily: 'inherit', fontSize: 14, minWidth: 280, outline: 'none', background: 'var(--paper)'
              }}
            />
            <span className="mono muted">·</span>
            <div className="topics-row" style={{ marginBottom: 0 }}>
              {TOPICS.map(t => (
                <button key={t} className={`tag ${topic === t ? 'active' : ''}`} onClick={() => setTopic(t)}>
                  {topic === t && <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--accent)', display: 'inline-block' }}></span>}
                  {t}
                </button>
              ))}
            </div>
          </div>
        </div>
      </section>
      <section className="section" style={{ borderBottom: 0 }}>
        <div className="container">
          {articles.length === 0 ? (
            <div style={{ padding: '80px 0', textAlign: 'center' }}>
              <p className="serif" style={{ fontSize: 32 }}>No essays on that yet.</p>
              <p className="muted">Try another topic or clear the search.</p>
            </div>
          ) : (
            <div className="cards">
              {articles.map(a => (
                <article key={a.id} className="card" onClick={() => navigate('article', { article: a.id })}>
                  <div className="card-cover"><CoverArt palette={a.palette} motif={a.motif} /></div>
                  <div className="feat-meta">
                    <span className="feat-cat" style={{ background: 'var(--paper-2)', color: 'var(--ink)' }}>{a.topic}</span>
                    <span className="feat-time">{a.readTime} min · {a.date}</span>
                  </div>
                  <h3>{a.title}</h3>
                  <p>{a.excerpt}</p>
                </article>
              ))}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

/* ---------- ARTICLE READER ---------- */
function ArticlePage({ navigate, articleId }) {
  const a = ARTICLES.find(x => x.id === articleId) || ARTICLES[0];
  const related = ARTICLES.filter(x => x.id !== a.id && x.cat === a.cat).slice(0, 3);
  const [progress, setProgress] = React.useState(0);
  React.useEffect(() => {
    window.scrollTo(0, 0);
    const onScroll = () => {
      const h = document.documentElement;
      const total = h.scrollHeight - h.clientHeight;
      setProgress(total > 0 ? (h.scrollTop / total) : 0);
    };
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, [articleId]);

  return (
    <div className="page">
      <div className="read-progress" style={{ transform: `scaleX(${progress})` }}></div>

      <section className="article-hero">
        <div className="container">
          <div className="article-meta">
            <span style={{ color: 'var(--accent-ink)', background: 'var(--accent)', padding: '3px 8px', borderRadius: 3 }}>{a.cat}</span>
            <span>·</span>
            <span>{a.topic}</span>
            <span>·</span>
            <span>{a.readTime} min read</span>
            <span>·</span>
            <span>{a.date}</span>
          </div>
          <h1 className="article-title">{a.title}</h1>
          <p className="article-deck">{a.deck}</p>
          <div className="article-byline">
            <div className="byline">
              <span className="avatar" style={{ width: 36, height: 36 }}></span>
              <div>
                <div style={{ fontWeight: 600, color: 'var(--ink)' }}>Nathan Holwell</div>
                <div className="mono muted">Grad Student · Queen's University</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10 }}>
              {['Twitter', 'LinkedIn', 'Copy link'].map(s => (
                <button key={s} className="tag">{s}</button>
              ))}
            </div>
          </div>
        </div>
      </section>

      <div className="container" style={{ position: 'relative' }}>
        <div className="article-cover"><CoverArt palette={a.palette} motif={a.motif} label={`fig.01 · ${a.topic}`} /></div>
      </div>

      <article className="article-body">
        {a.body.map((b, i) => {
          if (typeof b === 'string') return <p key={i}>{b}</p>;
          if (b.type === 'h2') return <h2 key={i}>{b.text}</h2>;
          if (b.type === 'quote') return <blockquote key={i}>"{b.text}"</blockquote>;
          return null;
        })}
        <hr className="rule" style={{ margin: '48px 0' }} />
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}>
          <div className="byline">
            <span className="avatar" style={{ width: 44, height: 44 }}></span>
            <div>
              <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 15 }}>Written by Nathan Holwell</div>
              <div style={{ color: 'var(--ink-soft)', fontSize: 13.5, maxWidth: '50ch' }}>
                I research a better way to repair torn ACLs by mimicking native ligament structure and biology.
              </div>
            </div>
          </div>
          <button className="btn btn-accent" onClick={() => navigate('home', { scrollTo: 'newsletter' })}>
            Get the next one
          </button>
        </div>
      </article>

      <section className="section" style={{ background: 'var(--paper-2)' }}>
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">— Keep reading</div>
              <h2 className="section-title">Related essays.</h2>
            </div>
          </div>
          <div className="cards">
            {related.map(x => (
              <article key={x.id} className="card" onClick={() => navigate('article', { article: x.id })}>
                <div className="card-cover"><CoverArt palette={x.palette} motif={x.motif} /></div>
                <div className="feat-meta">
                  <span className="feat-cat" style={{ background: 'var(--paper)', color: 'var(--ink)' }}>{x.topic}</span>
                  <span className="feat-time">{x.readTime} min</span>
                </div>
                <h3>{x.title}</h3>
                <p>{x.excerpt}</p>
              </article>
            ))}
          </div>
        </div>
      </section>
    </div>
  );
}

/* ---------- ABOUT ---------- */
function AboutPage({ navigate }) {
  return (
    <div className="page">
      <section style={{ padding: '64px 0 0', borderBottom: '1px solid var(--rule)' }}>
        <div className="container">
          <div className="about-hero">
            <div>
              <div className="mono muted" style={{ marginBottom: 16 }}>— Hi, I'm Nathan</div>
              <h1 className="hero-title" style={{ fontSize: 'clamp(44px, 5.5vw, 80px)', maxWidth: '14ch', marginBottom: 20 }}>
                Grad student by day. <em>Slow writer</em> by Friday.
              </h1>
              <p className="hero-lede" style={{ marginBottom: 24 }}>
                I'm a graduate student at Queen's University in Kingston, Canada. I'm researching a better way to repair torn anterior cruciate ligaments by mimicking both the biology and structure of native ACLs. When I'm not in the lab, I write here.
              </p>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <button className="btn btn-primary" onClick={() => navigate('about', { scrollTo: 'contact' })}>Get in touch</button>
                <button className="btn btn-ghost">Download CV</button>
              </div>
            </div>
            <div className="about-portrait">
              <svg viewBox="0 0 320 400" preserveAspectRatio="xMidYMid slice" style={{ width: '100%', height: '100%' }}>
                <rect width="320" height="400" fill="var(--paper-2)" />
                {Array.from({ length: 22 }).map((_, i) => (
                  <line key={i} x1="0" y1={i * 20} x2="320" y2={i * 20} stroke="var(--rule)" strokeWidth="0.6" />
                ))}
                <circle cx="160" cy="160" r="78" fill="oklch(82% 0.19 130)" opacity="0.6" />
                <text x="160" y="380" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="var(--ink-mute)" textAnchor="middle" letterSpacing="2">
                  PORTRAIT · DROP IMAGE HERE
                </text>
              </svg>
            </div>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">— Why this exists</div>
              <h2 className="section-title">Mission.</h2>
            </div>
          </div>
          <div className="about-mission">
            <div className="mission-card">
              <div className="num">01</div>
              <h4>Create.</h4>
              <p>Build tools, charts, and short essays that deliver science cleanly — without dumbing it down or hiding the hard parts.</p>
            </div>
            <div className="mission-card">
              <div className="num">02</div>
              <h4>Educate.</h4>
              <p>Pick interesting, relevant news and explain it slowly enough to actually be useful, fast enough to still be relevant.</p>
            </div>
            <div className="mission-card">
              <div className="num">03</div>
              <h4>Elevate.</h4>
              <p>Help readers ask sharper questions about the science they encounter, so the public conversation about research keeps up.</p>
            </div>
          </div>
        </div>
      </section>

      <section className="section" id="press">
        <div className="container">
          <div className="press">
            <div>
              <div className="mono muted" style={{ marginBottom: 8 }}>— Bylines</div>
              <h2 className="section-title" style={{ marginTop: 0 }}>Drug Discovery News.</h2>
              <p className="muted" style={{ marginTop: 16, maxWidth: '36ch' }}>Selected reporting I've contributed elsewhere. Click through for the full story.</p>
            </div>
            <div className="press-list">
              {PRESS.map((p, i) => (
                <div className="press-item" key={i}>
                  <h3 className="press-headline">{p.title}</h3>
                  <span className="press-meta">{p.pub} · {p.date}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <section className="section" id="contact" style={{ borderBottom: 0 }}>
        <div className="container">
          <div className="section-head">
            <div>
              <div className="eyebrow">— Say hi</div>
              <h2 className="section-title">Got a tip, a paper, a question?</h2>
            </div>
          </div>
          <ContactForm />
        </div>
      </section>
    </div>
  );
}

function ContactForm() {
  const [data, setData] = React.useState({ name: '', email: '', topic: 'A tip', message: '' });
  const [sent, setSent] = React.useState(false);
  const set = (k) => (e) => setData(d => ({ ...d, [k]: e.target.value }));
  const inputStyle = {
    width: '100%', padding: '14px 16px', border: '1px solid var(--rule)', borderRadius: 6,
    fontFamily: 'inherit', fontSize: 15, background: 'var(--paper)', outline: 'none',
  };
  if (sent) {
    return (
      <div style={{ padding: '64px', textAlign: 'center', background: 'var(--paper-2)', borderRadius: 8, border: '1px solid var(--rule)' }}>
        <div style={{ fontSize: 56 }}>✓</div>
        <h3 className="serif" style={{ fontSize: 32, margin: '12px 0 8px' }}>Thanks, {data.name || 'friend'}.</h3>
        <p className="muted">I read every message. You'll hear back within a week.</p>
      </div>
    );
  }
  return (
    <form
      style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18, maxWidth: 760 }}
      onSubmit={(e) => { e.preventDefault(); setSent(true); }}>
      <div>
        <label className="mono muted" style={{ display: 'block', marginBottom: 6 }}>Name</label>
        <input style={inputStyle} value={data.name} onChange={set('name')} required />
      </div>
      <div>
        <label className="mono muted" style={{ display: 'block', marginBottom: 6 }}>Email</label>
        <input style={inputStyle} type="email" value={data.email} onChange={set('email')} required />
      </div>
      <div style={{ gridColumn: 'span 2' }}>
        <label className="mono muted" style={{ display: 'block', marginBottom: 6 }}>About</label>
        <select style={inputStyle} value={data.topic} onChange={set('topic')}>
          <option>A tip</option><option>A correction</option><option>A speaking invite</option><option>Just saying hi</option>
        </select>
      </div>
      <div style={{ gridColumn: 'span 2' }}>
        <label className="mono muted" style={{ display: 'block', marginBottom: 6 }}>Message</label>
        <textarea style={{ ...inputStyle, minHeight: 140, resize: 'vertical', fontFamily: 'inherit' }} value={data.message} onChange={set('message')} required />
      </div>
      <button className="btn btn-primary" type="submit" style={{ justifySelf: 'start', gridColumn: 'span 2' }}>Send message</button>
    </form>
  );
}

/* ---------- INFOGRAPHICS ---------- */
function InfographicsPage() {
  return (
    <div className="page">
      <section style={{ padding: '64px 0 36px', borderBottom: '1px solid var(--rule)' }}>
        <div className="container">
          <div className="mono muted" style={{ marginBottom: 16 }}>— Visuals</div>
          <h1 className="hero-title" style={{ fontSize: 'clamp(48px, 6vw, 88px)', maxWidth: '20ch' }}>Infographics.</h1>
          <p className="hero-lede">Single-image explainers. Sometimes a chart says it; usually a chart needs a paragraph; occasionally a paragraph needs a chart. Built mostly in BioRender.</p>
        </div>
      </section>
      <section className="section" style={{ borderBottom: 0 }}>
        <div className="container">
          <div className="gallery">
            {INFOGRAPHICS.map((g, i) => {
              const palettes = [
                ['#F4F1EA', '#1F2937', '#7BC47F'],
                ['#FCE38A', '#0E1A2B', '#D4423E'],
                ['#E6F0FF', '#2A3D66', '#7BC47F'],
                ['#FFE5E0', '#0E1A2B', '#F4D35E'],
                ['#E8F5E9', '#1B5E20', '#D4423E'],
                ['#F5E6FF', '#3D2A66', '#7BC47F'],
              ];
              const motifs = ['wave', 'cell', 'globe', 'dna', 'flask', 'gear'];
              return (
                <div key={i}>
                  <div style={{ height: g.h }}>
                    <CoverArt palette={palettes[i % palettes.length]} motif={motifs[i % motifs.length]} />
                  </div>
                  <div className="gallery-cap">
                    {g.title} <span style={{ opacity: 0.6 }}>· {g.pub}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>
    </div>
  );
}

window.HomePage = HomePage;
window.ArchivePage = ArchivePage;
window.ArticlePage = ArticlePage;
window.AboutPage = AboutPage;
window.InfographicsPage = InfographicsPage;
