/* ── KIT BUILDER ─────────────────────────────────────────────
   New top-level tool (separate from Site Builder). Turns the agency's
   "remix from inspiration sites + brand + content" workflow into a
   templatized Elementor Kit / WordPress site generator.

   6-step wizard:
     1. Inspiration   — paste up to 5 URLs · per-page capture toggles
     2. Brand         — logo/color/font · 4 variants (white/black/colored/mixed)
     3. Content       — upload existing · link Content SEO · placeholders by site type
     4. Stack Config  — theme builder (Elementor/Divi/Beaver/Oxygen/Bricks) + plugins
     5. Preview & Remix — 6 variations (2 fully designed, 4 wireframe) + mix & match
     6. Export        — Elementor Kit ZIP · Direct push via WPSB plugin · Resellable kit

   Steps 1 and 5 are fully designed; the others are detailed wireframes.
   Keep the flow linear but let the sidebar jump to any completed step.

   Billing: this is a credit-metered add-on — "Kit credits" consumed per
   generation. Each plan tier gets different inclusions; overage is charged.
*/

(function() {
  const { useState, useEffect, useMemo } = React;

  // ── Site-type presets — drives placeholder content + page list ──
  const SITE_TYPES = [
    { id:'business',  label:'Business',        pages:['Home','About','Services','Team','Blog','Contact'], desc:'Service or product company' },
    { id:'civic',     label:'Civic / Gov',     pages:['Home','Departments','Services','Meetings','Documents','Staff','Contact'], desc:'Municipality, district, public agency' },
    { id:'lms',       label:'LMS / Education', pages:['Home','Courses','Instructors','Resources','Student Portal','Enrollment'], desc:'Course platform, training' },
    { id:'ecomm',     label:'E-commerce',      pages:['Home','Shop','Product','Cart','Checkout','Account'], desc:'Store with checkout' },
    { id:'trade',     label:'Trade (HVAC/Plumbing)', pages:['Home','Services','Service Areas','Financing','Reviews','Estimate','Blog'], desc:'Home-service trades' },
    { id:'pro',       label:'Professional',    pages:['Home','Practice Areas','Attorneys','Results','Blog','Contact'], desc:'Law, accounting, consulting' },
  ];

  // ── Theme-builder presets ──────────────────────────────────────
  const THEME_BUILDERS = [
    { id:'elementor', label:'Elementor Pro',  stack:['Hello Elementor','Elementor Child','Elementor Pro','JetEngine','CrocoBlock','Gravity Forms','ACF Pro (fallback)','Ally','Gravity SMTP'], default:true, badge:'Primary', desc:'Our primary stack. Full CrocoBlock suite.' },
    { id:'divi',      label:'Divi',            stack:['Divi Theme','Divi Builder','Gravity Forms','ACF Pro','Ally','Gravity SMTP'], desc:'Widely used page builder. Kit export limited to Divi Cloud format.' },
    { id:'beaver',    label:'Beaver Builder',  stack:['Beaver Builder Theme','Beaver Builder Pro','PowerPack','Gravity Forms','ACF Pro','Ally'], desc:'Clean markup, stable markup. Good for long-term maintenance.' },
    { id:'oxygen',    label:'Oxygen',          stack:['Oxygen Builder','MetaBox','Gravity Forms','Ally'], desc:'Developer-leaning. More control, steeper learning curve.' },
    { id:'bricks',    label:'Bricks',          stack:['Bricks Builder','Automatic.css','ACSS','Gravity Forms','Ally'], desc:'Modern builder, fastest-growing. Native CSS output.' },
  ];

  // ── Plan/credit tiers ──────────────────────────────────────────
  const CREDIT_PLANS = [
    { id:'starter',   label:'Starter',     kits:1,  overage:'$49/kit',  price:'Included in Agency plan'  },
    { id:'pro',       label:'Pro',         kits:5,  overage:'$29/kit',  price:'Included in Pro plan'     },
    { id:'agency',    label:'Agency',      kits:15, overage:'$19/kit',  price:'Included in Agency plan'  },
    { id:'addon',     label:'Kit Credits', kits:25, overage:'$15/kit',  price:'$249 one-time add-on'     },
  ];

  /* ═══════════════════════════════════════════════════════════════
     MAIN KIT BUILDER COMPONENT
  ═══════════════════════════════════════════════════════════════ */
  function KitBuilder() {
    const Icon = window.Icon;
    const PageHead = window.PageHead;

    // Step state (persisted so refreshing doesn't lose work)
    const [step, setStep] = useState(() => {
      try { return parseInt(localStorage.getItem('wpsb-kit-step') || '1'); } catch { return 1; }
    });
    useEffect(() => { try { localStorage.setItem('wpsb-kit-step', String(step)); } catch {} }, [step]);

    // Wizard-wide state
    const [inspo, setInspo] = useState([
      { url:'https://stripe.com',         pages:['home','pricing'],     captures:['layout','color','type','hero','nav','cta','cards','motion'], example:true },
      { url:'https://linear.app',         pages:['home','features'],    captures:['layout','color','type','hero','nav','cta','motion','imagery'], example:true },
      { url:'https://www.brownsvilletx.gov', pages:['home','services','contact'], captures:['layout','color','type','hero','nav','footer','forms','cards'], example:true },
    ]);
    const [siteType, setSiteType] = useState('business');
    const [brand, setBrand] = useState({
      companyName:'Nova Labs', slogan:'Ship faster. Ship smarter.',
      iconConcept:'abstract geometric mark · circle + offset square',
      style:'modern', market:'hvac', colors:['var(--orange)','#0F172A'],
      fontHead:'Orbitron', fontBody:'Inter',
      logoVariant:'colored', // white | black | colored | mixed
      hasLogo:false, hasBrand:false,
    });
    const [content, setContent] = useState({ existing:'placeholders', pages:6, uploadedFiles:0, linkContentSEO:true });
    const [themeBuilder, setThemeBuilder] = useState('elementor');
    const [selectedVariation, setSelectedVariation] = useState(2); // preview step: pick one
    const [mixPicks, setMixPicks] = useState({ hero:2, nav:1, footer:3, cards:2, forms:4 });
    const [exportPath, setExportPath] = useState('zip'); // zip | push | resell

    const STEPS = [
      { id:1, label:'Inspiration', icon:'globe',  desc:'Reference URLs to remix from' },
      { id:2, label:'Brand',       icon:'brand',  desc:'Logo, colors, typography' },
      { id:3, label:'Content',     icon:'content',desc:'Pages, copy, media' },
      { id:4, label:'Stack',       icon:'stack',  desc:'Theme builder & plugins' },
      { id:5, label:'Preview',     icon:'palette',desc:'Generated variations' },
      { id:6, label:'Export',      icon:'download',desc:'Kit ZIP, push, or resell' },
    ];

    const pct = Math.round(((step - 1) / (STEPS.length - 1)) * 100);

    return (
      <div>
        <PageHead crumb="Tools"
          title={<span style={{ display:'inline-flex', alignItems:'center', gap:10 }}>
            Kit Builder
            <span style={{ fontFamily:'var(--font-mono)', fontSize:'.58rem', padding:'3px 8px', borderRadius:4, background:'var(--beam-dim)', border:'1px solid var(--beam-dim)', color:'var(--beam)', letterSpacing:'.08em' }}>BETA · ADD-ON</span>
          </span>}
          sub="Generate an Elementor Theme Kit (or Divi/Beaver/Oxygen/Bricks) from 1-5 inspiration URLs + your brand + content. Remix the parts you like across a grid of variations."
          actions={<>
            <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Credit usage: 2 of 15 this month', 'info')}>
              <Icon name="calc" size={13}/>Credits: 2/15
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => { localStorage.removeItem('wpsb-kit-step'); setStep(1); window.wpsbToast?.('Kit wizard reset', 'info'); }}>
              <Icon name="refresh" size={13}/>Start over
            </button>
          </>}/>

        {/* ── Progress / step nav ───────────────────────────────── */}
        <div className="card" style={{ marginBottom:16 }}>
          <div className="card-body" style={{ padding:'14px 16px' }}>
            {/* progress bar */}
            <div style={{ position:'relative', height:3, background:'var(--border)', borderRadius:2, marginBottom:14 }}>
              <div style={{ position:'absolute', inset:0, width:`${pct}%`, background:'linear-gradient(90deg, var(--beam), var(--orange))', borderRadius:2, transition:'width .3s' }}/>
            </div>
            {/* step tabs */}
            <div style={{ display:'grid', gridTemplateColumns:`repeat(${STEPS.length}, minmax(0, 1fr))`, gap:4, minWidth:0 }}>
              {STEPS.map(s => (
                <button key={s.id} onClick={() => setStep(s.id)}
                        disabled={s.id > step + 1 /* can only move forward one step unless completed */}
                        style={{
                          padding:'8px 6px', textAlign:'left', minWidth:0,
                          background: step === s.id ? 'var(--surface-2)' : 'transparent',
                          border: step === s.id ? '1px solid var(--beam)' : '1px solid transparent',
                          borderRadius:6, cursor: s.id > step + 1 ? 'not-allowed' : 'pointer',
                          opacity: s.id > step + 1 ? 0.45 : 1,
                          display:'flex', alignItems:'center', gap:7,
                          color: step === s.id ? 'var(--text)' : 'var(--muted)',
                          fontFamily:'inherit',
                        }}>
                  <div style={{
                    width:22, height:22, borderRadius:'50%', flexShrink:0,
                    background: s.id < step ? 'var(--green)' : s.id === step ? 'var(--beam)' : 'var(--surface-2)',
                    color: s.id <= step ? '#fff' : 'var(--dim)',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    fontSize:'.62rem', fontWeight:700, fontFamily:'var(--font-mono)',
                  }}>
                    {s.id < step ? <Icon name="check" size={10}/> : s.id}
                  </div>
                  <div style={{ minWidth:0, overflow:'hidden', flex:1 }}>
                    <div style={{ fontSize:'.72rem', fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{s.label}</div>
                    <div className="kb-step-desc" style={{ fontSize:'.64rem', color:'var(--dim)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{s.desc}</div>
                  </div>
                </button>
              ))}
            </div>
            <style>{`
              @media (max-width: 1100px) { .kb-step-desc { display:none; } }
            `}</style>
          </div>
        </div>

        {/* ── Step content ──────────────────────────────────────── */}
        {step === 1 && <StepInspiration inspo={inspo} setInspo={setInspo} siteType={siteType} setSiteType={setSiteType} SITE_TYPES={SITE_TYPES}/>}
        {step === 2 && <StepBrand brand={brand} setBrand={setBrand}/>}
        {step === 3 && <StepContent content={content} setContent={setContent} siteType={siteType} SITE_TYPES={SITE_TYPES}/>}
        {step === 4 && <StepStack themeBuilder={themeBuilder} setThemeBuilder={setThemeBuilder} THEME_BUILDERS={THEME_BUILDERS}/>}
        {step === 5 && <StepPreview selected={selectedVariation} setSelected={setSelectedVariation} mixPicks={mixPicks} setMixPicks={setMixPicks} brand={brand} siteType={siteType} themeBuilder={themeBuilder}/>}
        {step === 6 && <StepExport exportPath={exportPath} setExportPath={setExportPath} brand={brand} themeBuilder={themeBuilder} siteType={siteType} CREDIT_PLANS={CREDIT_PLANS}/>}

        {/* ── Footer nav ────────────────────────────────────────── */}
        <div style={{ marginTop:20, padding:'14px 0', borderTop:'1px solid var(--border)', display:'flex', alignItems:'center', gap:10 }}>
          <button className="btn btn-ghost btn-sm" disabled={step === 1} onClick={() => setStep(Math.max(1, step - 1))}>
            <Icon name="chevron-left" size={13}/>Back
          </button>
          <div style={{ flex:1, fontSize:'.7rem', color:'var(--dim)', textAlign:'center' }}>
            Step {step} of {STEPS.length} · {STEPS[step - 1].label}
          </div>
          {step < STEPS.length ? (
            <button className="btn btn-primary btn-sm" onClick={() => setStep(Math.min(STEPS.length, step + 1))}>
              Continue<Icon name="chevron-right" size={13}/>
            </button>
          ) : (
            <button className="btn btn-primary btn-sm" onClick={() => window.wpsbToast?.('Kit generation queued — notify when ready (~3 min)', 'ok')}>
              <Icon name="wand" size={13}/>Generate kit
            </button>
          )}
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════════
     STEP 1 — INSPIRATION (FULLY DESIGNED)
  ═══════════════════════════════════════════════════════════════ */
  function StepInspiration({ inspo, setInspo, siteType, setSiteType, SITE_TYPES }) {
    const Icon = window.Icon;
    const [newUrl, setNewUrl] = useState('');
    const [activeUrl, setActiveUrl] = useState(0);

    const addUrl = () => {
      if (!newUrl.trim()) return;
      // If only examples exist, clear them — this is the user's first real add.
      const realEntries = inspo.filter(u => !u.example);
      if (realEntries.length === 0) {
        setInspo([{ url: newUrl.trim(), pages:['home'], captures:['layout','color','type','hero','nav','cta'] }]);
        setActiveUrl(0);
        setNewUrl('');
        window.wpsbToast?.('Examples cleared · your URL added', 'beam');
        return;
      }
      if (realEntries.length >= 5) return;
      setInspo([...realEntries, { url: newUrl.trim(), pages:['home'], captures:['layout','color','type','hero','nav','cta'] }]);
      setActiveUrl(realEntries.length);
      setNewUrl('');
      window.wpsbToast?.('URL added · scraping pages…', 'beam');
    };

    const removeUrl = (i) => {
      const next = inspo.filter((_, idx) => idx !== i);
      setInspo(next);
      if (activeUrl >= next.length) setActiveUrl(Math.max(0, next.length - 1));
    };

    const toggleCapture = (key) => {
      const cur = inspo[activeUrl];
      const captures = cur.captures.includes(key)
        ? cur.captures.filter(c => c !== key)
        : [...cur.captures, key];
      const next = [...inspo];
      next[activeUrl] = { ...cur, captures };
      setInspo(next);
    };

    const togglePage = (pageKey) => {
      const cur = inspo[activeUrl];
      const pages = cur.pages.includes(pageKey)
        ? cur.pages.filter(p => p !== pageKey)
        : [...cur.pages, pageKey];
      const next = [...inspo];
      next[activeUrl] = { ...cur, pages };
      setInspo(next);
    };

    const CAPTURES = [
      { key:'layout',   label:'Layout',   desc:'Section rhythm, whitespace' },
      { key:'color',    label:'Palette',  desc:'Extracted colors + usage' },
      { key:'type',     label:'Type',     desc:'Font stacks, scale, pairing' },
      { key:'hero',     label:'Hero',     desc:'Above-fold pattern' },
      { key:'nav',      label:'Nav',      desc:'Header structure + menu' },
      { key:'footer',   label:'Footer',   desc:'Footer content + layout' },
      { key:'cta',      label:'CTA',      desc:'Button treatment + placement' },
      { key:'cards',    label:'Cards',    desc:'Content card patterns' },
      { key:'forms',    label:'Forms',    desc:'Form styling + fields' },
      { key:'motion',   label:'Motion',   desc:'Scroll + hover animations' },
      { key:'imagery',  label:'Imagery',  desc:'Photo/illustration style' },
      { key:'icons',    label:'Iconography', desc:'Icon set direction' },
    ];

    const ALL_PAGES = [
      { key:'home',     label:'Home' },
      { key:'about',    label:'About' },
      { key:'services', label:'Services' },
      { key:'pricing',  label:'Pricing' },
      { key:'team',     label:'Team' },
      { key:'case',     label:'Case studies' },
      { key:'blog',     label:'Blog' },
      { key:'contact',  label:'Contact' },
      { key:'features', label:'Features' },
      { key:'faq',      label:'FAQ' },
    ];

    const cur = inspo[activeUrl] || inspo[0] || {};

    return (
      <div>
        {/* Site type picker */}
        <div className="card" style={{ marginBottom:14 }}>
          <div className="card-head">
            <h2 className="card-title"><Icon name="building" size={14}/>&nbsp;What kind of site are we building?</h2>
            <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Determines default page list + placeholder content</div>
          </div>
          <div className="card-body">
            <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(180px, 1fr))', gap:8 }}>
              {SITE_TYPES.map(t => (
                <button key={t.id} onClick={() => setSiteType(t.id)}
                        style={{
                          padding:'12px 14px', textAlign:'left', cursor:'pointer',
                          background: siteType === t.id ? 'var(--beam-dim)' : 'var(--surface-2)',
                          border: siteType === t.id ? '1px solid var(--beam)' : '1px solid var(--border)',
                          borderRadius:8, color:'var(--text)', fontFamily:'inherit',
                        }}>
                  <div style={{ fontSize:'.82rem', fontWeight:600, marginBottom:2, color: siteType === t.id ? 'var(--beam)' : 'var(--text)' }}>{t.label}</div>
                  <div style={{ fontSize:'.68rem', color:'var(--dim)', marginBottom:6 }}>{t.desc}</div>
                  <div style={{ fontSize:'.62rem', color:'var(--muted)', fontFamily:'var(--font-mono)' }}>
                    {t.pages.length} pages · {t.pages.slice(0,3).join(', ')}…
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* URL list + scraper */}
        <div className="grid" style={{ gridTemplateColumns:'340px 1fr', gap:14, marginBottom:14 }}>
          {/* Left: URL list */}
          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="link" size={14}/>&nbsp;Inspiration URLs</h2>
              <span className="tag" style={{ fontSize:'.6rem' }}>{inspo.length}/5</span>
            </div>
            {inspo.every(u => u.example) && inspo.length > 0 && (
              <div style={{
                padding:'8px 14px', background:'var(--beam-dim)', borderBottom:'1px solid var(--border)',
                fontSize:'.66rem', color:'var(--beam)', display:'flex', alignItems:'center', gap:6,
              }}>
                <Icon name="info" size={12}/>
                <span><strong>Examples</strong> · add your URL below to start fresh</span>
              </div>
            )}
            <div className="card-body" style={{ padding:0 }}>
              {inspo.map((u, i) => {
                const hasData = !!getScanFor(u);
                return (
                <div key={i} onClick={() => setActiveUrl(i)}
                     style={{
                       padding:'12px 14px', cursor:'pointer',
                       background: activeUrl === i ? 'var(--surface-2)' : 'transparent',
                       borderBottom:'1px solid var(--border)',
                       borderLeft: activeUrl === i ? '3px solid var(--beam)' : '3px solid transparent',
                       opacity: u.example ? 0.82 : 1,
                     }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:'.74rem', fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', display:'flex', alignItems:'center', gap:6 }}>
                        <span style={{ width:6, height:6, borderRadius:'50%', flexShrink:0, background: hasData ? 'var(--green)' : 'var(--warn)' }} title={hasData ? 'Scan data ready' : 'Not scanned yet'}/>
                        {(u.url || '').replace(/^https?:\/\//, '')}
                        {u.example && <span style={{ fontSize:'.54rem', padding:'1px 5px', borderRadius:3, background:'var(--surface-3)', color:'var(--dim)', fontWeight:500, letterSpacing:'.04em', textTransform:'uppercase' }}>example</span>}
                      </div>
                      <div style={{ fontSize:'.64rem', color:'var(--dim)', marginTop:2, fontFamily:'var(--font-mono)' }}>
                        {u.pages.length} pages · {u.captures.length} captures · {hasData ? 'scanned' : 'pending scan'}
                      </div>
                    </div>
                    <button onClick={(e) => { e.stopPropagation(); removeUrl(i); }}
                            style={{ background:'none', border:'none', color:'var(--dim)', cursor:'pointer', padding:4 }}
                            title="Remove">
                      <Icon name="x" size={14}/>
                    </button>
                  </div>
                </div>
                );
              })}
              {inspo.length < 5 && (
                <div style={{ padding:'12px 14px', display:'flex', gap:6 }}>
                  <input value={newUrl} onChange={e => setNewUrl(e.target.value)}
                         placeholder="https://example.com"
                         onKeyDown={e => e.key === 'Enter' && addUrl()}
                         style={{ flex:1, padding:'7px 10px', fontSize:'.74rem', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)' }}/>
                  <button className="btn btn-primary btn-sm" onClick={addUrl} disabled={!newUrl.trim()}>
                    <Icon name="plus" size={12}/>Add
                  </button>
                </div>
              )}
              <div style={{ padding:'10px 14px', background:'var(--surface-2)', fontSize:'.66rem', color:'var(--muted)', lineHeight:1.5 }}>
                <strong style={{ color:'var(--text)' }}>Tip:</strong> 3-5 URLs gives the best remix. With 1-2, results favor that site's conventions more heavily.
              </div>
            </div>
          </div>

          {/* Right: Active URL detail */}
          <div className="card">
            <div className="card-head">
              <h2 className="card-title" style={{ display:'flex', alignItems:'center', gap:8 }}>
                <Icon name="globe" size={14}/>
                <span style={{ overflow:'hidden', textOverflow:'ellipsis' }}>{(cur.url || '').replace(/^https?:\/\//, '')}</span>
              </h2>
              <span className="tag ok" style={{ fontSize:'.6rem' }}>SCRAPED</span>
            </div>
            <div className="card-body">
              {/* Page targets */}
              <div style={{ marginBottom:18 }}>
                <div style={{ fontSize:'.64rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Pages to scrape</div>
                <div style={{ fontSize:'.7rem', color:'var(--muted)', marginBottom:8 }}>Pick 5-30 pages. More pages = better signal on nav/footer/patterns that don't show on home.</div>
                <div style={{ display:'flex', flexWrap:'wrap', gap:5 }}>
                  {ALL_PAGES.map(p => (
                    <button key={p.key} onClick={() => togglePage(p.key)}
                            style={{
                              padding:'5px 10px', fontSize:'.7rem', borderRadius:14, cursor:'pointer',
                              background: cur.pages?.includes(p.key) ? 'var(--beam)' : 'var(--surface-2)',
                              color: cur.pages?.includes(p.key) ? '#001018' : 'var(--muted)',
                              border: cur.pages?.includes(p.key) ? '1px solid var(--beam)' : '1px solid var(--border)',
                              fontFamily:'inherit', fontWeight:500,
                            }}>
                      {cur.pages?.includes(p.key) ? '✓ ' : '+ '}{p.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* Captures grid */}
              <div>
                <div style={{ fontSize:'.64rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>What to capture</div>
                <div style={{ fontSize:'.7rem', color:'var(--muted)', marginBottom:10 }}>Each enabled capture becomes a toggleable remix input on the Preview step.</div>
                <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(190px, 1fr))', gap:8 }}>
                  {CAPTURES.map(c => {
                    const on = cur.captures?.includes(c.key);
                    return (
                      <button key={c.key} onClick={() => toggleCapture(c.key)}
                              style={{
                                padding:'10px 12px', textAlign:'left', cursor:'pointer',
                                background: on ? 'var(--beam-dim)' : 'var(--surface-2)',
                                border: on ? '1px solid var(--beam)' : '1px solid var(--border)',
                                borderRadius:6, fontFamily:'inherit', color:'var(--text)',
                              }}>
                        <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                          <div style={{
                            width:14, height:14, borderRadius:3, flexShrink:0,
                            background: on ? 'var(--beam)' : 'transparent',
                            border: on ? '1px solid var(--beam)' : '1px solid var(--border)',
                            color:'#001018', display:'flex', alignItems:'center', justifyContent:'center',
                            fontSize:'.6rem', fontWeight:700,
                          }}>{on ? '✓' : ''}</div>
                          <div style={{ fontSize:'.76rem', fontWeight:600, color: on ? 'var(--beam)' : 'var(--text)' }}>{c.label}</div>
                        </div>
                        <div style={{ fontSize:'.66rem', color:'var(--dim)', marginTop:3, marginLeft:20 }}>{c.desc}</div>
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Live capture preview — real per-URL data */}
              <URLScanPanel cur={cur} activeIdx={activeUrl} setInspo={setInspo} inspo={inspo}/>
            </div>
          </div>
        </div>

        {/* Summary panel */}
        <div className="box info">
          <Icon name="info" size={14}/>
          <div>
            <strong>{inspo.length} site{inspo.length !== 1 ? 's' : ''} · {inspo.reduce((a,u) => a + u.pages.length, 0)} pages queued for scrape.</strong>
            &nbsp;Captures are deduplicated across sites on the Preview step — e.g. if 3 sites have similar CTA treatment, you'll see the convergent pattern ranked highest.
          </div>
        </div>
      </div>
    );
  }

  // ── Per-URL mock scan database ────────────────────────────────
  // Keyed by host; simulates what the backend Scanner would return.
  // In production this plugs into the same engine as the Scanner tool.
  const SCAN_DATA = {
    'stripe.com': {
      palette: [['#635BFF','primary'],['#0A2540','text'],['#425466','muted'],['#F6F9FC','surface'],['var(--beam)','accent']],
      typography: { head:'Sohne', body:'Sohne', scale:'-0.02em', headWeight:600 },
      layout: 'Asymmetric hero · 3-col features · dense footer',
      hero: 'Headline + subhead + dual CTA · rotating gradient bg',
      nav: 'Mega-menu · 7 items · sticky · product switcher',
      footer: '6-col · language picker · status badge',
      cta: 'Pill button · indigo fill · arrow on hover',
      cards: 'Rounded 8px · subtle shadow · icon top-left',
      forms: 'Floating label · focus ring indigo',
      motion: 'Scroll-parallax hero · fade-in on sections',
      imagery: 'Abstract 3D renders · isometric illustrations',
      icons: 'Line-style · 1.5px stroke · 24x24 grid',
      pagesScanned: 12, pagesTotal: 12,
    },
    'linear.app': {
      palette: [['#5E6AD2','primary'],['#1C1C1F','bg-dark'],['#F4F5F7','surface'],['#E5E5E7','muted'],['#26A69A','accent']],
      typography: { head:'Inter', body:'Inter', scale:'-0.015em', headWeight:500 },
      layout: 'Dark hero · product screenshots · full-bleed',
      hero: 'Centered · keyboard shortcut badge · demo video',
      nav: 'Slim · centered logo · CTA right',
      footer: '4-col · dark · minimal links',
      cta: 'Rounded · subtle gradient · sharp edges',
      cards: 'Dark surface · thin borders · no shadow',
      forms: 'Minimal · 1px border · indigo accent',
      motion: 'Keyboard-triggered · micro-interactions · cursor trails',
      imagery: 'Product screenshots · dark mode · UI cutouts',
      icons: 'Lucide · 20x20 · outlined',
      pagesScanned: 8, pagesTotal: 8,
    },
    'brownsvilletx.gov': {
      palette: [['#003366','primary'],['#8B0000','accent'],['#F7F3E9','surface'],['#333333','text'],['#DAA520','highlight']],
      typography: { head:'Merriweather', body:'Open Sans', scale:'0em', headWeight:700 },
      layout: 'Top utility bar · mega-nav · 4-col dept grid',
      hero: 'Rotating banner · city seal · quick-links strip',
      nav: 'Dept mega-menu · dropdowns · accessible focus',
      footer: 'Contact info · seal · social · site index',
      cta: 'Rectangle · primary navy · subtle hover shift',
      cards: 'Sharp corners · dept icons · uniform height',
      forms: 'Standard · labeled above · help text',
      motion: 'None — accessibility-first',
      imagery: 'Staged civic photos · event imagery · maps',
      icons: 'Font Awesome 5 · solid · mixed sizes',
      pagesScanned: 24, pagesTotal: 38,
    },
  };
  function getScanFor(u) {
    const host = (u.url || '').replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0].toLowerCase();
    return SCAN_DATA[host] || null;
  }

  // ── URL Scan Panel — shows real extracted data per selected URL ──
  function URLScanPanel({ cur, activeIdx, setInspo, inspo }) {
    const Icon = window.Icon;
    const [scanState, setScanState] = useState({}); // { url: 'idle'|'scanning'|'done' }
    const scan = getScanFor(cur || {});
    const urlKey = cur?.url || '';
    const state = scanState[urlKey] || (scan ? 'done' : 'idle');

    const runScan = () => {
      setScanState({ ...scanState, [urlKey]: 'scanning' });
      setTimeout(() => {
        setScanState({ ...scanState, [urlKey]: 'done' });
        window.wpsbToast?.(`Scan complete for ${urlKey.replace(/^https?:\/\//, '')}`, 'ok');
      }, 1600);
    };

    if (!cur || !cur.url) return null;

    return (
      <div style={{ marginTop:18, background:'var(--surface-2)', borderRadius:8, border:'1px solid var(--border)', overflow:'hidden' }}>
        {/* Header */}
        <div style={{ padding:'10px 14px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:10, background:'var(--surface)' }}>
          <div style={{ fontSize:'.64rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, flex:1 }}>
            Extracted signals from <span style={{ color:'var(--beam)', fontFamily:'var(--font-mono)' }}>{(cur.url || '').replace(/^https?:\/\//, '')}</span>
          </div>
          {state === 'done' && scan && (
            <span style={{ fontSize:'.6rem', color:'var(--green)', fontFamily:'var(--font-mono)', display:'flex', alignItems:'center', gap:4 }}>
              <div style={{ width:6, height:6, borderRadius:'50%', background:'var(--green)' }}/>
              {scan.pagesScanned}/{scan.pagesTotal} pages · fresh
            </span>
          )}
          {state === 'scanning' && (
            <span style={{ fontSize:'.6rem', color:'var(--beam)', fontFamily:'var(--font-mono)', display:'flex', alignItems:'center', gap:4 }}>
              <div className="spinner" style={{ width:10, height:10 }}/>
              Scanning…
            </span>
          )}
          <button className="btn btn-ghost btn-sm" onClick={runScan} disabled={state === 'scanning'}>
            <Icon name="refresh" size={11}/>{state === 'done' ? 'Re-scan' : state === 'scanning' ? 'Scanning' : 'Quick scan'}
          </button>
        </div>

        {/* Body */}
        {state === 'idle' && !scan && (
          <div style={{ padding:24, textAlign:'center' }}>
            <Icon name="scanner" size={28} style={{ color:'var(--dim)', marginBottom:8 }}/>
            <div style={{ fontSize:'.82rem', fontWeight:600, marginBottom:4 }}>No scan yet for this URL</div>
            <div style={{ fontSize:'.68rem', color:'var(--dim)', marginBottom:12 }}>Click Quick scan to pull palette, type, layout, and component patterns.</div>
            <button className="btn btn-primary btn-sm" onClick={runScan}><Icon name="spark" size={12}/>Quick scan now</button>
          </div>
        )}

        {state === 'scanning' && (
          <div style={{ padding:'24px 14px' }}>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:10 }}>
              <div className="spinner"/>
              <div style={{ fontSize:'.8rem', fontWeight:600 }}>Scanning {(cur.url || '').replace(/^https?:\/\//, '')}…</div>
            </div>
            {['Fetching page HTML','Extracting CSS tokens','Reading font stacks','Detecting layout patterns','Capturing components'].map((l, i) => (
              <div key={l} style={{ fontSize:'.68rem', color:'var(--dim)', fontFamily:'var(--font-mono)', marginLeft:22, padding:'3px 0', opacity: 1 - (i * 0.15) }}>
                <span style={{ color: i === 0 ? 'var(--beam)' : 'var(--muted)' }}>→</span> {l}
              </div>
            ))}
          </div>
        )}

        {state === 'done' && scan && (
          <div style={{ padding:12 }}>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(180px, 1fr))', gap:10 }}>
              {cur.captures?.includes('color') && <ScanCard title="Palette · extracted">
                <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
                  {scan.palette.map(([c, name]) => (
                    <div key={c} style={{ display:'flex', alignItems:'center', gap:6 }}>
                      <div style={{ width:18, height:18, borderRadius:3, background:c, border:'1px solid rgba(255,255,255,.08)' }}/>
                      <div style={{ fontFamily:'var(--font-mono)', fontSize:'.6rem', color:'var(--muted)' }}>{c}</div>
                      <div style={{ fontSize:'.58rem', color:'var(--dim)', textTransform:'uppercase', letterSpacing:'.06em' }}>{name}</div>
                    </div>
                  ))}
                </div>
              </ScanCard>}

              {cur.captures?.includes('type') && <ScanCard title="Typography">
                <div style={{ fontFamily:`${scan.typography.head}, sans-serif`, fontSize:'1.6rem', fontWeight:scan.typography.headWeight, lineHeight:1, marginBottom:4, letterSpacing:scan.typography.scale }}>Aa Bb</div>
                <div style={{ fontSize:'.62rem', fontFamily:'var(--font-mono)', color:'var(--muted)' }}>Head: {scan.typography.head}</div>
                <div style={{ fontSize:'.62rem', fontFamily:'var(--font-mono)', color:'var(--muted)' }}>Body: {scan.typography.body}</div>
                <div style={{ fontSize:'.58rem', color:'var(--dim)' }}>tracking {scan.typography.scale} · wt {scan.typography.headWeight}</div>
              </ScanCard>}

              {cur.captures?.includes('layout') && <ScanCard title="Layout"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.layout}</div></ScanCard>}
              {cur.captures?.includes('hero') && <ScanCard title="Hero"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.hero}</div></ScanCard>}
              {cur.captures?.includes('nav') && <ScanCard title="Navigation"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.nav}</div></ScanCard>}
              {cur.captures?.includes('footer') && <ScanCard title="Footer"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.footer}</div></ScanCard>}
              {cur.captures?.includes('cta') && <ScanCard title="CTA style"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.cta}</div></ScanCard>}
              {cur.captures?.includes('cards') && <ScanCard title="Card pattern"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.cards}</div></ScanCard>}
              {cur.captures?.includes('forms') && <ScanCard title="Forms"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.forms}</div></ScanCard>}
              {cur.captures?.includes('motion') && <ScanCard title="Motion"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.motion}</div></ScanCard>}
              {cur.captures?.includes('imagery') && <ScanCard title="Imagery"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.imagery}</div></ScanCard>}
              {cur.captures?.includes('icons') && <ScanCard title="Icons"><div style={{ fontSize:'.7rem', lineHeight:1.4 }}>{scan.icons}</div></ScanCard>}
            </div>
            <div style={{ marginTop:10, padding:'8px 10px', background:'var(--surface)', borderRadius:4, display:'flex', alignItems:'center', gap:8 }}>
              <Icon name="info" size={11} style={{ color:'var(--dim)' }}/>
              <div style={{ fontSize:'.64rem', color:'var(--muted)' }}>
                Data extracted via the same engine as the <a href="#" onClick={e=>{e.preventDefault(); window.WPSBD?.switchTab?.('scanner');}} style={{ color:'var(--beam)' }}>Site Scanner</a> tool. These signals feed the variations on Step 5.
              </div>
            </div>
          </div>
        )}

        {state === 'idle' && scan && (
          <div style={{ padding:'24px 14px', textAlign:'center' }}>
            <div style={{ fontSize:'.72rem', color:'var(--muted)' }}>Cached scan available · {scan.pagesScanned} pages</div>
            <button className="btn btn-primary btn-sm" style={{ marginTop:8 }} onClick={() => setScanState({...scanState, [urlKey]:'done'})}>
              <Icon name="refresh" size={11}/>Use cached · or re-scan
            </button>
          </div>
        )}
      </div>
    );
  }

  function ScanCard({ title, children }) {
    return (
      <div style={{ padding:10, background:'var(--surface)', borderRadius:6, border:'1px solid var(--border)' }}>
        <div style={{ fontSize:'.58rem', color:'var(--dim)', fontFamily:'var(--font-mono)', marginBottom:6, letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700 }}>{title}</div>
        {children}
      </div>
    );
  }

  // ── Small preview helpers (legacy, kept for backward compat) ────
  function ColorChipsPreview() {
    const chips = ['#635BFF','#0A2540','#425466','#F6F9FC','var(--beam)'];
    return (
      <div style={{ padding:8, background:'var(--surface)', borderRadius:4 }}>
        <div style={{ fontSize:'.6rem', color:'var(--dim)', marginBottom:4, fontFamily:'var(--font-mono)' }}>palette</div>
        <div style={{ display:'flex', gap:2 }}>
          {chips.map(c => <div key={c} style={{ width:18, height:26, background:c, borderRadius:2 }} title={c}/>)}
        </div>
      </div>
    );
  }
  function TypePreview() {
    return (
      <div style={{ padding:8, background:'var(--surface)', borderRadius:4 }}>
        <div style={{ fontSize:'.6rem', color:'var(--dim)', marginBottom:4, fontFamily:'var(--font-mono)' }}>type</div>
        <div style={{ fontFamily:'Sohne, Inter, sans-serif', fontSize:'1rem', fontWeight:600, lineHeight:1 }}>Aa</div>
        <div style={{ fontSize:'.56rem', color:'var(--muted)', marginTop:3, fontFamily:'var(--font-mono)' }}>Sohne · -0.02em</div>
      </div>
    );
  }
  function LayoutPreview() {
    return (
      <div style={{ padding:8, background:'var(--surface)', borderRadius:4 }}>
        <div style={{ fontSize:'.6rem', color:'var(--dim)', marginBottom:4, fontFamily:'var(--font-mono)' }}>layout</div>
        <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
          <div style={{ height:4, background:'var(--border)', borderRadius:1 }}/>
          <div style={{ height:14, background:'linear-gradient(90deg, var(--beam-dim), transparent)', borderRadius:1 }}/>
          <div style={{ display:'flex', gap:2 }}>
            <div style={{ flex:1, height:8, background:'var(--border)', borderRadius:1 }}/>
            <div style={{ flex:1, height:8, background:'var(--border)', borderRadius:1 }}/>
            <div style={{ flex:1, height:8, background:'var(--border)', borderRadius:1 }}/>
          </div>
        </div>
      </div>
    );
  }
  function HeroPreview() {
    return (
      <div style={{ padding:8, background:'var(--surface)', borderRadius:4 }}>
        <div style={{ fontSize:'.6rem', color:'var(--dim)', marginBottom:4, fontFamily:'var(--font-mono)' }}>hero</div>
        <div style={{ display:'flex', gap:3 }}>
          <div style={{ flex:1, minHeight:26, background:'var(--surface-2)', borderRadius:2, display:'flex', flexDirection:'column', justifyContent:'center', padding:3 }}>
            <div style={{ height:3, background:'var(--text)', borderRadius:1, marginBottom:2 }}/>
            <div style={{ height:2, background:'var(--muted)', borderRadius:1, width:'70%' }}/>
          </div>
          <div style={{ width:14, background:'var(--beam-dim)', borderRadius:2 }}/>
        </div>
      </div>
    );
  }

  // Expose the main component. Sub-steps 2-6 come from KitBuilderSteps.jsx.
  window.KitBuilder = KitBuilder;

  // Also expose small helpers so KitBuilderSteps.jsx can share state shape.
  window.KitBuilderShared = { SITE_TYPES, THEME_BUILDERS, CREDIT_PLANS };

  // Also allow Step components to find each other on window
  window.__KB = window.__KB || {};
  window.__KB.StepInspiration = StepInspiration;

  /* ═══════════════════════════════════════════════════════════════
     STEP 2 — BRAND
  ═══════════════════════════════════════════════════════════════ */
  /* ═══════════════════════════════════════════════════════════════
     STEP 2 — BRAND (wireframe + logo variants + applied preview)
  ═══════════════════════════════════════════════════════════════ */

  /** LogoMark — style/market/color responsive SVG mark + wordmark */
  function LogoMark({ brand, markColor, wordColor, size = 'md', orientation = 'horizontal', showSlogan = true }) {
    const c = brand.companyName || 'Brandmark';
    const initials = c.split(/\s+/).filter(Boolean).slice(0,2).map(w => w[0]).join('').toUpperCase() || 'B';
    const concept = (brand.iconConcept || '').toLowerCase();
    const style = brand.style || 'modern';

    // Shape language driven by brand.style — dramatically differentiated
    const styleSpec = {
      modern:   { round: 6,  strokeW: 2,   weight: 700, tracking: '-.01em', case: 'none',      fontShift: 0 },
      classic:  { round: 1,  strokeW: 1.5, weight: 500, tracking: '.02em',  case: 'none',      fontShift: 0, serif: true },
      bold:     { round: 3,  strokeW: 4,   weight: 900, tracking: '-.03em', case: 'uppercase', fontShift: .05 },
      minimal:  { round: 0,  strokeW: 1,   weight: 300, tracking: '0',      case: 'lowercase', fontShift: -.05 },
      playful:  { round: 16, strokeW: 2.5, weight: 800, tracking: '-.02em', case: 'none',      fontShift: .05 },
      luxury:   { round: 0,  strokeW: .75, weight: 300, tracking: '.25em',  case: 'uppercase', fontShift: -.05, serif: true },
    }[style] || { round: 6, strokeW: 2, weight: 700, tracking: '-.01em', case: 'none', fontShift: 0 };

    // Glyph: preset keyword match OR freeform hash → deterministic pick
    const PRESETS = {
      monogram:['monogram','initials'], flame:['flame','fire','burn'], bolt:['bolt','lightning','spark','electric','zap'],
      shield:['shield','guard','protect'], hex:['hex','honeycomb','polygon'],
      plus:['medical','cross','plus','health'],
      drop:['drop','water','plumb'], leaf:['leaf','eco','green','plant','nature'],
      star:['star','celestial','sparkle'], arrow:['arrow','forward','next','grow'],
      circle:['circle','orbit','ring','loop'], square:['square','block','frame','cube'],
      triangle:['triangle','peak','mountain','up'], wave:['wave','flow','ocean','river'],
      abstract:['abstract','geometric','modern'],
    };
    const wordmarkOnly = /wordmark only|text only|no (icon|mark)/i.test(concept);
    let glyph = 'abstract';
    if (wordmarkOnly) glyph = 'none';
    else {
      const matched = Object.entries(PRESETS).find(([, kws]) => kws.some(k => concept.includes(k)));
      if (matched) glyph = matched[0];
      else if (concept.trim()) {
        // Freeform input: hash into a deterministic visual family so each typed concept yields a different mark
        let h = 0; for (let i=0; i<concept.length; i++) h = (h*31 + concept.charCodeAt(i)) >>> 0;
        const pool = ['abstract','hex','circle','square','triangle','wave','star','arrow','drop','leaf'];
        glyph = pool[h % pool.length];
      } else {
        // Market fallback
        const m = brand.market || '';
        if (['hvac','plumbing'].includes(m)) glyph = 'flame';
        else if (m === 'electric') glyph = 'bolt';
        else if (m === 'law' || m === 'civic') glyph = 'shield';
        else if (m === 'medical') glyph = 'plus';
        else if (m === 'nonprofit') glyph = 'leaf';
        else if (m === 'ecomm') glyph = 'arrow';
        else if (m === 'education') glyph = 'star';
      }
    }

    // Dynamic size — scales to available width
    const markSize = size === 'lg' ? 44 : size === 'sm' ? 22 : 32;
    const round = styleSpec.round;
    const sw = styleSpec.strokeW;

    const SVG = (
      <svg width={markSize} height={markSize} viewBox="0 0 32 32" style={{ flexShrink:0 }}>
        {glyph === 'abstract'   && (<g><rect x="3" y="3" width="14" height="14" rx={round} fill={markColor}/><circle cx="22" cy="22" r="7" fill="none" stroke={markColor} strokeWidth={sw}/></g>)}
        {glyph === 'monogram'   && (<g><rect x="2" y="2" width="28" height="28" rx={round} fill={markColor}/><text x="16" y="22" textAnchor="middle" fontSize={initials.length > 1 ? 13 : 16} fontWeight="800" fill="#fff" fontFamily={`${brand.fontHead}, sans-serif`}>{initials}</text></g>)}
        {glyph === 'flame'      && (<path d="M16 3c0 6-8 8-8 16a8 8 0 0016 0c0-4-3-6-3-10-2 3-5 3-5-6z" fill={markColor}/>)}
        {glyph === 'bolt'       && (<path d="M18 2L6 18h8l-2 12 14-18h-8l2-10z" fill={markColor}/>)}
        {glyph === 'shield'     && (<path d="M16 2l12 4v10c0 8-5 12-12 14-7-2-12-6-12-14V6l12-4z" fill={markColor}/>)}
        {glyph === 'hex'        && (<path d="M16 2l12 7v14l-12 7-12-7V9z" fill="none" stroke={markColor} strokeWidth={sw+1}/>)}
        {glyph === 'plus'       && (<g><rect x="3" y="3" width="26" height="26" rx={round} fill={markColor}/><rect x="14" y="7" width="4" height="18" fill="#fff"/><rect x="7" y="14" width="18" height="4" fill="#fff"/></g>)}
        {glyph === 'drop'       && (<path d="M16 3c-5 6-9 10-9 16a9 9 0 0018 0c0-6-4-10-9-16z" fill={markColor}/>)}
        {glyph === 'leaf'       && (<path d="M4 28c0-14 10-24 24-24 0 14-10 24-24 24z" fill={markColor}/>)}
        {glyph === 'star'       && (<path d="M16 2l4 10 10 1-8 7 3 10-9-6-9 6 3-10-8-7 10-1z" fill={markColor}/>)}
        {glyph === 'arrow'      && (<g><circle cx="16" cy="16" r="13" fill="none" stroke={markColor} strokeWidth={sw+.5}/><path d="M10 16h12m-5-5l5 5-5 5" fill="none" stroke={markColor} strokeWidth={sw+.5} strokeLinecap="round" strokeLinejoin="round"/></g>)}
        {glyph === 'circle'     && (<g><circle cx="16" cy="16" r="13" fill="none" stroke={markColor} strokeWidth={sw+1}/><circle cx="16" cy="16" r="5" fill={markColor}/></g>)}
        {glyph === 'square'     && (<g><rect x="4" y="4" width="24" height="24" rx={round} fill="none" stroke={markColor} strokeWidth={sw+1}/><rect x="11" y="11" width="10" height="10" rx={Math.max(0, round-2)} fill={markColor}/></g>)}
        {glyph === 'triangle'   && (<path d="M16 3l14 26H2z" fill={markColor}/>)}
        {glyph === 'wave'       && (<path d="M2 18c4-8 8-8 12 0s8 8 16 0" fill="none" stroke={markColor} strokeWidth={sw+2} strokeLinecap="round"/>)}
      </svg>
    );

    // Auto-scale wordmark to fit container width
    const baseFS = size === 'lg' ? 1.4 : size === 'sm' ? 0.78 : 1.05;
    const nameLen = c.length;
    const scale = orientation === 'stacked'
      ? (nameLen > 22 ? 0.6 : nameLen > 17 ? 0.72 : nameLen > 13 ? 0.85 : 1)
      : (nameLen > 22 ? 0.55 : nameLen > 17 ? 0.65 : nameLen > 13 ? 0.78 : 1);
    const fs = (baseFS + styleSpec.fontShift) * scale;
    const fontStack = styleSpec.serif
      ? `'DM Serif Display', 'Playfair Display', Georgia, serif`
      : `${brand.fontHead}, sans-serif`;

    const iconOnly = orientation === 'iconOnly';
    if (iconOnly) return SVG;

    const stacked = orientation === 'stacked';

    return (
      <div style={{
        display:'flex',
        flexDirection: stacked ? 'column' : 'row',
        alignItems:'center',
        gap: wordmarkOnly ? 0 : (stacked ? 8 : (size === 'lg' ? 12 : 9)),
        minWidth:0, maxWidth:'100%',
      }}>
        {!wordmarkOnly && SVG}
        <div style={{
          display:'flex', flexDirection:'column',
          alignItems: stacked ? 'center' : 'flex-start',
          textAlign: stacked ? 'center' : 'left',
          minWidth:0, gap:2, overflow:'hidden',
        }}>
          <div style={{
            fontFamily: fontStack,
            fontWeight: styleSpec.weight,
            fontSize: `${fs}rem`,
            color: wordColor,
            letterSpacing: styleSpec.tracking,
            textTransform: styleSpec.case,
            lineHeight: 1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', maxWidth:'100%',
            fontStyle: style === 'classic' ? 'italic' : 'normal',
          }}>{c}</div>
          {brand.slogan && showSlogan && (
            <div style={{
              fontFamily:`${brand.fontBody}, sans-serif`,
              fontSize: size === 'lg' ? '.62rem' : '.52rem',
              opacity:.65, color: wordColor,
              letterSpacing: style === 'luxury' ? '.2em' : '.08em',
              textTransform:'uppercase',
              lineHeight:1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', maxWidth:'100%',
            }}>{brand.slogan}</div>
          )}
        </div>
      </div>
    );
  }

  function StepBrand({ brand, setBrand }) {
    const Icon = window.Icon;
    const STYLES = ['modern','classic','bold','minimal','playful','luxury'];
    const MARKETS = ['hvac','plumbing','electric','law','medical','nonprofit','civic','ecomm','education','other'];
    // Google Fonts library — grouped by role
    const GOOGLE_HEAD = [
      { g:'Sans', fonts:['Inter','Space Grotesk','DM Sans','Manrope','Outfit','Plus Jakarta Sans','Work Sans','Nunito','Montserrat','Poppins','Rubik','Urbanist','Archivo'] },
      { g:'Display', fonts:['Orbitron','Bebas Neue','Anton','Righteous','Unica One','Fraunces','Syne','Oswald'] },
      { g:'Serif', fonts:['Playfair Display','DM Serif Display','Merriweather','Lora','Libre Baskerville','Cormorant Garamond','EB Garamond','Crimson Pro'] },
      { g:'Script / Unique', fonts:['Caveat','Pacifico','Dancing Script','Sacramento','Permanent Marker','Shrikhand'] },
      { g:'Mono', fonts:['JetBrains Mono','Fira Code','Space Mono','IBM Plex Mono'] },
    ];
    const GOOGLE_BODY = [
      { g:'Sans', fonts:['Inter','Open Sans','Lato','Roboto','Source Sans 3','Nunito Sans','DM Sans','Work Sans','Manrope','Public Sans','Mulish','IBM Plex Sans','Rubik'] },
      { g:'Serif', fonts:['Lora','Merriweather','PT Serif','Source Serif 4','Crimson Text','Libre Caslon Text'] },
      { g:'Mono', fonts:['JetBrains Mono','IBM Plex Mono','Roboto Mono','Space Mono','Fira Code'] },
    ];
    const fontSource = brand.fontSource || 'google';
    const LOGO_VARIANTS = [
      { id:'white',   label:'All White',    bg:'#0f0f12', fg:'#ffffff' },
      { id:'black',   label:'All Black',    bg:'#f4f5f7', fg:'#0f0f12' },
      { id:'colored', label:'Colored',      bg:'#ffffff', fg:brand.colors[0] },
      { id:'mixed',   label:'Mixed / Transparent', bg:'transparent', fg:brand.colors[0], mixed:true },
    ];

    // Dynamically inject Google Fonts @import when fonts change
    React.useEffect(() => {
      if (fontSource !== 'google') return;
      const families = [brand.fontHead, brand.fontBody].filter(Boolean).map(f => f.replace(/\s/g,'+'));
      if (!families.length) return;
      const id = 'kb-gfont-' + families.join('-');
      if (document.getElementById(id)) return;
      const link = document.createElement('link');
      link.id = id; link.rel = 'stylesheet';
      link.href = `https://fonts.googleapis.com/css2?${families.map(f => `family=${f}:wght@300;400;500;600;700;800;900`).join('&')}&display=swap`;
      document.head.appendChild(link);
    }, [brand.fontHead, brand.fontBody, fontSource]);

    // Adobe Fonts (Typekit) — inject kit CSS when kit ID provided
    React.useEffect(() => {
      if (fontSource !== 'adobe' || !brand.adobeKitId) return;
      const id = 'kb-adobe-' + brand.adobeKitId;
      if (document.getElementById(id)) return;
      const link = document.createElement('link');
      link.id = id; link.rel = 'stylesheet';
      link.href = `https://use.typekit.net/${brand.adobeKitId}.css`;
      document.head.appendChild(link);
    }, [brand.adobeKitId, fontSource]);

    return (
      <div>
        <div className="grid" style={{ gridTemplateColumns:'minmax(0, 5fr) minmax(0, 7fr)', gap:14 }}>
          {/* Left: Brand inputs */}
          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="brand" size={14}/>&nbsp;Direction</h2>
              <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Drives logo + color + type generation</div>
            </div>
            <div className="card-body">
              {/* Identity */}
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Company name</div>
                <input value={brand.companyName} onChange={e => setBrand({...brand, companyName:e.target.value})}
                       placeholder="Acme Industries"
                       style={{ width:'100%', padding:'8px 10px', fontSize:'.82rem', fontWeight:600, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:'inherit' }}/>
              </div>
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Slogan / tagline</div>
                <input value={brand.slogan} onChange={e => setBrand({...brand, slogan:e.target.value})}
                       placeholder="The thing that matters, made simple."
                       style={{ width:'100%', padding:'8px 10px', fontSize:'.78rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:'inherit' }}/>
                <div style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:4 }}>Used in hero + footer + meta description</div>
              </div>
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Icon / graphic concept</div>
                <textarea value={brand.iconConcept} onChange={e => setBrand({...brand, iconConcept:e.target.value})}
                       placeholder="e.g. abstract mark, first-letter monogram, flame, lightning…"
                       rows={2}
                       style={{ width:'100%', padding:'8px 10px', fontSize:'.74rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:'inherit', resize:'vertical' }}/>
                <div style={{ display:'flex', gap:6, marginTop:6, flexWrap:'wrap' }}>
                  {['monogram','flame','spark','shield','hex','wordmark only','abstract geometric'].map(p => (
                    <button key={p} onClick={() => setBrand({...brand, iconConcept:p})}
                            style={{ padding:'3px 8px', fontSize:'.64rem', background:'var(--surface-3)', border:'1px solid var(--border)', borderRadius:10, cursor:'pointer', color:'var(--muted)', fontFamily:'inherit' }}>
                      {p}
                    </button>
                  ))}
                </div>
              </div>

              {/* Style */}
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Brand style</div>
                <div style={{ display:'flex', flexWrap:'wrap', gap:5 }}>
                  {STYLES.map(s => (
                    <button key={s} onClick={() => setBrand({...brand, style:s})}
                            style={{
                              padding:'6px 12px', fontSize:'.72rem', borderRadius:14, cursor:'pointer', textTransform:'capitalize',
                              background: brand.style === s ? 'var(--beam)' : 'var(--surface-2)',
                              color: brand.style === s ? '#001018' : 'var(--muted)',
                              border: brand.style === s ? '1px solid var(--beam)' : '1px solid var(--border)',
                              fontFamily:'inherit',
                            }}>
                      {s}
                    </button>
                  ))}
                </div>
              </div>

              {/* Market */}
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Industry / market</div>
                <select value={brand.market} onChange={e => setBrand({...brand, market:e.target.value})}
                        style={{ width:'100%', padding:'8px 10px', fontSize:'.78rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:'inherit', textTransform:'capitalize' }}>
                  {MARKETS.map(m => <option key={m} value={m}>{m}</option>)}
                </select>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', marginTop:4 }}>Drives default iconography and stock imagery library</div>
              </div>

              {/* Colors */}
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Brand colors</div>
                <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                  {brand.colors.map((c, i) => (
                    <div key={i} style={{ display:'flex', alignItems:'center', gap:4 }}>
                      <input type="color" value={c} onChange={e => {
                        const next = [...brand.colors]; next[i] = e.target.value;
                        setBrand({...brand, colors: next});
                      }} style={{ width:36, height:36, border:'1px solid var(--border)', borderRadius:6, cursor:'pointer', background:'none' }}/>
                      <span style={{ fontSize:'.66rem', fontFamily:'var(--font-mono)', color:'var(--muted)' }}>{c}</span>
                    </div>
                  ))}
                  {brand.colors.length < 5 && (
                    <button className="btn btn-ghost btn-sm" onClick={() => setBrand({...brand, colors:[...brand.colors, 'var(--beam)']})}>
                      <Icon name="plus" size={11}/>Add
                    </button>
                  )}
                </div>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', marginTop:6 }}>First color is your primary; second is your accent.</div>
              </div>

              {/* Fonts */}
              <div style={{ marginBottom:14 }}>
                <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6, display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                  <span>Typography</span>
                  <div style={{ display:'flex', gap:4 }}>
                    {[
                      { id:'google', label:'Google Fonts', desc:'Free · 1500+' },
                      { id:'adobe',  label:'Adobe Fonts',  desc:'Typekit Kit ID' },
                      { id:'system', label:'System',       desc:'No external load' },
                    ].map(s => (
                      <button key={s.id} onClick={() => setBrand({...brand, fontSource:s.id})}
                              title={s.desc}
                              style={{
                                padding:'3px 8px', fontSize:'.62rem', borderRadius:10, cursor:'pointer',
                                background: fontSource === s.id ? 'var(--beam)' : 'var(--surface-3)',
                                color: fontSource === s.id ? '#001018' : 'var(--muted)',
                                border: fontSource === s.id ? '1px solid var(--beam)' : '1px solid var(--border)',
                                fontFamily:'inherit', textTransform:'none', letterSpacing:0, fontWeight:600,
                              }}>{s.label}</button>
                    ))}
                  </div>
                </div>

                {fontSource === 'adobe' && (
                  <div style={{ padding:'10px 12px', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, marginBottom:10 }}>
                    <div style={{ fontSize:'.7rem', fontWeight:600, marginBottom:4, display:'flex', alignItems:'center', gap:6 }}>
                      <Icon name="brand" size={11}/>Adobe Fonts Kit ID
                    </div>
                    <input value={brand.adobeKitId || ''} onChange={e => setBrand({...brand, adobeKitId:e.target.value.trim()})}
                           placeholder="e.g. xyz1abc (from typekit.com/kits)"
                           style={{ width:'100%', padding:'6px 10px', fontSize:'.74rem', fontFamily:'var(--font-mono)', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:4, color:'var(--text)' }}/>
                    <div style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:6, lineHeight:1.5 }}>
                      Stored on your <a href="#" onClick={e=>{e.preventDefault();window.WPSBD?.switchTab?.('brandprofile');}} style={{ color:'var(--beam)' }}>Brand Profile</a>. Create a web kit at <code style={{ color:'var(--muted)' }}>fonts.adobe.com</code>, add the families, copy the Kit ID. Then type any family name from that kit below.
                    </div>
                  </div>
                )}

                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
                  <div>
                    <div style={{ fontSize:'.62rem', color:'var(--dim)', marginBottom:4 }}>Display / Headline</div>
                    {fontSource === 'google' ? (
                      <select value={brand.fontHead} onChange={e => setBrand({...brand, fontHead:e.target.value})}
                              style={{ width:'100%', padding:'8px 10px', fontSize:'.78rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:`${brand.fontHead}, inherit` }}>
                        {GOOGLE_HEAD.map(grp => (
                          <optgroup key={grp.g} label={grp.g}>
                            {grp.fonts.map(f => <option key={f} value={f}>{f}</option>)}
                          </optgroup>
                        ))}
                      </select>
                    ) : (
                      <input value={brand.fontHead} onChange={e => setBrand({...brand, fontHead:e.target.value})}
                             placeholder={fontSource === 'adobe' ? 'e.g. Proxima Nova' : 'e.g. system-ui'}
                             style={{ width:'100%', padding:'8px 10px', fontSize:'.78rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:`${brand.fontHead}, inherit` }}/>
                    )}
                    <div style={{ marginTop:6, padding:'8px 10px', background:'var(--surface-2)', borderRadius:4, fontFamily:`${brand.fontHead}, sans-serif`, fontSize:'1.1rem', fontWeight:700, lineHeight:1 }}>Aa — Headline 123</div>
                  </div>
                  <div>
                    <div style={{ fontSize:'.62rem', color:'var(--dim)', marginBottom:4 }}>Body / Paragraph</div>
                    {fontSource === 'google' ? (
                      <select value={brand.fontBody} onChange={e => setBrand({...brand, fontBody:e.target.value})}
                              style={{ width:'100%', padding:'8px 10px', fontSize:'.78rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:`${brand.fontBody}, inherit` }}>
                        {GOOGLE_BODY.map(grp => (
                          <optgroup key={grp.g} label={grp.g}>
                            {grp.fonts.map(f => <option key={f} value={f}>{f}</option>)}
                          </optgroup>
                        ))}
                      </select>
                    ) : (
                      <input value={brand.fontBody} onChange={e => setBrand({...brand, fontBody:e.target.value})}
                             placeholder={fontSource === 'adobe' ? 'e.g. Source Sans 3' : 'e.g. system-ui'}
                             style={{ width:'100%', padding:'8px 10px', fontSize:'.78rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, color:'var(--text)', fontFamily:`${brand.fontBody}, inherit` }}/>
                    )}
                    <div style={{ marginTop:6, padding:'8px 10px', background:'var(--surface-2)', borderRadius:4, fontFamily:`${brand.fontBody}, sans-serif`, fontSize:'.82rem', lineHeight:1.4 }}>The quick brown fox jumps over the lazy dog.</div>
                  </div>
                </div>
                <div style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:6 }}>
                  {fontSource === 'google' && '✓ Auto-loaded from Google Fonts CDN · open-license · free forever'}
                  {fontSource === 'adobe' && (brand.adobeKitId ? `✓ Kit ${brand.adobeKitId} loaded · weights per your kit config` : '⚠ Add Kit ID above to load Adobe Fonts')}
                  {fontSource === 'system' && 'Uses visitor\'s OS fonts · zero load time · limited aesthetics'}
                </div>
              </div>

              {/* Existing brand assets */}
              <div style={{ padding:12, background:'var(--surface-2)', borderRadius:6, border:'1px solid var(--border)' }}>
                <div style={{ fontSize:'.72rem', fontWeight:600, marginBottom:8 }}>Existing brand assets</div>
                <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                  <label style={{ fontSize:'.74rem', display:'flex', alignItems:'center', gap:8, cursor:'pointer' }}>
                    <input type="checkbox" checked={brand.hasLogo} onChange={e => setBrand({...brand, hasLogo:e.target.checked})}/>
                    I already have a logo (upload next)
                  </label>
                  <label style={{ fontSize:'.74rem', display:'flex', alignItems:'center', gap:8, cursor:'pointer' }}>
                    <input type="checkbox" checked={brand.hasBrand} onChange={e => setBrand({...brand, hasBrand:e.target.checked})}/>
                    Pull from existing Brand Profile
                  </label>
                  <button className="btn btn-ghost btn-sm" style={{ alignSelf:'flex-start', marginTop:4 }} onClick={() => window.WPSBD?.switchTab?.('brandprofile')}>
                    <Icon name="external" size={11}/>Open Brand Profile
                  </button>
                </div>
              </div>
            </div>
          </div>

          {/* Right: Logo variants preview */}
          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="palette" size={14}/>&nbsp;Logo variants</h2>
              <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>3 layouts × 4 color variants</div>
            </div>
            <div className="card-body">
              <div style={{ fontSize:'.7rem', color:'var(--muted)', marginBottom:10 }}>
                Every kit ships all layouts at every color variant. Pick the primary the site header leads with.
              </div>

              {/* Orientation picker */}
              <div style={{ display:'flex', gap:4, marginBottom:10, padding:3, background:'var(--surface-2)', borderRadius:6 }}>
                {[
                  { id:'horizontal', label:'Horizontal', icon:'rows' },
                  { id:'stacked',    label:'Stacked',    icon:'cols' },
                  { id:'iconOnly',   label:'Icon only',  icon:'brand' },
                ].map(o => {
                  const active = (brand.logoOrientation || 'horizontal') === o.id;
                  return (
                    <button key={o.id} onClick={() => setBrand({...brand, logoOrientation:o.id})}
                            style={{
                              flex:1, padding:'6px 10px', fontSize:'.7rem', borderRadius:4, cursor:'pointer',
                              background: active ? 'var(--beam)' : 'transparent',
                              color: active ? '#001018' : 'var(--muted)',
                              border:'none', fontFamily:'inherit', fontWeight:600,
                              display:'flex', alignItems:'center', justifyContent:'center', gap:5,
                            }}>
                      <Icon name={o.icon} size={11}/>{o.label}
                    </button>
                  );
                })}
              </div>

              <div className="grid" style={{ gridTemplateColumns:'1fr 1fr', gap:10 }}>
                {LOGO_VARIANTS.map(v => {
                  const isSel = brand.logoVariant === v.id;
                  const markColor = v.mixed ? brand.colors[0] : v.fg;
                  const wordColor = v.mixed ? brand.colors[0] : v.fg;
                  return (
                    <button key={v.id} onClick={() => setBrand({...brand, logoVariant:v.id})}
                            style={{
                              padding:0, cursor:'pointer', overflow:'hidden',
                              border: isSel ? '2px solid var(--beam)' : '1px solid var(--border)',
                              borderRadius:8, fontFamily:'inherit', color:'var(--text)', textAlign:'left',
                            }}>
                      <div style={{
                        minHeight:130, background: v.mixed
                          ? `repeating-conic-gradient(var(--surface-2) 0% 25%, var(--surface) 0% 50%) 50% / 16px 16px, ${v.bg}`
                          : v.bg,
                        display:'flex', alignItems:'center', justifyContent:'center', padding:'22px 14px',
                      }}>
                        <LogoMark brand={brand} markColor={markColor} wordColor={wordColor}
                                  orientation={brand.logoOrientation || 'horizontal'}
                                  size={brand.logoOrientation === 'iconOnly' ? 'lg' : 'md'}/>
                      </div>
                      <div style={{ padding:'8px 10px', display:'flex', alignItems:'center', gap:6, background:'var(--surface-2)' }}>
                        <div style={{
                          width:12, height:12, borderRadius:'50%', flexShrink:0,
                          background: isSel ? 'var(--beam)' : 'transparent',
                          border: isSel ? 'none' : '1px solid var(--border)',
                        }}/>
                        <div style={{ fontSize:'.74rem', fontWeight:600 }}>{v.label}</div>
                      </div>
                    </button>
                  );
                })}
              </div>

              {/* Elementor logo spec + vector note */}
              <div style={{ marginTop:12, padding:'10px 12px', background:'rgba(111,235,255,.06)', border:'1px solid rgba(111,235,255,.2)', borderRadius:6, display:'flex', alignItems:'flex-start', gap:10 }}>
                <Icon name="info" size={12} style={{ color:'var(--beam)', marginTop:2, flexShrink:0 }}/>
                <div style={{ fontSize:'.66rem', color:'var(--muted)', lineHeight:1.55 }}>
                  <strong style={{ color:'var(--beam)' }}>Elementor header spec:</strong> recommended site-logo dimensions <strong style={{ color:'var(--text)' }}>350 × 100 px</strong>. All logo marks on this page are rendered as <strong style={{ color:'var(--text)' }}>vector SVG</strong> — scale losslessly from favicon (16 px) through car-wrap (2 m+). Export covers both: <span style={{ color:'var(--dim)' }}>SVG (infinite) + PNG @ 350×100 / 700×200 / 1400×400 for Retina.</span>
                </div>
              </div>

              {/* Brand Kit export teaser */}
              <div style={{ marginTop:10, padding:12, background:'var(--surface-2)', borderRadius:6, border:'1px solid var(--border)' }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
                  <div style={{ fontSize:'.74rem', fontWeight:600, display:'flex', alignItems:'center', gap:6 }}>
                    <Icon name="download" size={12}/>Brand Kit export
                  </div>
                  <span className="tag" style={{ fontSize:'.58rem' }}>ships with every kit</span>
                </div>
                <div style={{ fontSize:'.64rem', color:'var(--dim)', lineHeight:1.55, marginBottom:10 }}>
                  One ZIP containing everything a client, printer, or agency needs — no repeat work.
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, fontSize:'.62rem' }}>
                  {[
                    { l:'Logo suite',     d:'SVG + PNG 350/700/1400 + EPS + PDF (print)' },
                    { l:'Favicon pack',   d:'512 master + ico + 16/32/48 + apple-touch + android-chrome' },
                    { l:'Color tokens',   d:'HEX · RGB · CMYK · Pantone + CSS vars + JSON + ASE (Adobe)' },
                    { l:'Type specimen', d:'Heading + body + weights, PDF + CSS + Adobe Fonts IDs' },
                    { l:'Brand guide',   d:'8-page PDF: logo rules, clearspace, misuse, voice' },
                    { l:'Social avatars', d:'Round + square, 400 / 800 / 1500, all channels' },
                  ].map(item => (
                    <div key={item.l} style={{ padding:'7px 9px', background:'var(--surface)', borderRadius:4, border:'1px solid var(--border)' }}>
                      <div style={{ fontWeight:600, color:'var(--text)', marginBottom:2 }}>{item.l}</div>
                      <div style={{ color:'var(--dim)', lineHeight:1.4 }}>{item.d}</div>
                    </div>
                  ))}
                </div>
                <button style={{
                  marginTop:10, width:'100%', padding:'8px 12px', fontSize:'.72rem', fontWeight:600,
                  background:'var(--surface)', border:'1px dashed var(--border)', color:'var(--muted)',
                  borderRadius:4, cursor:'pointer', fontFamily:'inherit',
                  display:'flex', alignItems:'center', justifyContent:'center', gap:6,
                }}
                onClick={() => alert('Brand Kit export — queued. Compiles logos, favicons, color tokens, type specimen, guidelines PDF, and social avatars into a single ZIP. Triggers on Step 6 (Export) unless downloaded individually here.')}>
                  <Icon name="download" size={11}/>Preview / download Brand Kit ZIP
                </button>
              </div>

              {/* Marketing Materials teaser — links to future module */}
              <div style={{ marginTop:10, padding:12, background:'linear-gradient(135deg, rgba(111,235,255,.05), rgba(193,125,255,.04))', borderRadius:6, border:'1px dashed var(--border)' }}>
                <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:10, marginBottom:8 }}>
                  <div>
                    <div style={{ fontSize:'.72rem', fontWeight:700, color:'var(--text)', marginBottom:3, display:'flex', alignItems:'center', gap:6 }}>
                      <Icon name="layers" size={12} style={{ color:'var(--beam)' }}/>Marketing Materials
                      <span className="tag" style={{ fontSize:'.52rem', background:'var(--surface)', color:'var(--beam)', border:'1px solid var(--beam)' }}>proposed · new tab</span>
                    </div>
                    <div style={{ fontSize:'.62rem', color:'var(--dim)', lineHeight:1.55 }}>
                      Generate print + digital collateral from this brand data — <strong style={{ color:'var(--muted)' }}>for branding agencies to deliver complete packages to their clients</strong>, not just a website.
                    </div>
                  </div>
                </div>
                <div style={{ display:'flex', flexWrap:'wrap', gap:5, marginBottom:8 }}>
                  {['Business cards','Letterhead','Envelopes','Yard signs','Vehicle wraps','Email signatures','Social templates','Brochures','Flyers','Trade-show banners','Door hangers','Invoices'].map(t => (
                    <span key={t} className="tag" style={{ fontSize:'.56rem', background:'var(--surface-2)', color:'var(--muted)', border:'1px solid var(--border)' }}>{t}</span>
                  ))}
                </div>
                <div style={{ display:'flex', gap:6 }}>
                  <button style={{
                    flex:1, padding:'7px 10px', fontSize:'.66rem', fontWeight:600,
                    background:'var(--beam)', color:'#001018', border:'none',
                    borderRadius:4, cursor:'pointer', fontFamily:'inherit',
                  }}
                  onClick={() => alert('Marketing Materials — coming in next sprint.\n\nThe module will:\n• Pull this brand kit (logo, colors, type, slogan, market) + scan-data contact info\n• Pre-populate print + digital templates (cards, signage, wraps, email sigs, social)\n• Apply the same optimization guarantee: ADA contrast, print CMYK color-accurate, brand-consistent, local-SEO variants (service area in copy/NAP)\n• One-click send to print partners')}>
                    Open Marketing Materials →
                  </button>
                  <button style={{
                    padding:'7px 10px', fontSize:'.66rem', fontWeight:600,
                    background:'var(--surface)', color:'var(--muted)', border:'1px solid var(--border)',
                    borderRadius:4, cursor:'pointer', fontFamily:'inherit',
                  }}
                  onClick={() => alert('Roadmap note captured — Marketing Materials module.\n\nConcept:\n• Canvas-based print templates pre-populated with this brand kit (logo, colors, type, contact)\n• InDesign / Canva-equivalent layouts — business cards, signage, vehicle wraps, email sigs\n• Bleed / safe-area / CMYK preview built in\n• One-click send to print partner (Moo, VistaPrint, Signs.com API)\n• Agency-mode: bulk-generate across all client brands')}>
                    Roadmap note
                  </button>
                </div>
              </div>

              {/* Favicon + mobile icon preview — editable */}
              {(() => {
                const favStyle   = brand.faviconStyle   || 'initials';      // initials | custom | glyph | upload
                const favText    = brand.faviconText    ?? ((brand.companyName || 'B').split(/\s+/).filter(Boolean).map(w => w[0]).join('').toUpperCase().slice(0,3) || 'B');
                const favGlyph   = brand.faviconGlyph   || 'brand';
                const favShape   = brand.faviconShape   || 'squircle';      // squircle | circle | square
                const favBgMode  = brand.faviconBgMode  || 'solid';         // solid | gradient | transparent
                const favUpload  = brand.faviconUpload  || null;
                const shapeRadius = (px) => favShape === 'circle' ? '50%' : favShape === 'square' ? 2 : Math.round(px * 0.22);

                const renderFavicon = (size) => {
                  const radius = shapeRadius(size);
                  const bg = favBgMode === 'transparent' ? 'transparent'
                    : favBgMode === 'gradient' ? `linear-gradient(135deg, ${brand.colors[0]}, ${brand.colors[1] || brand.colors[0]})`
                    : brand.colors[0];
                  const common = {
                    width: size, height: size, background: bg, borderRadius: radius,
                    display:'flex', alignItems:'center', justifyContent:'center',
                    color:'#fff', lineHeight:1, overflow:'hidden', flexShrink:0,
                    border: favBgMode === 'transparent' ? '1px dashed var(--border)' : 'none',
                  };
                  if (favStyle === 'upload' && favUpload) {
                    return <img src={favUpload} alt="" style={{ ...common, objectFit:'cover' }}/>;
                  }
                  if (favStyle === 'glyph') {
                    const glyphMap = {
                      brand:'◆', flame:'🔥', bolt:'⚡', shield:'🛡', hex:'⬡', plus:'+', star:'★', leaf:'✦', waves:'∿', circle:'●',
                    };
                    return (
                      <div style={{ ...common, fontSize: size * 0.58, fontWeight:700 }}>
                        {glyphMap[favGlyph] || '◆'}
                      </div>
                    );
                  }
                  // initials OR custom text
                  const text = (favStyle === 'custom' ? favText : favText) || 'B';
                  const len = text.length;
                  // auto-scale text to fit
                  const fontSize = size < 20 ? (len > 2 ? 6 : 9)
                                 : size < 36 ? (len > 2 ? 10 : 14)
                                 : size < 56 ? (len > 2 ? 16 : 22)
                                 : (len > 2 ? 22 : 28);
                  return (
                    <div style={{ ...common, fontFamily:`${brand.fontHead}, sans-serif`, fontWeight:900, fontSize }}>
                      {text}
                    </div>
                  );
                };

                return (
                  <div style={{ marginTop:14, padding:12, background:'var(--surface-2)', borderRadius:6, border:'1px solid var(--border)' }}>
                    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
                      <div style={{ fontSize:'.74rem', fontWeight:600, display:'flex', alignItems:'center', gap:6 }}>
                        <Icon name="globe" size={12}/>Favicon &amp; app-icon — editable
                      </div>
                      <span className="tag" style={{ fontSize:'.58rem' }}>live preview</span>
                    </div>

                    {/* Style switcher */}
                    <div style={{ display:'flex', gap:4, marginBottom:10 }}>
                      {[
                        { id:'initials', label:'Initials', hint:'auto from company name' },
                        { id:'custom',   label:'Custom',   hint:'type your own 1–3 chars' },
                        { id:'glyph',    label:'Glyph',    hint:'pick a symbol' },
                        { id:'upload',   label:'Upload',   hint:'your own PNG/SVG' },
                      ].map(s => {
                        const active = favStyle === s.id;
                        return (
                          <button key={s.id} title={s.hint}
                                  onClick={() => setBrand({...brand, faviconStyle:s.id})}
                                  style={{
                                    flex:1, padding:'6px 8px', fontSize:'.66rem', borderRadius:4, cursor:'pointer',
                                    background: active ? 'var(--beam)' : 'var(--surface)',
                                    color: active ? '#001018' : 'var(--muted)',
                                    border: active ? '1px solid var(--beam)' : '1px solid var(--border)',
                                    fontFamily:'inherit', fontWeight:600,
                                  }}>{s.label}</button>
                        );
                      })}
                    </div>

                    {/* Editor — varies by style */}
                    <div style={{ marginBottom:10, padding:8, background:'var(--surface)', borderRadius:4, display:'grid', gridTemplateColumns:'1fr auto', gap:8, alignItems:'center' }}>
                      {favStyle === 'initials' && (
                        <>
                          <input value={favText}
                                 onChange={e => setBrand({...brand, faviconText:e.target.value.slice(0,3).toUpperCase()})}
                                 maxLength={3}
                                 placeholder="Auto (CD, AB, etc.)"
                                 style={{ padding:'6px 8px', fontSize:'.72rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:3, color:'var(--text)', fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'.1em' }}/>
                          <button onClick={() => setBrand({...brand, faviconText:(brand.companyName || 'B').split(/\s+/).filter(Boolean).map(w => w[0]).join('').toUpperCase().slice(0,3)})}
                                  style={{ padding:'5px 10px', fontSize:'.62rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:3, color:'var(--muted)', cursor:'pointer', fontFamily:'inherit' }}>
                            ↻ Reset from name
                          </button>
                        </>
                      )}
                      {favStyle === 'custom' && (
                        <>
                          <input value={favText} onChange={e => setBrand({...brand, faviconText:e.target.value.slice(0,3).toUpperCase()})}
                                 maxLength={3} placeholder="e.g. CD, A, NOVA"
                                 style={{ padding:'6px 8px', fontSize:'.72rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:3, color:'var(--text)', fontFamily:'var(--font-mono)', textTransform:'uppercase', letterSpacing:'.1em' }}/>
                          <span style={{ fontSize:'.62rem', color:'var(--dim)' }}>{favText.length}/3 chars</span>
                        </>
                      )}
                      {favStyle === 'glyph' && (
                        <div style={{ gridColumn:'1 / -1', display:'flex', gap:5, flexWrap:'wrap' }}>
                          {[
                            { id:'brand', s:'◆' }, { id:'flame', s:'🔥' }, { id:'bolt', s:'⚡' },
                            { id:'shield', s:'🛡' }, { id:'hex', s:'⬡' }, { id:'plus', s:'+' },
                            { id:'star', s:'★' }, { id:'leaf', s:'✦' }, { id:'waves', s:'∿' }, { id:'circle', s:'●' },
                          ].map(g => (
                            <button key={g.id} onClick={() => setBrand({...brand, faviconGlyph:g.id})}
                                    style={{
                                      width:30, height:30, borderRadius:4, cursor:'pointer',
                                      background: favGlyph === g.id ? brand.colors[0] : 'var(--surface-2)',
                                      color: favGlyph === g.id ? '#fff' : 'var(--muted)',
                                      border: favGlyph === g.id ? '1px solid var(--beam)' : '1px solid var(--border)',
                                      fontSize:14, display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'inherit',
                                    }}>{g.s}</button>
                          ))}
                        </div>
                      )}
                      {favStyle === 'upload' && (
                        <>
                          <input type="file" accept="image/png,image/svg+xml,image/jpeg"
                                 onChange={e => {
                                   const f = e.target.files?.[0];
                                   if (!f) return;
                                   const reader = new FileReader();
                                   reader.onload = () => setBrand({...brand, faviconUpload:reader.result});
                                   reader.readAsDataURL(f);
                                 }}
                                 style={{ fontSize:'.7rem', color:'var(--muted)', fontFamily:'inherit' }}/>
                          {favUpload && (
                            <button onClick={() => setBrand({...brand, faviconUpload:null})}
                                    style={{ padding:'5px 10px', fontSize:'.62rem', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:3, color:'var(--rose)', cursor:'pointer', fontFamily:'inherit' }}>
                              Clear
                            </button>
                          )}
                        </>
                      )}
                    </div>

                    {/* Shape + bg controls */}
                    <div style={{ display:'flex', gap:10, marginBottom:12, fontSize:'.64rem' }}>
                      <div style={{ flex:1 }}>
                        <div style={{ color:'var(--dim)', marginBottom:4, fontSize:'.6rem', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:700 }}>Shape</div>
                        <div style={{ display:'flex', gap:4 }}>
                          {[{id:'squircle',l:'Squircle'},{id:'circle',l:'Circle'},{id:'square',l:'Square'}].map(o => {
                            const active = favShape === o.id;
                            return (
                              <button key={o.id} onClick={() => setBrand({...brand, faviconShape:o.id})}
                                      style={{ flex:1, padding:'5px 8px', fontSize:'.64rem', borderRadius:3, cursor:'pointer', background: active ? 'var(--surface-3)' : 'var(--surface)', color: active ? 'var(--text)' : 'var(--dim)', border: active ? '1px solid var(--beam)' : '1px solid var(--border)', fontFamily:'inherit' }}>{o.l}</button>
                            );
                          })}
                        </div>
                      </div>
                      <div style={{ flex:1 }}>
                        <div style={{ color:'var(--dim)', marginBottom:4, fontSize:'.6rem', textTransform:'uppercase', letterSpacing:'.06em', fontWeight:700 }}>Background</div>
                        <div style={{ display:'flex', gap:4 }}>
                          {[{id:'solid',l:'Solid'},{id:'gradient',l:'Gradient'},{id:'transparent',l:'Trans'}].map(o => {
                            const active = favBgMode === o.id;
                            return (
                              <button key={o.id} onClick={() => setBrand({...brand, faviconBgMode:o.id})}
                                      style={{ flex:1, padding:'5px 8px', fontSize:'.64rem', borderRadius:3, cursor:'pointer', background: active ? 'var(--surface-3)' : 'var(--surface)', color: active ? 'var(--text)' : 'var(--dim)', border: active ? '1px solid var(--beam)' : '1px solid var(--border)', fontFamily:'inherit' }}>{o.l}</button>
                            );
                          })}
                        </div>
                      </div>
                    </div>

                    {/* Live preview grid */}
                    <div style={{ display:'flex', alignItems:'flex-end', gap:14, flexWrap:'wrap', padding:'10px 4px' }}>
                      {[
                        { size:16, label:'16 · tab' },
                        { size:32, label:'32 · bookmark' },
                        { size:48, label:'48 · Windows' },
                        { size:64, label:'64 · retina' },
                      ].map(f => (
                        <div key={f.size} style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:4 }}>
                          {renderFavicon(f.size)}
                          <div style={{ fontSize:'.54rem', color:'var(--dim)', fontFamily:'var(--font-mono)' }}>{f.label}</div>
                        </div>
                      ))}
                      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:4, marginLeft:8, paddingLeft:12, borderLeft:'1px solid var(--border)' }}>
                        {renderFavicon(60)}
                        <div style={{ fontSize:'.54rem', color:'var(--dim)', fontFamily:'var(--font-mono)' }}>60 · iOS/Android</div>
                      </div>
                      {/* Elementor master @ 512 */}
                      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:4, marginLeft:8, paddingLeft:12, borderLeft:'1px solid var(--border)', position:'relative' }}>
                        {/* scaled-down preview of 512 master */}
                        <div style={{ position:'relative' }}>
                          {renderFavicon(72)}
                          <span style={{
                            position:'absolute', top:-6, right:-8, background:'var(--beam)', color:'#001018',
                            fontSize:'.5rem', fontWeight:800, padding:'1px 5px', borderRadius:3, letterSpacing:'.04em',
                            fontFamily:'var(--font-mono)', textTransform:'uppercase',
                          }}>master</span>
                        </div>
                        <div style={{ fontSize:'.54rem', color:'var(--muted)', fontFamily:'var(--font-mono)', fontWeight:700 }}>512 · Elementor</div>
                      </div>
                    </div>

                    {/* Elementor spec callout */}
                    <div style={{ marginTop:10, padding:'8px 10px', background:'rgba(111,235,255,.06)', border:'1px solid rgba(111,235,255,.2)', borderRadius:4, display:'flex', alignItems:'flex-start', gap:8 }}>
                      <Icon name="info" size={11} style={{ color:'var(--beam)', marginTop:2, flexShrink:0 }}/>
                      <div style={{ fontSize:'.62rem', color:'var(--muted)', lineHeight:1.5 }}>
                        <strong style={{ color:'var(--beam)' }}>Elementor spec:</strong> site identity favicon master is <strong style={{ color:'var(--text)' }}>512 × 512 px</strong> (square, PNG preferred). WP auto-downsamples for tab / bookmark / touch-icon sizes — we export the full set from this one master.
                      </div>
                    </div>

                    <div style={{ fontSize:'.62rem', color:'var(--dim)', marginTop:8, lineHeight:1.5 }}>
                      Exports: <span style={{ color:'var(--muted)', fontWeight:600 }}>favicon-512.png</span> (Elementor master) + favicon.ico + favicon-16/32/48.png + apple-touch-icon 180 + android-chrome 192/512 + site.webmanifest · all wired into the WP header.
                    </div>
                  </div>
                );
              })()}

              {/* Optimization Guarantee — ADA · SEO · Brand · Local */}
              <div style={{ marginTop:10, padding:12, background:'var(--surface-2)', borderRadius:6, border:'1px solid var(--border)' }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
                  <div style={{ fontSize:'.72rem', fontWeight:700, display:'flex', alignItems:'center', gap:6 }}>
                    <Icon name="shield" size={12} style={{ color:'var(--beam)' }}/>Optimization guarantee
                  </div>
                  <span className="tag" style={{ fontSize:'.54rem', background:'rgba(120,220,140,.12)', color:'var(--mint)', border:'1px solid rgba(120,220,140,.3)' }}>auto-validated</span>
                </div>
                <div style={{ fontSize:'.62rem', color:'var(--dim)', lineHeight:1.5, marginBottom:10 }}>
                  Every brand asset generated here passes 4 checks, using data already pulled from Scanner, Content SEO, and plugin telemetry.
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:6 }}>
                  {[
                    {
                      icon:'shield', color:'var(--beam)', label:'ADA compliant',
                      pass:true,
                      detail:`Logo mark contrast ratio 7.8:1 (AAA). Alt text auto-injected: "${brand.companyName || 'Brand'} logo · ${brand.market || 'home services'}". Favicon has 4.5:1 min against any bg.`,
                      source:`${(window.WPSB && window.WPSB.CONSTANTS && window.WPSB.CONSTANTS.WCAG.DISPLAY) || 'WCAG 2.1 AA'} · Contrast verified`,
                    },
                    {
                      icon:'search', color:'var(--amber)', label:'SEO optimized',
                      pass:true,
                      detail:`Logo <img> uses schema.org/Organization markup · width/height attrs set · filename slug "${(brand.companyName || 'brand').toLowerCase().replace(/\s+/g,'-')}-logo.svg" · favicon tag block in <head>.`,
                      source:'Content SEO · Yoast/RankMath-compatible',
                    },
                    {
                      icon:'palette', color:'var(--purple)', label:'Brand consistent',
                      pass:true,
                      detail:`Colors match Brand Profile tokens (${(brand.colors || []).slice(0,3).join(' · ')}). Typography ${brand.fontHead || 'display'} / ${brand.fontBody || 'body'}. Clearspace + minimum-size rules exported in brand guide PDF.`,
                      source:'Brand Profile · locked tokens',
                    },
                    {
                      icon:'pin', color:'var(--rose)', label:'Local-SEO ready',
                      pass:true,
                      detail:`Service-area meta wired from Scanner NAP: "${brand.serviceArea || brand.city || '[scan data]'}${brand.state ? ', ' + brand.state : ''}". Logo alt + OG image carry "${brand.market || 'services'} in ${brand.city || '[city]'}" variants for Local Business schema.`,
                      source:'Scanner NAP · LocalBusiness schema',
                    },
                  ].map(pillar => (
                    <div key={pillar.label} style={{ padding:'8px 10px', background:'var(--surface)', borderRadius:4, border:'1px solid var(--border)' }}>
                      <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
                        <Icon name={pillar.icon} size={11} style={{ color:pillar.color }}/>
                        <span style={{ fontSize:'.66rem', fontWeight:700, color:'var(--text)' }}>{pillar.label}</span>
                        <span style={{ marginLeft:'auto', fontSize:'.52rem', color:'var(--mint)', fontFamily:'var(--font-mono)', fontWeight:700 }}>✓ PASS</span>
                      </div>
                      <div style={{ fontSize:'.58rem', color:'var(--dim)', lineHeight:1.45, marginBottom:4 }}>
                        {pillar.detail}
                      </div>
                      <div style={{ fontSize:'.54rem', color:'var(--muted)', fontFamily:'var(--font-mono)', fontWeight:600 }}>
                        ← {pillar.source}
                      </div>
                    </div>
                  ))}
                </div>
                <div style={{ marginTop:10, padding:'7px 10px', background:'var(--surface)', borderRadius:4, fontSize:'.6rem', color:'var(--dim)', lineHeight:1.5, borderLeft:'2px solid var(--beam)' }}>
                  <strong style={{ color:'var(--beam)' }}>Data sources in use:</strong> Scanner site-data (NAP, service-area, existing meta), Content SEO (target keywords, schema), Brand Profile (locked tokens), WPSB plugin telemetry (live site context). Same guarantee applies to all downstream content — page copy, blog posts, image alt, social OG, print collateral.
                </div>
              </div>

              <div style={{ marginTop:10, padding:10, background:'var(--surface)', borderRadius:6, border:'1px dashed var(--border)', display:'flex', alignItems:'flex-start', gap:8 }}>
                <Icon name="info" size={12} style={{ color:'var(--dim)', marginTop:2, flexShrink:0 }}/>
                <div style={{ fontSize:'.62rem', color:'var(--dim)', lineHeight:1.5 }}>
                  <strong style={{ color:'var(--muted)' }}>Future:</strong> full iOS / Android app-icon + splash-screen generator · PWA manifest builder · logo motion preset · all planned for a later release.
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Wireframe: Brand-preview strip */}
        <div className="card" style={{ marginTop:14 }}>
          <div className="card-head">
            <h2 className="card-title"><Icon name="info" size={14}/>&nbsp;Applied preview</h2>
            <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>How brand renders in a hero section</div>
          </div>
          <div className="card-body" style={{ padding:0 }}>
            <div style={{
              padding:'48px 36px', background: brand.colors[1] || '#0F172A',
              color: '#fff', display:'flex', alignItems:'center', justifyContent:'space-between', gap:24,
            }}>
              <div>
                <div style={{ fontSize:'.72rem', letterSpacing:'.12em', textTransform:'uppercase', color: brand.colors[0], marginBottom:8, opacity:.9 }}>{brand.companyName || 'Your Company'} · {brand.market}</div>
                <div style={{ fontFamily:`${brand.fontHead}, sans-serif`, fontSize:'2.5rem', fontWeight:700, lineHeight:1.1, marginBottom:12, letterSpacing:'-.02em' }}>{brand.slogan || 'The headline that sells the thing.'}</div>
                <div style={{ fontFamily:`${brand.fontBody}, sans-serif`, fontSize:'.95rem', lineHeight:1.6, opacity:.85, maxWidth:500, marginBottom:20 }}>Subhead copy that explains the value clearly without jargon. Replaced with real content on step 3.</div>
                <div style={{ display:'flex', gap:10 }}>
                  <div style={{ padding:'12px 20px', background: brand.colors[0], color:'#000', borderRadius:6, fontFamily:`${brand.fontBody}, sans-serif`, fontWeight:600, fontSize:'.88rem' }}>Primary CTA</div>
                  <div style={{ padding:'12px 20px', border:'1px solid rgba(255,255,255,.3)', color:'#fff', borderRadius:6, fontFamily:`${brand.fontBody}, sans-serif`, fontWeight:500, fontSize:'.88rem' }}>Secondary</div>
                </div>
              </div>
              <div style={{ width:220, height:180, background:'rgba(255,255,255,.06)', border:'1px dashed rgba(255,255,255,.2)', borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <div style={{ fontSize:'.7rem', color:'rgba(255,255,255,.5)' }}>hero image</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════════
     STEP 3 — CONTENT (wireframe)
  ═══════════════════════════════════════════════════════════════ */
  function StepContent({ content, setContent, siteType, SITE_TYPES }) {
    const Icon = window.Icon;
    const type = SITE_TYPES.find(t => t.id === siteType);
    return (
      <div>
        <div className="grid" style={{ gridTemplateColumns:'1fr 1fr', gap:14 }}>
          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="content" size={14}/>&nbsp;Content source</h2>
            </div>
            <div className="card-body">
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {[
                  { id:'upload',       label:'Upload existing content',      desc:'DOCX, PDF, CSV, or paste · we extract and slot into pages' },
                  { id:'migrate',      label:'Migrate from existing site',   desc:'Crawl + import from one of the inspiration URLs above' },
                  { id:'placeholders', label:'Start from placeholders',      desc:`We'll generate ${type?.label}-appropriate placeholder copy` },
                  { id:'ai-generate',  label:'AI-generate from brief',       desc:'Answer ~10 questions; we draft full content · consumes 2 credits' },
                ].map(o => (
                  <button key={o.id} onClick={() => setContent({...content, existing:o.id})}
                          style={{
                            padding:'14px 16px', textAlign:'left', cursor:'pointer',
                            background: content.existing === o.id ? 'var(--beam-dim)' : 'var(--surface-2)',
                            border: content.existing === o.id ? '1px solid var(--beam)' : '1px solid var(--border)',
                            borderRadius:8, fontFamily:'inherit', color:'var(--text)',
                          }}>
                    <div style={{ fontSize:'.82rem', fontWeight:600, marginBottom:3, color: content.existing === o.id ? 'var(--beam)' : 'var(--text)' }}>{o.label}</div>
                    <div style={{ fontSize:'.7rem', color:'var(--dim)' }}>{o.desc}</div>
                  </button>
                ))}
              </div>

              {content.existing === 'upload' && (
                <div style={{ marginTop:12, padding:20, background:'var(--surface-2)', border:'1px dashed var(--border)', borderRadius:8, textAlign:'center' }}>
                  <Icon name="download" size={22} style={{ transform:'rotate(180deg)', opacity:.5 }}/>
                  <div style={{ fontSize:'.82rem', fontWeight:600, marginTop:6 }}>Drop files or click to upload</div>
                  <div style={{ fontSize:'.66rem', color:'var(--dim)', marginTop:3 }}>DOCX · PDF · CSV · MD · up to 20MB each</div>
                </div>
              )}
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="sitemap" size={14}/>&nbsp;Page list · {type?.label}</h2>
              <button className="btn btn-ghost btn-sm"><Icon name="plus" size={11}/>Add page</button>
            </div>
            <div className="card-body" style={{ padding:0 }}>
              {type?.pages.map((p, i) => (
                <div key={p} style={{ padding:'11px 16px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:10 }}>
                  <span style={{ fontFamily:'var(--font-mono)', fontSize:'.64rem', color:'var(--dim)', width:18 }}>{String(i+1).padStart(2,'0')}</span>
                  <span style={{ fontSize:'.78rem', fontWeight:500, flex:1 }}>{p}</span>
                  <span style={{ fontSize:'.6rem', color:'var(--dim)', fontFamily:'var(--font-mono)' }}>4 sections</span>
                  <button style={{ background:'none', border:'none', color:'var(--dim)', cursor:'pointer' }}><Icon name="edit" size={12}/></button>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Integration links */}
        <div className="grid" style={{ gridTemplateColumns:'1fr 1fr', gap:14, marginTop:14 }}>
          <div className="card" style={{ background:'var(--surface-2)' }}>
            <div className="card-body" style={{ display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:40, height:40, borderRadius:8, background:'var(--beam-dim)', color:'var(--beam)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="spark" size={18}/>
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:'.82rem', fontWeight:600 }}>Link Content SEO</div>
                <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Pull keyword targets + SERP gaps into page copy briefs</div>
              </div>
              <label style={{ display:'flex', alignItems:'center', gap:6, fontSize:'.72rem', cursor:'pointer' }}>
                <input type="checkbox" checked={content.linkContentSEO} onChange={e => setContent({...content, linkContentSEO:e.target.checked})}/>
                On
              </label>
            </div>
          </div>
          <div className="card" style={{ background:'var(--surface-2)' }}>
            <div className="card-body" style={{ display:'flex', alignItems:'center', gap:12 }}>
              <div style={{ width:40, height:40, borderRadius:8, background:'var(--warn-dim)', color:'var(--warn)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                <Icon name="content" size={18}/>
              </div>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:'.82rem', fontWeight:600 }}>Push to Site Content</div>
                <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Once kit ships, content goes live in Site Content for edits</div>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => window.WPSBD?.switchTab?.('content')}>
                <Icon name="external" size={11}/>Open
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════════
     STEP 4 — STACK CONFIG (wireframe)
  ═══════════════════════════════════════════════════════════════ */
  function StepStack({ themeBuilder, setThemeBuilder, THEME_BUILDERS }) {
    const Icon = window.Icon;
    const cur = THEME_BUILDERS.find(t => t.id === themeBuilder);
    // Vault gating — map builder/plugin names to catalog credential ids
    const [vault] = window.useVault ? window.useVault() : [{}, ()=>{}, ()=>{}, ()=>false];
    const CATALOG = window.CREDENTIAL_CATALOG || [];
    const credByVendor = useMemo(() => {
      const map = {};
      CATALOG.forEach(c => { map[c.vendor.toLowerCase()] = c; });
      return map;
    }, [CATALOG]);
    // Resolve credential for a plugin/builder label (fuzzy match on vendor name)
    const resolveCred = (label) => {
      const key = label.toLowerCase();
      // Direct hit
      if (credByVendor[key]) return credByVendor[key];
      // Partial contains
      for (const c of CATALOG) {
        if (key.includes(c.vendor.toLowerCase()) || c.vendor.toLowerCase().includes(key)) return c;
      }
      return null;
    };
    // Builder id → catalog id
    const BUILDER_CRED = { elementor:'elementor-pro', divi:'divi', beaver:'beaver-builder', oxygen:'oxygen', bricks:'bricks' };
    const builderLicensed = (builderId) => {
      const cid = BUILDER_CRED[builderId];
      const v = vault[cid];
      return !!(v && v.status === 'valid' && Object.keys(v.values || {}).length);
    };

    const goToVault = (e) => {
      e?.preventDefault?.();
      window.WPSBD?.switchTab?.('brandprofile');
      // BrandProfile tab state is local — post a hint
      setTimeout(() => window.dispatchEvent(new CustomEvent('wpsb:brand-subtab', { detail:'vault' })), 50);
    };

    return (
      <div>
        <div className="card" style={{ marginBottom:14 }}>
          <div className="card-head">
            <h2 className="card-title"><Icon name="stack" size={14}/>&nbsp;Theme builder</h2>
            <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Builders without licenses are locked · <a href="#" onClick={goToVault} style={{ color:'var(--beam)' }}>add keys in Credential Vault</a></div>
          </div>
          <div className="card-body">
            <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(190px, 1fr))', gap:8 }}>
              {THEME_BUILDERS.map(b => {
                const licensed = builderLicensed(b.id);
                const isSel = themeBuilder === b.id;
                return (
                  <button key={b.id}
                          onClick={() => {
                            if (!licensed) {
                              window.wpsbToast?.(`Add ${b.label} license to unlock`, 'warn');
                              goToVault();
                              return;
                            }
                            setThemeBuilder(b.id);
                          }}
                          disabled={!licensed}
                          style={{
                            padding:'14px', textAlign:'left', cursor: licensed ? 'pointer' : 'not-allowed', position:'relative',
                            background: isSel ? 'var(--beam-dim)' : licensed ? 'var(--surface-2)' : 'var(--surface)',
                            border: isSel ? '1px solid var(--beam)' : licensed ? '1px solid var(--border)' : '1px dashed var(--border)',
                            borderRadius:8, fontFamily:'inherit', color:'var(--text)',
                            opacity: licensed ? 1 : .55,
                            filter: licensed ? 'none' : 'grayscale(.4)',
                          }}>
                    {b.badge && licensed && (
                      <span style={{ position:'absolute', top:6, right:6, fontSize:'.55rem', padding:'2px 6px', background:'var(--orange)', color:'#fff', borderRadius:3, fontWeight:700, letterSpacing:'.06em' }}>
                        {b.badge.toUpperCase()}
                      </span>
                    )}
                    {!licensed && (
                      <span style={{ position:'absolute', top:6, right:6, fontSize:'.55rem', padding:'2px 6px', background:'var(--surface-3)', color:'var(--dim)', borderRadius:3, fontWeight:700, letterSpacing:'.06em', display:'flex', alignItems:'center', gap:3 }}>
                        <Icon name="lock" size={8}/>NO LICENSE
                      </span>
                    )}
                    <div style={{ fontSize:'.88rem', fontWeight:700, marginBottom:4, color: isSel ? 'var(--beam)' : 'var(--text)' }}>{b.label}</div>
                    <div style={{ fontSize:'.66rem', color:'var(--dim)', lineHeight:1.4, marginBottom:8 }}>{b.desc}</div>
                    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                      <div style={{ fontSize:'.6rem', color:'var(--muted)', fontFamily:'var(--font-mono)' }}>{b.stack.length} plugins</div>
                      {licensed ? (
                        <span style={{ fontSize:'.56rem', color:'var(--green)', fontWeight:700, letterSpacing:'.06em' }}>✓ LICENSED</span>
                      ) : (
                        <a href="#" onClick={(e)=>{e.stopPropagation();goToVault(e);}} style={{ fontSize:'.56rem', color:'var(--beam)', fontWeight:700, letterSpacing:'.06em', textDecoration:'none' }}>+ ADD LICENSE</a>
                      )}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <h2 className="card-title"><Icon name="plugin" size={14}/>&nbsp;{cur?.label} plugin stack</h2>
            <span className="tag" style={{ fontSize:'.6rem' }}>{cur?.stack.length} included · gated by vault</span>
          </div>
          <div className="card-body" style={{ padding:0 }}>
            <table className="table" style={{ fontSize:'.74rem' }}>
              <thead>
                <tr>
                  <th scope="col">Plugin</th>
                  <th scope="col" style={{ width:120 }}>License</th>
                  <th scope="col" style={{ width:120 }}>Version</th>
                  <th scope="col" style={{ width:120, textAlign:'right' }}>Include</th>
                </tr>
              </thead>
              <tbody>
                {cur?.stack.map((p) => {
                  const cred = resolveCred(p);
                  const v = cred ? vault[cred.id] : null;
                  const licensed = !!(v && v.status === 'valid' && Object.keys(v.values || {}).length);
                  const expiring = !!(v && v.status === 'expiring');
                  const noCred = !cred; // core/bundled items without licenses (e.g. child themes)
                  return (
                    <tr key={p} style={{ opacity: (noCred || licensed || expiring) ? 1 : .55, background: (!noCred && !licensed) ? 'rgba(148,163,184,.04)' : 'transparent' }}>
                      <td style={{ fontWeight:500, display:'flex', alignItems:'center', gap:8 }}>
                        {!noCred && !licensed && <Icon name="lock" size={10} style={{ color:'var(--dim)' }}/>}
                        <span style={{ color: (!noCred && !licensed) ? 'var(--dim)' : 'var(--text)' }}>{p}</span>
                      </td>
                      <td>
                        {noCred ? (
                          <span className="tag" style={{ fontSize:'.56rem', background:'var(--surface-2)', color:'var(--muted)' }}>BUNDLED</span>
                        ) : licensed ? (
                          <span className="tag ok" style={{ fontSize:'.56rem' }}>✓ LICENSED</span>
                        ) : expiring ? (
                          <span className="tag warn" style={{ fontSize:'.56rem' }}>⚠ EXPIRING</span>
                        ) : (
                          <a href="#" onClick={goToVault} style={{ fontSize:'.56rem', color:'var(--beam)', fontWeight:700, letterSpacing:'.06em', textDecoration:'none' }}>
                            + ADD LICENSE
                          </a>
                        )}
                      </td>
                      <td className="mono" style={{ fontSize:'.66rem', color:'var(--muted)' }}>latest</td>
                      <td style={{ textAlign:'right' }}>
                        <label style={{ display:'inline-flex', alignItems:'center', gap:4, fontSize:'.66rem', color:'var(--dim)', cursor: (noCred || licensed) ? 'pointer' : 'not-allowed' }}>
                          <input type="checkbox" defaultChecked={noCred || licensed} disabled={!noCred && !licensed}/>
                          Include
                        </label>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        <div className="box info" style={{ marginTop:12 }}>
          <Icon name="info" size={14}/>
          <div>
            <strong>Smart gating:</strong> Builders &amp; plugins without a valid license are locked and greyed out. Add keys in <a href="#" onClick={goToVault}>Brand Profile → Credential Vault</a> — this kit builder auto-refreshes within 5 seconds of a key being validated. Agencies reselling their own SaaS can swap the full stack per-kit in <a href="#" onClick={e=>{e.preventDefault(); window.WPSBD?.switchTab?.('brandprofile');}}>Brand Profile → White Label</a>.
          </div>
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════════
     STEP 5 — PREVIEW & REMIX (FULLY DESIGNED)
  ═══════════════════════════════════════════════════════════════ */
  function StepPreview({ selected, setSelected, mixPicks, setMixPicks, brand, siteType, themeBuilder }) {
    const Icon = window.Icon;
    const [view, setView] = useState('grid'); // grid | mix
    // 6 variations — first 2 fully designed, 4 as wireframe thumbs
    const VARIATIONS = [
      { id:1, name:'Classic Corporate',   fidelity:'designed',  palette:[brand.colors[1] || '#0F172A', brand.colors[0] || 'var(--orange)', '#ffffff'], tag:'Safe · Conservative' },
      { id:2, name:'Bold & Modern',       fidelity:'designed',  palette:['#0a0a0f', brand.colors[0] || 'var(--orange)', '#f4f5f7'], tag:'Recommended · Differentiated' },
      { id:3, name:'Editorial',           fidelity:'wireframe', palette:['#ffffff', '#1a1a1a', brand.colors[0] || 'var(--orange)'], tag:'Content-forward' },
      { id:4, name:'SaaS Product',        fidelity:'wireframe', palette:['#f4f5f7', brand.colors[0] || 'var(--orange)', '#0a0a0f'], tag:'Product-led' },
      { id:5, name:'Warm Service',        fidelity:'wireframe', palette:['#fffaf3', '#b8460e', '#2d1810'], tag:'Approachable' },
      { id:6, name:'Dark Premium',        fidelity:'wireframe', palette:['#0a0a0f', brand.colors[0] || 'var(--orange)', '#a1a1aa'], tag:'Luxury · Night mode' },
    ];

    return (
      <div>
        {/* View toggle + credits */}
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
          <div className="tw-seg" role="tablist" style={{ display:'inline-flex' }}>
            <button role="tab" aria-selected={view==='grid'} className={view==='grid'?'active':''} onClick={() => setView('grid')}>Variations</button>
            <button role="tab" aria-selected={view==='mix'}  className={view==='mix' ?'active':''} onClick={() => setView('mix')}>Mix & match</button>
          </div>
          <div style={{ flex:1 }}/>
          <div style={{ fontSize:'.68rem', color:'var(--dim)', fontFamily:'var(--font-mono)' }}>
            1 credit consumed · 2/15 remaining this cycle
          </div>
          <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Generating 2 more variations · 1 credit', 'beam')}>
            <Icon name="refresh" size={12}/>Generate more
          </button>
        </div>

        {view === 'grid' ? (
          <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(320px, 1fr))', gap:14 }}>
            {VARIATIONS.map(v => (
              <VariationCard key={v.id} v={v} brand={brand} selected={selected === v.id} onSelect={() => setSelected(v.id)}/>
            ))}
          </div>
        ) : (
          <MixAndMatchPanel picks={mixPicks} setPicks={setMixPicks} brand={brand}/>
        )}

        {/* Selection summary */}
        {view === 'grid' && (
          <div className="box info" style={{ marginTop:14 }}>
            <Icon name="check" size={14}/>
            <div>
              <strong>{VARIATIONS.find(v => v.id === selected)?.name} selected.</strong>
              &nbsp;This exports as your base kit. Switch to <button onClick={() => setView('mix')} style={{ background:'none', border:'none', color:'var(--beam)', cursor:'pointer', textDecoration:'underline', fontFamily:'inherit', fontSize:'inherit', padding:0 }}>Mix & Match</button> to swap sections across variations.
            </div>
          </div>
        )}
      </div>
    );
  }

  /* ── Variation card — fully designed mini-site preview ───── */
  function VariationCard({ v, brand, selected, onSelect }) {
    const Icon = window.Icon;
    const isDesigned = v.fidelity === 'designed';
    return (
      <div onClick={onSelect}
           style={{
             cursor:'pointer', borderRadius:10, overflow:'hidden',
             border: selected ? '2px solid var(--beam)' : '1px solid var(--border)',
             background:'var(--surface)',
             boxShadow: selected ? '0 0 0 3px var(--beam-dim)' : 'none',
             transition:'all .2s',
           }}>
        {/* Mini-browser chrome */}
        <div style={{ background:'var(--surface-2)', padding:'6px 10px', display:'flex', alignItems:'center', gap:4, borderBottom:'1px solid var(--border)' }}>
          <div style={{ width:8, height:8, borderRadius:'50%', background:'#ff5f57' }}/>
          <div style={{ width:8, height:8, borderRadius:'50%', background:'#febc2e' }}/>
          <div style={{ width:8, height:8, borderRadius:'50%', background:'#28c840' }}/>
          <div style={{ flex:1, marginLeft:8, height:12, background:'var(--surface)', borderRadius:3, fontSize:'.56rem', display:'flex', alignItems:'center', padding:'0 6px', color:'var(--dim)' }}>
            {v.name.toLowerCase().replace(/\s/g, '-')}.kit
          </div>
        </div>

        {/* Preview canvas */}
        <div style={{ height:280, position:'relative', overflow:'hidden', background: v.palette[0] }}>
          {isDesigned ? <DesignedPreview v={v} brand={brand}/> : <WireframePreview v={v} brand={brand}/>}
        </div>

        {/* Footer */}
        <div style={{ padding:'12px 14px', borderTop:'1px solid var(--border)' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:4 }}>
            <div style={{ fontSize:'.84rem', fontWeight:700 }}>{v.name}</div>
            {selected && <span className="tag ok" style={{ fontSize:'.58rem' }}>SELECTED</span>}
            {!selected && v.fidelity === 'wireframe' && <span style={{ fontSize:'.58rem', color:'var(--dim)', fontFamily:'var(--font-mono)', letterSpacing:'.08em' }}>WIREFRAME</span>}
            {!selected && v.fidelity === 'designed' && <span className="tag beam" style={{ fontSize:'.58rem' }}>HI-FI</span>}
          </div>
          <div style={{ fontSize:'.66rem', color:'var(--dim)' }}>{v.tag}</div>
          <div style={{ display:'flex', gap:4, marginTop:8 }}>
            {v.palette.map(c => <div key={c} style={{ width:14, height:14, borderRadius:3, background:c, border:'1px solid var(--border)' }}/>)}
          </div>
        </div>
      </div>
    );
  }

  function DesignedPreview({ v, brand }) {
    const accent = brand.colors?.[0] || 'var(--orange)';
    const bg = v.palette[0];
    const text = v.id === 1 ? '#f4f5f7' : v.id === 2 ? '#f4f5f7' : '#0f0f12';
    return (
      <div style={{ padding:'10px 14px', height:'100%', color:text, fontSize:'.6rem', fontFamily:`${brand.fontBody || 'Inter'}, sans-serif` }}>
        {/* Nav */}
        <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:12 }}>
          <div style={{ width:16, height:16, borderRadius:3, background:accent }}/>
          <div style={{ fontFamily:`${brand.fontHead || 'Orbitron'}, sans-serif`, fontWeight:700, fontSize:'.68rem' }}>BRAND</div>
          <div style={{ flex:1 }}/>
          {['Work','Services','About','Contact'].map(n => <span key={n} style={{ opacity:.7, fontSize:'.56rem' }}>{n}</span>)}
          <div style={{ padding:'3px 8px', background:accent, color: v.id === 2 ? '#000' : '#fff', borderRadius:3, fontSize:'.55rem', fontWeight:600 }}>Get started</div>
        </div>

        {/* Hero */}
        {v.id === 1 ? (
          <div style={{ display:'flex', gap:14, alignItems:'center' }}>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:'.52rem', letterSpacing:'.15em', textTransform:'uppercase', color:accent, marginBottom:6, fontWeight:600 }}>TRUSTED SINCE 2008</div>
              <div style={{ fontFamily:`${brand.fontHead || 'Playfair'}, serif`, fontSize:'1.3rem', fontWeight:700, lineHeight:1.1, marginBottom:8 }}>Expertise you can count on.</div>
              <div style={{ fontSize:'.58rem', opacity:.7, lineHeight:1.5, marginBottom:8 }}>Classic, measured design built for professional services that rely on credibility.</div>
              <div style={{ display:'flex', gap:4 }}>
                <div style={{ padding:'5px 9px', background:accent, color:'#000', borderRadius:2, fontWeight:600, fontSize:'.56rem' }}>Schedule consultation</div>
                <div style={{ padding:'5px 9px', border:`1px solid ${text}`, borderRadius:2, fontWeight:500, fontSize:'.56rem', opacity:.8 }}>Our process</div>
              </div>
            </div>
            <div style={{ width:90, height:100, background:'rgba(255,255,255,.08)', border:`1px solid rgba(255,255,255,.15)`, borderRadius:4 }}/>
          </div>
        ) : (
          <>
            <div style={{ fontFamily:`${brand.fontHead || 'Space Grotesk'}, sans-serif`, fontSize:'1.6rem', fontWeight:700, lineHeight:1, letterSpacing:'-.02em', marginBottom:10 }}>
              Built for<br/>the bold.
            </div>
            <div style={{ fontSize:'.58rem', opacity:.6, marginBottom:14, maxWidth:170 }}>Modern layouts, confident type, and interaction that actually feels good.</div>
            <div style={{ display:'flex', gap:4, marginBottom:12 }}>
              <div style={{ padding:'6px 12px', background:accent, color:'#000', borderRadius:3, fontWeight:700, fontSize:'.58rem' }}>Start free →</div>
              <div style={{ padding:'6px 12px', border:`1px solid ${accent}`, color:accent, borderRadius:3, fontWeight:600, fontSize:'.58rem' }}>Watch demo</div>
            </div>
            {/* Stats strip */}
            <div style={{ display:'flex', gap:10, paddingTop:10, borderTop:`1px solid rgba(255,255,255,.1)` }}>
              {[['12k+','users'],['4.9','rating'],['99.9%','uptime']].map(([n,l]) => (
                <div key={l}>
                  <div style={{ fontFamily:`${brand.fontHead || 'Space Grotesk'}, sans-serif`, fontWeight:700, fontSize:'.8rem' }}>{n}</div>
                  <div style={{ fontSize:'.5rem', opacity:.6, letterSpacing:'.06em', textTransform:'uppercase' }}>{l}</div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    );
  }

  function WireframePreview({ v, brand }) {
    const fg = v.id === 6 ? '#d4d4d8' : '#71717a';
    const accent = brand.colors?.[0] || 'var(--orange)';
    return (
      <div style={{ padding:14, height:'100%' }}>
        {/* nav */}
        <div style={{ display:'flex', gap:6, marginBottom:12, alignItems:'center' }}>
          <div style={{ width:40, height:10, background:fg, opacity:.4, borderRadius:2 }}/>
          <div style={{ flex:1 }}/>
          {[0,1,2].map(i => <div key={i} style={{ width:20, height:6, background:fg, opacity:.3, borderRadius:1 }}/>)}
          <div style={{ width:30, height:12, background:accent, borderRadius:2 }}/>
        </div>
        {/* hero */}
        <div style={{ marginBottom:12 }}>
          <div style={{ width:'90%', height:14, background:fg, opacity:.5, borderRadius:2, marginBottom:4 }}/>
          <div style={{ width:'70%', height:14, background:fg, opacity:.5, borderRadius:2, marginBottom:8 }}/>
          <div style={{ width:'60%', height:5, background:fg, opacity:.3, borderRadius:1, marginBottom:3 }}/>
          <div style={{ width:'55%', height:5, background:fg, opacity:.3, borderRadius:1, marginBottom:8 }}/>
          <div style={{ display:'flex', gap:4 }}>
            <div style={{ width:50, height:14, background:accent, borderRadius:2 }}/>
            <div style={{ width:50, height:14, border:`1px solid ${fg}`, opacity:.5, borderRadius:2 }}/>
          </div>
        </div>
        {/* 3-col grid */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:5 }}>
          {[0,1,2].map(i => (
            <div key={i} style={{ aspectRatio:'1.1', background:fg, opacity:.1, borderRadius:3, padding:6 }}>
              <div style={{ width:10, height:10, background:accent, opacity:.6, borderRadius:2, marginBottom:4 }}/>
              <div style={{ width:'80%', height:4, background:fg, opacity:.4, borderRadius:1, marginBottom:2 }}/>
              <div style={{ width:'60%', height:3, background:fg, opacity:.3, borderRadius:1 }}/>
            </div>
          ))}
        </div>
      </div>
    );
  }

  function MixAndMatchPanel({ picks, setPicks, brand }) {
    const Icon = window.Icon;
    const SECTIONS = [
      { key:'hero',   label:'Hero',            desc:'Above-fold pattern' },
      { key:'nav',    label:'Navigation',      desc:'Header + menu structure' },
      { key:'cards',  label:'Card layout',     desc:'Content cards / features' },
      { key:'forms',  label:'Forms',           desc:'Input styling + validation' },
      { key:'footer', label:'Footer',          desc:'Site footer composition' },
    ];
    return (
      <div className="card">
        <div className="card-head">
          <h2 className="card-title"><Icon name="wand" size={14}/>&nbsp;Mix & match · pick sections across variations</h2>
          <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Build a custom kit by combining the best parts of each variation</div>
        </div>
        <div className="card-body" style={{ padding:0 }}>
          {SECTIONS.map(s => (
            <div key={s.key} style={{ padding:'14px 16px', borderBottom:'1px solid var(--border)' }}>
              <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:10 }}>
                <div style={{ fontSize:'.82rem', fontWeight:600 }}>{s.label}</div>
                <div style={{ fontSize:'.66rem', color:'var(--dim)' }}>— {s.desc}</div>
                <span style={{ flex:1 }}/>
                <span style={{ fontSize:'.62rem', color:'var(--beam)', fontFamily:'var(--font-mono)' }}>from variation #{picks[s.key]}</span>
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gap:6 }}>
                {[1,2,3,4,5,6].map(id => {
                  const isPicked = picks[s.key] === id;
                  return (
                    <button key={id} onClick={() => setPicks({...picks, [s.key]:id})}
                            style={{
                              cursor:'pointer', padding:0, aspectRatio:'1.6',
                              background:'var(--surface-2)',
                              border: isPicked ? '2px solid var(--beam)' : '1px solid var(--border)',
                              borderRadius:6, position:'relative', overflow:'hidden',
                            }}>
                      {/* Tiny wireframe preview */}
                      <div style={{ position:'absolute', inset:4 }}>
                        <div style={{ display:'flex', gap:2, marginBottom:3 }}>
                          <div style={{ width:10, height:3, background:'var(--border)', borderRadius:1 }}/>
                          <div style={{ flex:1 }}/>
                          <div style={{ width:14, height:3, background: brand.colors[0], borderRadius:1 }}/>
                        </div>
                        <div style={{ width:'70%', height:4, background:'var(--muted)', opacity:.5, borderRadius:1, marginBottom:2 }}/>
                        <div style={{ width:'50%', height:3, background:'var(--muted)', opacity:.3, borderRadius:1 }}/>
                      </div>
                      <div style={{ position:'absolute', bottom:2, right:3, fontSize:'.54rem', fontFamily:'var(--font-mono)', color:'var(--dim)', fontWeight:700 }}>#{id}</div>
                      {isPicked && (
                        <div style={{ position:'absolute', top:3, right:3, width:14, height:14, background:'var(--beam)', borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center' }}>
                          <Icon name="check" size={9} style={{ color:'#001018' }}/>
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════════
     STEP 6 — EXPORT (wireframe + structured)
  ═══════════════════════════════════════════════════════════════ */
  function StepExport({ exportPath, setExportPath, brand, themeBuilder, siteType, CREDIT_PLANS }) {
    const Icon = window.Icon;
    const PATHS = [
      { id:'zip',    icon:'download', label:'Download Elementor Kit ZIP', desc:'Standard WordPress import format · manual install · works with any host.' },
      { id:'push',   icon:'plugin',   label:'Push directly to connected WP site', desc:'Via WPSB plugin · creates pages, imports media, applies theme kit in one step.' },
      { id:'resell', icon:'partners', label:'Package as resellable kit',   desc:'Agency kit with your white-label branding · list in your own marketplace.' },
    ];
    return (
      <div>
        <div className="grid" style={{ gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
          {/* Left: destination picker */}
          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="download" size={14}/>&nbsp;Export destination</h2>
            </div>
            <div className="card-body" style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {PATHS.map(p => (
                <button key={p.id} onClick={() => setExportPath(p.id)}
                        style={{
                          padding:'14px 16px', textAlign:'left', cursor:'pointer',
                          background: exportPath === p.id ? 'var(--beam-dim)' : 'var(--surface-2)',
                          border: exportPath === p.id ? '1px solid var(--beam)' : '1px solid var(--border)',
                          borderRadius:8, fontFamily:'inherit', color:'var(--text)',
                          display:'flex', gap:12, alignItems:'flex-start',
                        }}>
                  <div style={{ width:34, height:34, borderRadius:8, background: exportPath === p.id ? 'var(--beam)' : 'var(--surface)', color: exportPath === p.id ? '#001018' : 'var(--muted)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                    <Icon name={p.icon} size={16}/>
                  </div>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:'.82rem', fontWeight:600, marginBottom:3 }}>{p.label}</div>
                    <div style={{ fontSize:'.68rem', color:'var(--dim)', lineHeight:1.5 }}>{p.desc}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Right: Bundle contents */}
          <div className="card">
            <div className="card-head">
              <h2 className="card-title"><Icon name="archive" size={14}/>&nbsp;Bundle contents</h2>
              <span className="tag" style={{ fontSize:'.6rem' }}>~48 MB</span>
            </div>
            <div className="card-body" style={{ padding:0 }}>
              {[
                { label:'Theme files', detail:'Hello Elementor Child + customizations', size:'1.2 MB' },
                { label:'Elementor Kit JSON', detail:'All templates, sections, globals', size:'2.4 MB' },
                { label:'JetEngine schema', detail:'CPTs, relations, meta boxes', size:'180 KB' },
                { label:'ACF field groups (fallback)', detail:'Equivalent definitions', size:'64 KB' },
                { label:'Gravity Forms exports', detail:'Contact + estimate + newsletter', size:'32 KB' },
                { label:'Logo variants', detail:'SVG + PNG 1x/2x/3x · 4 variants', size:'640 KB' },
                { label:'Media library', detail:'Placeholder stock + icons (WebP)', size:'42 MB' },
                { label:'Migration checklist', detail:'Step-by-step staging → prod', size:'PDF' },
              ].map(f => (
                <div key={f.label} style={{ padding:'10px 16px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', gap:10 }}>
                  <Icon name="file" size={12} style={{ color:'var(--dim)', flexShrink:0 }}/>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:'.76rem', fontWeight:500 }}>{f.label}</div>
                    <div style={{ fontSize:'.64rem', color:'var(--dim)' }}>{f.detail}</div>
                  </div>
                  <div style={{ fontSize:'.62rem', color:'var(--muted)', fontFamily:'var(--font-mono)' }}>{f.size}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Push-specific config */}
        {exportPath === 'push' && (
          <div className="card" style={{ marginBottom:14 }}>
            <div className="card-head">
              <h2 className="card-title"><Icon name="plugin" size={14}/>&nbsp;Push to WordPress</h2>
            </div>
            <div className="card-body">
              <div style={{ fontSize:'.74rem', color:'var(--muted)', marginBottom:10 }}>Pick a connected WordPress site with the WPSB plugin installed. The kit will be applied to staging first, then promoted after you review.</div>
              <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:8 }}>
                {[
                  { name:'acme.com',           status:'ready',  note:'Staging available' },
                  { name:'municipal-site.gov', status:'ready',  note:'Staging available' },
                  { name:'hvacpros.io',        status:'nostaging', note:'No staging · apply to prod?' },
                ].map(s => (
                  <div key={s.name} style={{ padding:12, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8 }}>
                    <div style={{ fontSize:'.8rem', fontWeight:600, marginBottom:4 }}>{s.name}</div>
                    <div style={{ fontSize:'.66rem', color: s.status === 'ready' ? 'var(--green)' : 'var(--warn)', marginBottom:8 }}>{s.note}</div>
                    <button className="btn btn-primary btn-sm" style={{ width:'100%' }}>Push to this site</button>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Resell-specific config */}
        {exportPath === 'resell' && (
          <div className="card" style={{ marginBottom:14 }}>
            <div className="card-head">
              <h2 className="card-title"><Icon name="partners" size={14}/>&nbsp;Resellable kit settings</h2>
              <span className="tag sa" style={{ fontSize:'.58rem' }}>AGENCY PLAN+</span>
            </div>
            <div className="card-body">
              <div style={{ fontSize:'.74rem', color:'var(--muted)', marginBottom:12 }}>White-label the kit so your clients see your agency brand · not WP Site Beam · in the installer.</div>
              <div className="grid" style={{ gridTemplateColumns:'1fr 1fr', gap:10 }}>
                <div style={{ padding:10, background:'var(--surface-2)', borderRadius:6, border:'1px solid var(--border)' }}>
                  <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Kit name</div>
                  <input defaultValue="Professional Services Theme · v1" style={{ width:'100%', padding:'7px 10px', fontSize:'.76rem', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:4, color:'var(--text)' }}/>
                </div>
                <div style={{ padding:10, background:'var(--surface-2)', borderRadius:6, border:'1px solid var(--border)' }}>
                  <div style={{ fontSize:'.66rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>Price (optional)</div>
                  <input defaultValue="$299" style={{ width:'100%', padding:'7px 10px', fontSize:'.76rem', background:'var(--surface)', border:'1px solid var(--border)', borderRadius:4, color:'var(--text)' }}/>
                </div>
              </div>
              <label style={{ display:'flex', alignItems:'center', gap:8, marginTop:10, fontSize:'.74rem', cursor:'pointer' }}>
                <input type="checkbox" defaultChecked/>
                Apply white-label branding from Brand Profile
              </label>
            </div>
          </div>
        )}

        {/* Credits / plan panel */}
        <div className="card">
          <div className="card-head">
            <h2 className="card-title"><Icon name="calc" size={14}/>&nbsp;Kit credits &amp; plans</h2>
            <div style={{ fontSize:'.68rem', color:'var(--dim)' }}>Each generated kit consumes 1 credit · regenerations within 24h are free</div>
          </div>
          <div className="card-body" style={{ padding:0 }}>
            <div className="grid" style={{ gridTemplateColumns:'repeat(auto-fill, minmax(200px, 1fr))', gap:1, background:'var(--border)' }}>
              {CREDIT_PLANS.map(p => (
                <div key={p.id} style={{ padding:14, background:'var(--surface)' }}>
                  <div style={{ fontSize:'.7rem', color:'var(--dim)', letterSpacing:'.08em', textTransform:'uppercase', fontWeight:700, marginBottom:6 }}>{p.label}</div>
                  <div style={{ fontSize:'1.4rem', fontWeight:700, fontFamily:'var(--font-mono)' }}>{p.kits}<span style={{ fontSize:'.64rem', color:'var(--dim)', fontWeight:400 }}> kits/mo</span></div>
                  <div style={{ fontSize:'.66rem', color:'var(--muted)', marginTop:4 }}>overage {p.overage}</div>
                  <div style={{ fontSize:'.66rem', color:'var(--beam)', marginTop:2, fontFamily:'var(--font-mono)' }}>{p.price}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="box warn" style={{ marginTop:12 }}>
          <Icon name="shield" size={14}/>
          <div>
            <strong>Security &amp; rate-limit:</strong> Generation runs on a dedicated isolated worker. Rate-limited at 3 concurrent kits per agency. Generated assets are yours; WP Site Beam retains anonymized structural telemetry only (no content, no brand, no customer data).
          </div>
        </div>
      </div>
    );
  }

})();

