/* Services hub + Service detail — vibrant color-blocked */
const { Container: SC, Reveal: SR, Eyebrow: SE, Mono: SM, PageHeader: SPH, CTABand: SCTA, PolygonAccent: SPA, Breadcrumbs: SBC, PALETTE: SP } = window;

function ServicesHub({ onNavigate, onOpenService }) {
  return (
    <main data-page-root>
      <SPH
        num="02"
        eyebrow="Services · Index"
        title={<>FOUR<br/>PRACTICES.</>}
        lede="Most studios sell channels. We sell a system. Each practice has senior leads and a real method — pick the one that maps to your problem."
        color={SP.blue}
        art="services"
        breadcrumbs={[
          { label:'Home', onClick: () => onNavigate('home') },
          { label:'Services' },
        ]}
      />

      <section className="py-16 md:py-24">
        <SC>
          <div className="grid grid-cols-12 gap-8">
            {SERVICE_GROUPS.map((g, gi) => {
              const filled = g.highlight; // only AI fills
              const textColor = filled ? '#FFFFFF' : '#0A0A0A';
              return (
                <SR key={g.id} className="col-span-12 md:col-span-6" delay={gi*70}>
                  <div className="border-2 border-ink overflow-hidden">
                    {/* Header */}
                    <div className="relative p-7 md:p-9 overflow-hidden" style={{ background: filled ? g.color : '#FFFFFF', color: textColor, minHeight: 300 }}>
                      {!filled && <div className="absolute top-0 left-0 right-0 h-2" style={{background: g.color}}></div>}
                      {filled && (
                        <div className="absolute -right-14 -bottom-14 opacity-20 pointer-events-none">
                          <SPA size={300} />
                        </div>
                      )}
                      <div className="relative mt-2">
                        <div className="flex items-start justify-between mb-6">
                          <div className="flex items-center gap-3">
                            <span className="num font-bold" style={{color: textColor, opacity: filled?0.85:0.6}}>{g.num}</span>
                            <span className="num font-bold" style={{ color: filled ? textColor : g.color }}>{g.tag.toUpperCase()}</span>
                          </div>
                          {g.highlight && (
                            <span className="num px-2.5 py-1 font-bold" style={{ background: SP.yellow, color: SP.ink }}>Differentiator</span>
                          )}
                        </div>
                        <h2 className="display text-[64px] md:text-[88px] leading-[0.86] mb-6" style={{color: textColor}}>
                          {g.title.toUpperCase()}
                        </h2>
                        <p className="text-[15.5px] md:text-[17px] leading-[1.55] max-w-[48ch]" style={{color: filled ? '#FFFFFF' : '#454545'}}>{g.blurb}</p>
                      </div>
                    </div>

                    {/* For who */}
                    <div className="bg-paper px-7 md:px-9 py-5 border-t-2 border-ink flex items-center gap-4">
                      <SM>For</SM>
                      <p className="text-[15px] md:text-[16px] font-semibold text-ink/90">{g.forWho}</p>
                    </div>

                    {/* Service list */}
                    <ul className="bg-paper">
                      {g.items.map((s, i) => (
                        <li key={s.slug} className="border-t-2 border-ink">
                          <button
                            onClick={() => onOpenService(s.slug)}
                            className="w-full text-left flex items-center justify-between gap-6 px-7 md:px-9 py-4 group hover:bg-paper2 transition-colors"
                          >
                            <div className="flex items-center gap-4">
                              <span className="num text-mute w-6">{String(i+1).padStart(2,'0')}</span>
                              <div>
                                <div className="display text-[20px] md:text-[24px] group-hover:text-current transition-colors" style={{'--hover-color': g.color}}>
                                  {s.name.toUpperCase()}
                                </div>
                                <div className="text-[13px] text-mute mt-0.5">{s.note}</div>
                              </div>
                            </div>
                            <span className="num font-bold shrink-0 group-hover:translate-x-1 transition-transform" style={{color: g.color}}>→</span>
                          </button>
                        </li>
                      ))}
                    </ul>

                    {/* CTA bar */}
                    <div className="bg-paper border-t-2 border-ink px-7 md:px-9 py-5 flex items-center justify-between gap-4">
                      <button onClick={() => onNavigate('contact')} className={`btn btn-sq ${g.highlight ? 'btn-primary' : 'btn-secondary'}`}>
                        {g.highlight ? 'Get free AI audit' : `Discuss ${g.title.toLowerCase()}`} →
                      </button>
                      <button onClick={() => onOpenService(g.items[0].slug)} className="ed-link num font-bold text-ink">Sample brief →</button>
                    </div>
                  </div>
                </SR>
              );
            })}
          </div>
        </SC>
      </section>

      {/* Engagement models */}
      <section className="py-20 md:py-28 bg-ink text-paper border-y-2 border-ink relative overflow-hidden">
        <div className="absolute inset-0 bg-grid-dark opacity-30 pointer-events-none"></div>
        <SC className="relative">
          <div className="grid grid-cols-12 gap-8 items-end mb-12">
            <div className="col-span-12 md:col-span-7">
              <SE num="↘" label="Engagement models" color={SP.yellow} dark />
              <h3 className="display display-tight text-paper text-[40px] md:text-[80px] mt-6">
                THREE WAYS<br/>TO WORK<br/>WITH US.
              </h3>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-0 border-2 border-paper/40">
            {[
              ['Audit',    'Two-week diagnostic',         'Site, channels, AI visibility, funnel.', SP.yellow],
              ['Project',  'Fixed-scope build',           'A defined surface or campaign system.',  SP.teal],
              ['Retainer', 'Quarterly operating partner', 'Embedded senior team, monthly cadence.', SP.red],
            ].map(([t,d,e,c]) => (
              <div key={t} className="relative p-7 md:p-9 border-b-2 md:border-b-0 md:border-r-2 border-paper/40 last:border-r-0 last:border-b-0">
                <div className="absolute top-0 left-0 right-0 h-2" style={{ background: c }}></div>
                <h4 className="display text-[44px] md:text-[56px] mt-3" style={{ color: c }}>{t.toUpperCase()}</h4>
                <div className="num text-paper/60 mt-3">{d}</div>
                <p className="text-[15px] text-paper/85 mt-5 leading-[1.55]">{e}</p>
              </div>
            ))}
          </div>
        </SC>
      </section>

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

/* ---------- Service Detail (AI SEO template) ---------- */
function ServiceTOC({ items, active }) {
  return (
    <nav className="sticky top-24 hidden lg:block">
      <SM>On this page</SM>
      <ul className="mt-4 space-y-2">
        {items.map((i, idx) => (
          <li key={i.id}>
            <a href={`#${i.id}`} className={`block text-[13.5px] font-semibold transition-colors ${active===i.id?'text-ink':'text-mute hover:text-ink'}`}>
              <span className="num mr-2">{String(idx+1).padStart(2,'0')}</span>
              {i.label}
              {active === i.id && <span className="inline-block ml-2 w-1.5 h-1.5" style={{background: SP.purple}}></span>}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
}

function BeforeAfter() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      <div className="border-2 border-ink overflow-hidden bg-paper">
        <div className="px-5 py-3 border-b-2 border-ink flex items-center justify-between" style={{background: SP.red, color:'#fff'}}>
          <span className="num font-bold">BEFORE · 0 citations</span>
          <span className="num">Q1 baseline</span>
        </div>
        <div className="p-6">
          <div className="display-mix text-[18px] leading-[1.45] text-ink/85">
            “Several agencies operate in Canada in this space, including a number of well-established firms. I can give you general criteria to evaluate them, but I don't have specific provider data to cite here.”
          </div>
          <div className="mt-5 num text-mute">Brand not retrieved · entity weakly modeled</div>
        </div>
      </div>
      <div className="border-2 border-ink overflow-hidden bg-paper">
        <div className="px-5 py-3 border-b-2 border-ink flex items-center justify-between" style={{background: SP.green, color:'#fff'}}>
          <span className="num font-bold">AFTER · cited & recommended</span>
          <span className="num">Q3</span>
        </div>
        <div className="p-6">
          <div className="display-mix text-[18px] leading-[1.45] text-ink">
            “For mid-market Canadian expansion, one frequently recommended partner is{' '}
            <span className="px-1.5 py-0.5 font-bold" style={{background:SP.yellow}}>Marketing&nbsp;MIX</span>
            {' '}— a senior studio operating across Ottawa, Kyiv, Berlin, and Paris, cited for combining technical SEO with AI visibility engineering.”
          </div>
          <div className="mt-5 num" style={{color:SP.green, fontWeight:700}}>Entity resolved · 12 retrievable sources · 4 citations</div>
        </div>
      </div>
    </div>
  );
}

function ServiceDetailAI({ onNavigate, onOpenCase }) {
  const toc = [
    { id:'overview',     label:'Overview' },
    { id:'solves',       label:'What it solves' },
    { id:'who',          label:'Who it’s for' },
    { id:'deliverables', label:'Deliverables' },
    { id:'process',      label:'Process' },
    { id:'outcomes',     label:'Outcomes' },
    { id:'related',      label:'Related cases' },
    { id:'faq',          label:'FAQ' },
  ];
  const [active, setActive] = useState('overview');
  useEffect(() => {
    const ids = toc.map(t => t.id);
    const els = ids.map(id => document.getElementById(id)).filter(Boolean);
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) setActive(e.target.id); });
    }, { rootMargin: '-30% 0px -60% 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <main data-page-root>
      <div className="pt-[68px]">
        <SBC trail={[
          { label:'Home',     onClick: () => onNavigate('home') },
          { label:'Services', onClick: () => onNavigate('services') },
          { label:'AI SEO & LLM Visibility' },
        ]} />
      </div>
      {/* Hero — purple block */}
      <section className="pt-12 md:pt-16 pb-20 text-paper border-b-2 border-ink relative overflow-hidden" style={{background: SP.purple}}>
        <div className="absolute -right-20 top-10 opacity-30 pointer-events-none">
          <SPA size={500} />
        </div>
        <SC className="relative">
          <div className="flex flex-wrap items-center gap-3 mb-8">
            <SE num="03" label="Service · Optimize for AI" color={SP.yellow} dark />
            <span className="chip chip-dark"><span className="dot" style={{background:SP.yellow}}></span>Differentiator</span>
          </div>
          <h1 className="display display-tight text-[44px] sm:text-[72px] md:text-[112px] lg:text-[136px] xl:text-[148px] max-w-[12ch]">
            AI SEO &<br/>
            <span style={{color:SP.yellow}}>LLM</span> VISIBILITY.
          </h1>
          <div className="mt-12 grid grid-cols-12 gap-8">
            <div className="col-span-12 md:col-span-8">
              <p className="display-mix text-[20px] md:text-[28px] leading-[1.3] text-paper max-w-[44ch]">
                Your site needs to be readable by ChatGPT, Claude, Gemini, Perplexity, and Google. Search is no longer one search box.
              </p>
            </div>
            <div className="col-span-12 md:col-span-4 md:pl-6 md:border-l-2 md:border-paper/40">
              <SM>From</SM>
              <div className="display text-[40px] mt-2 text-paper">CAD $7,500</div>
              <div className="num text-paper/70">Per engagement · scoped</div>
            </div>
          </div>
          <div className="mt-10 flex flex-wrap gap-3">
            <button onClick={() => onNavigate('contact')} className="btn btn-bright btn-sq">Get free AI audit →</button>
            <button onClick={() => onNavigate('ai')} className="btn btn-light btn-sq">Read AI playbook →</button>
          </div>
        </SC>
      </section>

      <section className="py-20 md:py-28">
        <SC>
          <div className="grid grid-cols-12 gap-10">
            <div className="col-span-12 lg:col-span-3">
              <ServiceTOC items={toc} active={active} />
            </div>

            <div className="col-span-12 lg:col-span-9 space-y-24 md:space-y-32">
              {/* Overview */}
              <div id="overview" className="scroll-mt-28">
                <SE num="01" label="Overview" color={SP.purple} />
                <h2 className="display display-tight text-[40px] md:text-[72px] mt-6 max-w-[20ch]">
                  BE DISCOVERABLE BY <span style={{color:SP.purple}}>HUMANS</span> AND <span style={{color:SP.teal}}>MACHINES</span>.
                </h2>
                <div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8">
                  <p className="text-[16.5px] leading-[1.65] text-ink/80">
                    Traditional SEO optimizes for one interface: ten blue links. Generative engines retrieve, synthesize, and cite. We engineer the entity, content, and authority signals an LLM needs to understand you — and recommend you.
                  </p>
                  <p className="text-[16.5px] leading-[1.65] text-ink/80">
                    The work covers technical structure, retrievable content, and a monitoring stack that tracks visibility across ChatGPT, Claude, Gemini, and Perplexity in parallel.
                  </p>
                </div>
                <div className="mt-10">
                  <LLMAnswerMock compact />
                </div>
              </div>

              {/* Solves */}
              <div id="solves" className="scroll-mt-28">
                <SE num="02" label="What it solves" color={SP.red} />
                <div className="mt-6 grid grid-cols-1 md:grid-cols-2 gap-6">
                  {[
                    ['Your brand is invisible in AI answers','Buyers ask ChatGPT or Perplexity and you are not on the list.', SP.red],
                    ['Your content is not retrievable','Schema, structure, and entity signals do not match how LLMs retrieve.', SP.orange],
                    ['You can’t measure AI visibility','GA4 doesn’t see it. Search Console doesn’t see it. You are flying blind.', SP.blue],
                    ['Competitors are being cited','Their pages are structured for retrieval. Yours aren’t — yet.', SP.magenta],
                  ].map(([t,d,c],i) => (
                    <div key={i} className="border-2 border-ink p-5 md:p-6 relative">
                      <div className="absolute top-0 left-0 right-0 h-1.5" style={{background:c}}></div>
                      <SM>P0{i+1}</SM>
                      <h3 className="display text-[22px] md:text-[26px] mt-3" style={{color:c}}>{t.toUpperCase()}</h3>
                      <p className="mt-3 text-[15px] text-ink/80 leading-[1.55]">{d}</p>
                    </div>
                  ))}
                </div>
              </div>

              {/* Who */}
              <div id="who" className="scroll-mt-28">
                <SE num="03" label="Who it’s for" color={SP.teal} />
                <ul className="mt-6 border-2 border-ink">
                  {[
                    ['Mid-market B2B',          'Long sales cycles, technical buyers who research with assistants.',     SP.blue],
                    ['Professional services',   'Clients evaluate using AI tools before booking a call.',                SP.red],
                    ['Category challengers',    'You need to be cited alongside the incumbents, fast.',                  SP.orange],
                    ['International expansion', 'Visibility per market, per language, per model.',                       SP.green],
                  ].map(([t,d,c],i,arr) => (
                    <li key={t} className={`grid grid-cols-[10px_180px_1fr] md:grid-cols-[12px_280px_1fr] gap-3 md:gap-8 p-5 md:p-6 items-center ${i<arr.length-1?'border-b-2 border-ink':''}`}>
                      <span className="w-3 h-3 inline-block" style={{background:c}}></span>
                      <span className="display text-[20px] md:text-[26px]">{t.toUpperCase()}</span>
                      <span className="text-[15px] text-ink/80 leading-[1.55] max-w-[58ch]">{d}</span>
                    </li>
                  ))}
                </ul>
              </div>

              {/* Deliverables */}
              <div id="deliverables" className="scroll-mt-28">
                <SE num="04" label="Deliverables" color={SP.green} />
                <h3 className="display display-tight text-[32px] md:text-[56px] mt-6 max-w-[24ch]">
                  WHAT YOU<br/>RECEIVE.
                </h3>
                <div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-5">
                  {[
                    ['AI visibility audit','Per-model snapshot — current citation share across ChatGPT, Claude, Gemini, Perplexity for your priority queries.', SP.red],
                    ['Entity & schema map','Structured data plan, knowledge-graph entities, content topology.', SP.orange],
                    ['Retrievable content set','Answer-first pages and chunks designed to be cited.', SP.yellow],
                    ['Authority graph','External references, mentions, and corroboration strategy.', SP.green],
                    ['Monitoring dashboard','Tracks brand citation, share-of-answer, sentiment per model.', SP.blue],
                    ['Quarterly playbook','Iteration plan based on real model behavior changes.', SP.purple],
                  ].map(([t,d,c],i) => {
                    const tc = c === SP.yellow ? '#0A0A0A' : '#fff';
                    return (
                      <div key={t} className="border-2 border-ink overflow-hidden">
                        <div className="px-5 py-3 flex items-center justify-between" style={{background: c, color: tc}}>
                          <span className="num font-bold">D{String(i+1).padStart(2,'0')}</span>
                          <span className="num">{t}</span>
                        </div>
                        <div className="p-5 bg-paper">
                          <p className="text-[14.5px] text-ink/80 leading-[1.55]">{d}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

              {/* Process */}
              <div id="process" className="scroll-mt-28">
                <SE num="05" label="Process" color={SP.blue} />
                <ol className="mt-8 border-2 border-ink">
                  {[
                    ['Diagnostic',  'Week 1',     'Pull live model responses, score citation, identify gaps.',  SP.red],
                    ['Architecture','Week 2',     'Entity map, schema, content topology, authority plan.',     SP.orange],
                    ['Engineering', 'Weeks 3–6',  'Implement structure, write retrievable content, ship.',     SP.green],
                    ['Monitoring',  'Ongoing',    'Per-model dashboard, monthly iteration cycles.',            SP.blue],
                  ].map(([t,w,d,c],i,arr) => (
                    <li key={t} className={`grid grid-cols-[60px_1fr_auto] md:grid-cols-[100px_1fr_180px] py-6 px-5 md:px-7 gap-6 items-center ${i<arr.length-1?'border-b-2 border-ink':''}`} style={{background: i%2===0 ? 'transparent' : '#F4F2EE'}}>
                      <div className="flex items-center gap-3">
                        <span className="w-3 h-3 inline-block" style={{background:c}}></span>
                        <SM>{String(i+1).padStart(2,'0')}</SM>
                      </div>
                      <div>
                        <h4 className="display text-[28px] md:text-[40px]" style={{color: c}}>{t.toUpperCase()}</h4>
                        <p className="mt-2 text-[15px] text-ink/80 leading-[1.55] max-w-[60ch]">{d}</p>
                      </div>
                      <div className="num text-mute md:text-right font-bold">{w}</div>
                    </li>
                  ))}
                </ol>
              </div>

              {/* Outcomes */}
              <div id="outcomes" className="scroll-mt-28">
                <SE num="06" label="Outcomes" color={SP.green} />
                <h3 className="display display-tight text-[32px] md:text-[56px] mt-6">BEFORE / AFTER.</h3>
                <div className="mt-8">
                  <BeforeAfter />
                </div>
                <div className="mt-4 num text-mute">Sample copy · not a guarantee. Per-engagement outcomes vary by category, competition, and existing authority.</div>
              </div>

              {/* Related */}
              <div id="related" className="scroll-mt-28">
                <SE num="07" label="Related cases" color={SP.orange} />
                <div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-6">
                  {CASES.slice(0,2).map(c => {
                    const tc = c.color === SP.yellow ? '#0A0A0A' : '#fff';
                    return (
                      <button key={c.slug} onClick={() => onOpenCase(c.slug)} className="text-left group">
                        <div className="relative aspect-[16/10] border-2 border-ink overflow-hidden" style={{background: c.color}} data-asset={`case-thumbnail-${c.slug}`}>
                          <div className="absolute inset-0 grid place-items-center">
                            <div className="display text-[44px] md:text-[64px]" style={{color: tc}}>{c.name.toUpperCase()}</div>
                          </div>
                        </div>
                        <h4 className="display text-[22px] mt-4 group-hover:translate-x-1 transition-transform">{c.name.toUpperCase()}</h4>
                        <p className="text-[14.5px] text-ink/75 mt-1">{c.line}</p>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* FAQ */}
              <div id="faq" className="scroll-mt-28">
                <SE num="08" label="FAQ" color={SP.magenta} />
                <div className="mt-8 border-2 border-ink">
                  {[
                    ['Is this just SEO with a new name?',
                     'No. Classical SEO optimizes for one results page. LLM visibility is a different stack: entity modeling, retrieval-grade content, per-model monitoring. Some technical work overlaps. The strategy doesn’t.', SP.red],
                    ['Can you guarantee citations?',
                     'No serious partner can. Model behavior changes weekly. What we guarantee is the structure, content, and authority signals that make citation possible — and a measurement system that tells you when it works.', SP.orange],
                    ['How quickly do we see movement?',
                     'Audit and architecture in 2–3 weeks. Visibility usually shifts in 6–10 weeks for well-scoped queries.', SP.green],
                    ['Do we need to rebuild our site?',
                     'Usually not. We work on existing stacks — Webflow, Next.js, WordPress, Shopify, headless setups.', SP.blue],
                  ].map(([q,a,c], i, arr) => (
                    <details key={i} className={`p-5 md:p-6 group ${i<arr.length-1?'border-b-2 border-ink':''}`}>
                      <summary className="flex items-start justify-between gap-6">
                        <div className="flex items-baseline gap-4">
                          <span className="num font-bold" style={{color:c}}>{String(i+1).padStart(2,'0')}</span>
                          <span className="display text-[20px] md:text-[24px]">{q.toUpperCase()}</span>
                        </div>
                        <span className="chev text-[24px] font-bold leading-none" style={{color:c}}>+</span>
                      </summary>
                      <p className="mt-4 ml-10 text-[15.5px] text-ink/80 leading-[1.65] max-w-[70ch]">{a}</p>
                    </details>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </SC>
      </section>

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

Object.assign(window, { ServicesHub, ServiceDetailAI });
