/* Insights — list + article */
const { Container: IC, Reveal: IR, Eyebrow: IE, Mono: IM, PageHeader: IPH, CTABand: ICTA, PALETTE: IP } = window;

const ARTICLES = [
  { slug:'llm-seo-2026',     title:'LLM SEO in 2026: what changed when search stopped being one box.', topic:'AI Visibility', read:'9 min', date:'May 2026', author:'Maksym',     color: IP.purple },
  { slug:'entity-grade',     title:'Entity-grade content: how to be cited, not just indexed.',          topic:'AI Visibility', read:'7 min', date:'Apr 2026', author:'Editorial',  color: IP.magenta },
  { slug:'canada-expansion', title:'Quiet playbook for entering Canada from the EU.',                  topic:'International', read:'11 min',date:'Apr 2026', author:'Strategy',   color: IP.red },
  { slug:'ppc-after-ios',    title:'PPC after iOS attribution: the part nobody fixed.',                topic:'Performance',   read:'6 min', date:'Mar 2026', author:'Performance',color: IP.orange },
  { slug:'seo-versus-aeo',   title:'SEO, GEO, AEO: a clean glossary for marketing teams.',             topic:'AI Visibility', read:'5 min', date:'Mar 2026', author:'Editorial',  color: IP.blue },
  { slug:'automation-trap',  title:'The automation trap: when sequences kill conversion.',             topic:'Automation',    read:'8 min', date:'Feb 2026', author:'Strategy',   color: IP.green },
];

const TOPIC_COLORS = {
  'AI Visibility': IP.purple,
  'Performance':   IP.orange,
  'International': IP.red,
  'Automation':    IP.green,
};

function InsightsHub({ onNavigate, onOpenArticle }) {
  const [topic, setTopic] = useState('All');
  const topics = ['All','AI Visibility','Performance','International','Automation'];
  const filtered = topic === 'All' ? ARTICLES : ARTICLES.filter(a => a.topic === topic);
  const lead = filtered[0];
  const rest = filtered.slice(1);

  return (
    <main data-page-root>
      <IPH
        num="08"
        eyebrow="Insights · Editorial"
        title={<>NOTES FROM<br/>THE STUDIO.</>}
        lede="Working observations on AI visibility, international marketing, performance, and the parts of the craft that don't get written about elsewhere."
        color={IP.magenta}
        art="insights"
        breadcrumbs={[
          { label:'Home', onClick: () => onNavigate('home') },
          { label:'Insights' },
        ]}
      />

      <section className="py-8 border-b-2 border-ink sticky-strip bg-paper">
        <IC>
          <div className="flex items-center justify-between gap-6 flex-wrap">
            <div className="flex items-center gap-2 flex-wrap">
              {topics.map((t, i) => {
                const c = i === 0 ? IP.ink : TOPIC_COLORS[t];
                const active = topic === t;
                return (
                  <button key={t} onClick={() => setTopic(t)}
                    className={`num font-bold px-3.5 py-2 border-2 border-ink transition-colors ${active?'text-paper':'text-ink hover:bg-paper2'}`}
                    style={active?{background: c, color:'#fff'}:{}}>
                    {t}
                  </button>
                );
              })}
            </div>
            <div className="num text-mute">{filtered.length} articles</div>
          </div>
        </IC>
      </section>

      {/* Lead article */}
      {lead && (
        <section className="py-16 md:py-24 border-b-2 border-ink">
          <IC>
            <button onClick={() => onOpenArticle(lead.slug)} className="group block w-full text-left">
              <div className="grid grid-cols-12 gap-8 items-end">
                <div className="col-span-12 md:col-span-7">
                  <div className="flex items-center gap-3 mb-6 flex-wrap">
                    <span className="tag-chip" style={{borderColor: lead.color, color: lead.color}}>{lead.topic.toUpperCase()}</span>
                    <IM>{lead.read} · {lead.date}</IM>
                  </div>
                  <h2 className="display display-tight text-[40px] md:text-[88px] leading-[0.92] max-w-[20ch]">
                    {lead.title.toUpperCase()}
                  </h2>
                  <p className="mt-8 text-[16.5px] text-ink/75 leading-[1.6] max-w-[56ch]">
                    The interface collapsed. Ten blue links became one synthesized answer. The work of being visible — and being chosen — moved upstream into entity, structure, and citation.
                  </p>
                  <div className="mt-6 num font-bold text-ink">Read article →</div>
                </div>
                <div className="col-span-12 md:col-span-5">
                  <div className="aspect-[5/4] border-2 border-ink overflow-hidden relative" style={{background: lead.color}} data-asset={`insight-hero-${lead.slug}`}>
                    <div className="absolute inset-0 pointer-events-none" style={{
                      backgroundImage: 'linear-gradient(rgba(255,255,255,0.08) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.08) 1px, transparent 1px)',
                      backgroundSize: '32px 32px'
                    }}></div>
                    <div className="absolute inset-0 grid place-items-center p-6">
                      <span className="display text-[40px] md:text-[64px] text-paper text-center leading-[0.9]">{lead.topic.toUpperCase()}</span>
                    </div>
                  </div>
                </div>
              </div>
            </button>
          </IC>
        </section>
      )}

      {/* List */}
      <section className="py-16">
        <IC>
          <ul className="border-2 border-ink">
            {rest.map((a, i, arr) => (
              <li key={a.slug} className={i<arr.length-1?'border-b-2 border-ink':''}>
                <button onClick={() => onOpenArticle(a.slug)} className="w-full text-left grid grid-cols-12 gap-6 px-5 md:px-7 py-6 group hover:bg-paper2 transition-colors items-center">
                  <div className="col-span-2 md:col-span-1 flex items-center gap-3">
                    <span className="w-2.5 h-2.5 inline-block" style={{background: a.color}}></span>
                    <IM>{String(i+2).padStart(2,'0')}</IM>
                  </div>
                  <div className="col-span-12 md:col-span-7">
                    <h3 className="display text-[22px] md:text-[30px] leading-[1.05] group-hover:translate-x-1 transition-transform max-w-[40ch]">
                      {a.title.toUpperCase()}
                    </h3>
                  </div>
                  <div className="col-span-6 md:col-span-2">
                    <span className="num font-bold" style={{color: a.color}}>{a.topic}</span>
                  </div>
                  <div className="col-span-6 md:col-span-2 md:text-right">
                    <IM>{a.read} · {a.date}</IM>
                  </div>
                </button>
              </li>
            ))}
          </ul>
        </IC>
      </section>

      {/* Newsletter */}
      <section className="py-20 md:py-24 bg-paper2 border-y-2 border-ink">
        <IC>
          <div className="grid grid-cols-12 gap-8 items-end">
            <div className="col-span-12 md:col-span-7">
              <IE num="↘" label="Studio dispatch" color={IP.yellow} />
              <h3 className="display display-tight text-[36px] md:text-[64px] mt-6 max-w-[22ch]">
                ONE SHORT DISPATCH<br/>A MONTH. NOTHING ELSE.
              </h3>
            </div>
            <div className="col-span-12 md:col-span-5">
              <label className="block">
                <span className="num text-mute font-bold">Work email</span>
                <div className="flex items-end gap-3 mt-2">
                  <input type="email" placeholder="you@company.com" className="flex-1 bg-transparent border-b-2 border-ink pb-3 display-mix text-[18px] font-semibold focus:outline-none"/>
                  <button className="btn btn-primary btn-sq">Subscribe →</button>
                </div>
              </label>
              <div className="num text-mute mt-3">No tracking pixels · plain text · one click to leave.</div>
            </div>
          </div>
        </IC>
      </section>
    </main>
  );
}

function ArticleView({ slug, onNavigate, onBack }) {
  const a = ARTICLES.find(x => x.slug === slug) || ARTICLES[0];
  const related = ARTICLES.filter(x => x.slug !== a.slug && x.topic === a.topic).slice(0,2);
  return (
    <main data-page-root>
      <section className="pt-32 md:pt-40 pb-16 border-b-2 border-ink">
        <IC>
          <button onClick={onBack} className="num font-bold text-mute hover:text-ink mb-8">← All insights</button>
          <div className="flex items-center gap-3 mb-8 flex-wrap">
            <span className="tag-chip" style={{borderColor: a.color, color: a.color}}>{a.topic.toUpperCase()}</span>
            <IM>{a.read} · {a.date}</IM>
            <span className="w-1 h-1 rounded-full bg-rule"></span>
            <IM>By {a.author}</IM>
          </div>
          <h1 className="display display-tight text-[44px] md:text-[96px] leading-[0.92] max-w-[26ch]">
            {a.title.toUpperCase()}
          </h1>
        </IC>
      </section>

      <section className="py-20 md:py-24">
        <IC>
          <div className="grid grid-cols-12 gap-10">
            <aside className="col-span-12 md:col-span-3">
              <div className="sticky top-24">
                <IM>Sections</IM>
                <ul className="mt-4 space-y-2.5 text-[13.5px]">
                  {['Premise','What changed','The new ingredients','How to start','Closing'].map((s, i) => (
                    <li key={s} className="flex items-center gap-2">
                      <span className="w-1.5 h-1.5 inline-block" style={{background: [IP.red, IP.orange, IP.yellow, IP.green, IP.blue][i]}}></span>
                      <a href={`#s${i}`} className="text-mute hover:text-ink font-semibold ed-link">{String(i+1).padStart(2,'0')} {s}</a>
                    </li>
                  ))}
                </ul>
              </div>
            </aside>
            <article className="col-span-12 md:col-span-9 max-w-[68ch] space-y-10">
              <p className="display-mix text-[24px] md:text-[30px] leading-[1.35] font-medium">
                For a decade, marketing meant winning a results page. That page is collapsing into a single synthesized answer, generated by a model, drawing on whatever it can retrieve.
              </p>

              <div id="s0">
                <h2 className="display text-[28px]"><span style={{color: IP.red}}>01</span> &nbsp; PREMISE</h2>
                <p className="text-[17px] text-ink/80 leading-[1.7] mt-4">
                  If your buyer is asking ChatGPT, Claude, Gemini, or Perplexity before they ever land on your site, the relevant question is not your ranking. It’s whether the model considers you a credible answer to their question.
                </p>
              </div>

              <div id="s1">
                <h2 className="display text-[28px]"><span style={{color: IP.orange}}>02</span> &nbsp; WHAT CHANGED</h2>
                <p className="text-[17px] text-ink/80 leading-[1.7] mt-4">
                  Three quiet shifts: retrieval replaced browsing for many top-funnel questions. Citation became a higher-trust signal than position. And the cost of being absent from an answer compounded — the model doesn’t know what it cannot retrieve.
                </p>
                <blockquote className="my-8 pl-6 border-l-4" style={{borderColor: a.color}}>
                  <p className="display-mix text-[22px] md:text-[26px] leading-[1.35] font-medium">
                    “Models prefer what they can retrieve, structure, and corroborate. Most marketing pages were never written for any of those.”
                  </p>
                </blockquote>
              </div>

              <div id="s2">
                <h2 className="display text-[28px]"><span style={{color: IP.yellow}}>03</span> &nbsp; THE NEW INGREDIENTS</h2>
                <ol className="mt-4 space-y-2.5 text-[17px] text-ink/85 leading-[1.7]">
                  {['A resolvable entity definition.',
                    'Answer-first, retrievable content chunks.',
                    'An authority graph the model already trusts.',
                    'An update cadence that signals the source is alive.'].map((t, i) => (
                    <li key={t} className="flex items-baseline gap-3">
                      <span className="num font-bold w-6" style={{color: [IP.red, IP.orange, IP.green, IP.blue][i]}}>{String(i+1).padStart(2,'0')}</span>
                      <span>{t}</span>
                    </li>
                  ))}
                </ol>
              </div>

              <div id="s3">
                <h2 className="display text-[28px]"><span style={{color: IP.green}}>04</span> &nbsp; HOW TO START</h2>
                <p className="text-[17px] text-ink/80 leading-[1.7] mt-4">
                  Pull live model responses for your priority buyer questions. Score citation. Identify retrieval failures. Then design the smallest set of changes that move the needle — usually entity, schema, and a content refactor.
                </p>
              </div>

              <div id="s4">
                <h2 className="display text-[28px]"><span style={{color: IP.blue}}>05</span> &nbsp; CLOSING</h2>
                <p className="text-[17px] text-ink/80 leading-[1.7] mt-4">
                  This is not the end of SEO. It’s a new layer above it. Brands that move first will be the ones cited by default when the next buyer asks an assistant.
                </p>
              </div>

              <hr className="hr-fine border-2 border-ink" />

              <div className="flex items-start justify-between gap-6">
                <div>
                  <div className="num text-mute font-bold">Written by</div>
                  <div className="display text-[20px] mt-1">{a.author.toUpperCase()} · MARKETING MIX</div>
                </div>
                <button onClick={() => onNavigate('contact')} className="btn btn-primary btn-sq">Request audit →</button>
              </div>
            </article>
          </div>
        </IC>
      </section>

      {related.length > 0 && (
        <section className="py-20 bg-paper2 border-y-2 border-ink">
          <IC>
            <IE num="↘" label="Continue reading" color={IP.teal} />
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-10">
              {related.map(r => (
                <button key={r.slug} onClick={() => onBack(r.slug)} className="text-left group border-2 border-ink bg-paper p-6 relative overflow-hidden">
                  <div className="absolute top-0 left-0 right-0 h-2" style={{background: r.color}}></div>
                  <div className="num font-bold mt-2" style={{color: r.color}}>{r.topic.toUpperCase()} · {r.read} · {r.date}</div>
                  <h3 className="display text-[24px] md:text-[30px] mt-3 group-hover:translate-x-1 transition-transform max-w-[34ch] leading-[1.05]">{r.title.toUpperCase()}</h3>
                  <div className="num font-bold text-ink mt-4">Read →</div>
                </button>
              ))}
            </div>
          </IC>
        </section>
      )}

      <ICTA onNavigate={onNavigate} />
    </main>
  );
}

function InsightsPage({ onNavigate }) {
  const [openArticle, setOpenArticle] = useState(null);
  if (openArticle) return <ArticleView slug={openArticle} onNavigate={onNavigate} onBack={(slug) => { window.scrollTo(0,0); setOpenArticle(slug || null); }} />;
  return <InsightsHub onNavigate={onNavigate} onOpenArticle={(slug) => { window.scrollTo(0,0); setOpenArticle(slug); }} />;
}

Object.assign(window, { InsightsPage });
