/* ── MARKETING MATERIALS ──────────────────────────────────────
   New top-level tool for branding agencies. Generates print + digital
   collateral from the user's Brand Profile (logo / colors / type / NAP),
   ready to proof and send to a print partner.

   3 tabs:
     • Templates — gallery of ~20 template types w/ live mini-preview
                   (cards, signs, wraps, digital, etc.)
     • Canvas    — full-screen preview + light editing of the chosen
                   template; auto-populated from Brand Profile
     • Orders    — history of print jobs (demo data); reorder / download PDF

   Every preview shows the 4-pillar Optimization Guarantee:
     ADA · Print-CMYK · Brand-consistent · Local-SEO/NAP

   Send to Print: Moo / VistaPrint / Signs.com / direct PDF / Canva export.

   This is a wireframe-grade module — real rendering would use html2canvas
   or a server-side Chromium render to PDF/CMYK TIFF. Here we render the
   design in-browser and mark those pipelines as roadmap.
*/

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

  /* ── BRAND SOURCE ─────────────────────────────────────────────
     Read the brand profile from state (same shape KitBuilder uses). */
  function useBrand() {
    // Defaults — demo business
    const defaults = {
      companyName:   'Nova Home Services',
      slogan:        'Comfort that works, day and night.',
      market:        'HVAC',
      tagline:       'HVAC · Plumbing · Electrical',
      phone:         '(555) 234-9010',
      email:         'hello@novaservices.com',
      website:       'novaservices.com',
      address1:      '2104 Industrial Blvd, Suite 210',
      city:          'Austin',
      state:         'TX',
      zip:           '78744',
      serviceArea:   'Greater Austin · Travis · Williamson County',
      license:       'TACLB #4520321',
      contactName:   'Jamie Ortiz',
      contactTitle:  'Service Manager',
      colors:        ['var(--orange)', '#0F172A', '#ffffff', '#E2E8F0'],
      fontHead:      'Orbitron',
      fontBody:      'Inter',
      logoVariant:   'colored', // white | black | colored
    };
    try {
      const stored = JSON.parse(localStorage.getItem('wpsb-brand-profile') || '{}');
      return { ...defaults, ...stored };
    } catch { return defaults; }
  }

  /* ── TEMPLATE CATALOG ─────────────────────────────────────────
     Grouped by category. Each template knows its render type so the
     <TemplatePreview/> can pick the right layout. Sizes are listed
     in physical units so CMYK / bleed requirements are clear. */
  const CATALOG = [
    { group:'Print — Stationery', items:[
      { id:'bizcard',     label:'Business Card',       size:'3.5 × 2 in',    bleed:'0.125 in', cmyk:true,  layout:'bizcard',     blurb:'Front + back · both printed' },
      { id:'letterhead',  label:'Letterhead',          size:'8.5 × 11 in',   bleed:'0.125 in', cmyk:true,  layout:'letterhead',  blurb:'A4 available on export' },
      { id:'envelope',    label:'#10 Envelope',        size:'9.5 × 4.125 in',bleed:'0.125 in', cmyk:true,  layout:'envelope',    blurb:'Window / no-window variants' },
      { id:'notepad',     label:'Notepad',             size:'5.5 × 8.5 in',  bleed:'0.125 in', cmyk:true,  layout:'notepad',     blurb:'50-sheet · branded header' },
      { id:'invoice',     label:'Invoice template',    size:'8.5 × 11 in',   bleed:'n/a',      cmyk:false, layout:'invoice',     blurb:'PDF + editable Google Doc' },
    ]},
    { group:'Print — Signs & Large Format', items:[
      { id:'yardsign',    label:'Yard sign',           size:'24 × 18 in',    bleed:'0.25 in',  cmyk:true,  layout:'yardsign',    blurb:'Coroplast · double-sided' },
      { id:'banner',      label:'Vinyl banner',        size:'96 × 24 in',    bleed:'0.5 in',   cmyk:true,  layout:'banner',      blurb:'Grommets · outdoor vinyl' },
      { id:'trade-booth', label:'Trade-show backdrop', size:'96 × 96 in',    bleed:'0.5 in',   cmyk:true,  layout:'booth',       blurb:'Retractable · ≥150 DPI' },
      { id:'vehicle-wrap',label:'Vehicle wrap panel',  size:'240 × 72 in',   bleed:'1 in',     cmyk:true,  layout:'wrap',        blurb:'Spec sheet per vehicle model' },
      { id:'door-hanger', label:'Door hanger',         size:'4.25 × 11 in',  bleed:'0.125 in', cmyk:true,  layout:'door-hanger', blurb:'Neighborhood canvassing' },
    ]},
    { group:'Print — Marketing', items:[
      { id:'brochure',    label:'Tri-fold brochure',   size:'11 × 8.5 in',   bleed:'0.125 in', cmyk:true,  layout:'brochure',    blurb:'Two-sided · auto-fold guides' },
      { id:'flyer',       label:'Flyer',               size:'8.5 × 11 in',   bleed:'0.125 in', cmyk:true,  layout:'flyer',       blurb:'One-sided · hero + CTA' },
      { id:'postcard',    label:'Postcard (EDDM)',     size:'6 × 9 in',      bleed:'0.125 in', cmyk:true,  layout:'postcard',    blurb:'USPS EDDM-ready' },
      { id:'rackcard',    label:'Rack card',           size:'4 × 9 in',      bleed:'0.125 in', cmyk:true,  layout:'rackcard',    blurb:'Display-rack standard' },
    ]},
    { group:'Digital — Social & Web', items:[
      { id:'og-image',    label:'Open Graph image',    size:'1200 × 630 px', bleed:'n/a',      cmyk:false, layout:'og',          blurb:'Facebook · LinkedIn · Twitter' },
      { id:'ig-post',     label:'Instagram post',      size:'1080 × 1080 px',bleed:'n/a',      cmyk:false, layout:'square',      blurb:'Square · safe zones' },
      { id:'ig-story',    label:'Instagram story',     size:'1080 × 1920 px',bleed:'n/a',      cmyk:false, layout:'story',       blurb:'9:16 · text-safe center' },
      { id:'linkedin',    label:'LinkedIn banner',     size:'1584 × 396 px', bleed:'n/a',      cmyk:false, layout:'banner-wide', blurb:'Safe-zone markers' },
      { id:'youtube',     label:'YouTube banner',      size:'2560 × 1440 px',bleed:'n/a',      cmyk:false, layout:'banner-wide', blurb:'TV-safe area built in' },
      { id:'email-sig',   label:'Email signature',     size:'HTML',          bleed:'n/a',      cmyk:false, layout:'emailsig',    blurb:'Outlook + Apple Mail + Gmail' },
    ]},
    /* ── Compliance Deliverables (NEW v1.1.0 — CD Compliance Framework) ──
       Per-client branded PDF deliverables auto-populated from scanner
       findings + Brand Profile. Distribution: direct PDF download,
       email, Canva export. No print partners — agencies typically
       want the digital deliverable for client portals. */
    { group:'Compliance Deliverables', items:[
      { id:'editor-toolkit', label:'Content Editor Toolkit',           size:'8.5 × 11 in (7 pages)', bleed:'n/a', cmyk:false, layout:'editor-toolkit', blurb:'Branded editor reference: 3 Golden Rules, scenarios, snippet library, pre-publish checklist', plan_min:'growth', source:'compliance' },
      { id:'audit-report',   label:'Accessibility Audit Report',       size:'8.5 × 11 in (6-10 pages)', bleed:'n/a', cmyk:false, layout:'audit-report',   blurb:'Cover · exec summary · methodology · severity-grouped findings · attestation · recommendations',  plan_min:'growth', source:'compliance' },
      { id:'care-plan',      label:'Compliance Care Plan Proposal',    size:'8.5 × 11 in (4-5 pages)',  bleed:'n/a', cmyk:false, layout:'care-plan',      blurb:'Monthly retainer pitch: what\'s included, replaces, benefits, terms — Konza-format template', plan_min:'growth', source:'compliance' },
      { id:'attestation',    label:'Annual Compliance Attestation',    size:'8.5 × 11 in (2 pages)',    bleed:'n/a', cmyk:false, layout:'attestation',    blurb:'Formal attestation for HRSA reporting / OCR response / grant applications',                  plan_min:'agency', source:'compliance' },
    ]},
  ];

  const PRINT_PARTNERS = [
    { id:'moo',        label:'Moo',         kinds:['bizcard','letterhead','notepad','postcard','brochure'], desc:'Premium cards, fast turnaround' },
    { id:'vistaprint', label:'VistaPrint',  kinds:['bizcard','letterhead','envelope','flyer','brochure','postcard','rackcard','yardsign','banner'], desc:'Broadest range · budget-friendly' },
    { id:'signscom',   label:'Signs.com',   kinds:['yardsign','banner','trade-booth','vehicle-wrap','door-hanger'], desc:'Outdoor + large format specialist' },
    { id:'canva',      label:'Canva (edit)', kinds:'all', desc:'Open editable design in Canva' },
    { id:'pdf',        label:'Download print-ready PDF', kinds:'all', desc:'CMYK · bleed marks · crop marks' },
  ];

  /* Distribution channels for Compliance Deliverables (NEW v1.1.0).
     Per Jordan's directive: no third-party print partners on
     compliance items — agencies want digital deliverables for
     client portals + email + Canva for in-house edits. */
  const COMPLIANCE_DISTRIBUTION = [
    { id:'pdf-download', label:'Download PDF',           desc:'Direct PDF download · client portal-ready' },
    { id:'email-send',   label:'Email to client',        desc:'Sends to the contact on file via Mailgun · CC agency by default' },
    { id:'canva-export', label:'Open in Canva',          desc:'Editable copy in Canva for in-house tweaks (Canva account required)' },
    { id:'gdrive-save',  label:'Save to Google Drive',   desc:'Pushes to the agency Drive folder if Drive is connected' },
  ];

  /* ═══════════════════════════════════════════════════════════
     MAIN COMPONENT
  ═══════════════════════════════════════════════════════════ */
  function MarketingMaterials() {
    const Icon = window.Icon;
    const PageHead = window.Pages1?.PageHead;
    const brand = useBrand();

    const [tab, setTab] = useState(() => {
      try { return localStorage.getItem('wpsb-mm-tab') || 'templates'; } catch { return 'templates'; }
    });
    const [selected, setSelected] = useState(null); // { groupIdx, itemId }
    const [q, setQ] = useState('');
    const [groupFilter, setGroupFilter] = useState('all');

    useEffect(() => { try { localStorage.setItem('wpsb-mm-tab', tab); } catch {} }, [tab]);

    // Flat catalog for search
    const allItems = useMemo(() => {
      return CATALOG.flatMap(g => g.items.map(i => ({ ...i, group:g.group })));
    }, []);

    const filtered = useMemo(() => {
      const needle = q.trim().toLowerCase();
      return allItems.filter(it => {
        if (groupFilter !== 'all' && it.group !== groupFilter) return false;
        if (!needle) return true;
        return (it.label + ' ' + it.blurb + ' ' + it.group).toLowerCase().includes(needle);
      });
    }, [allItems, q, groupFilter]);

    return (
      <div>
        <PageHead crumb="Tools"
          title="Marketing Materials"
          sub={<>Auto-generate print + digital collateral from your Brand Profile. Templates pre-populated with {brand.companyName} brand assets · ADA / CMYK / local-SEO validation on export.</>}
          actions={<>
            <button className="btn btn-ghost btn-sm" onClick={() => window.WPSBD?.switchTab('brandprofile')}>
              <Icon name="brand" size={13}/>Edit Brand Profile
            </button>
            <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Brand Kit ZIP — backend pending (html2canvas + PDF pipeline)', 'warn')}>
              <Icon name="download" size={13}/>Download Brand Kit
            </button>
          </>}
        />

        {/* ── Implementation status banner — demo vs. live ─────── */}
        <BuildStatusBanner/>

        {/* ── Brand summary strip ─────────────────────────────── */}
        <div className="card" style={{ marginBottom:16 }}>
          <div className="card-head">
            <h3 className="card-title">Brand profile in use</h3>
            <div style={{ display:'flex', gap:6, alignItems:'center' }}>
              <span className="tag" style={{ color:'var(--dim)' }}>auto-populates every template</span>
              <button className="btn btn-ghost btn-sm" onClick={() => window.WPSBD?.switchTab('brandprofile')}>Edit →</button>
            </div>
          </div>
          <div className="card-body" style={{ padding:'12px 16px', display:'flex', alignItems:'center', gap:16, flexWrap:'wrap' }}>
            <MiniLogo brand={brand}/>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(140px, 1fr))', gap:14, flex:1, minWidth:0 }}>
              <MetaCell label="Company" value={brand.companyName}/>
              <MetaCell label="Market"  value={brand.market}/>
              <MetaCell label="Phone"   value={brand.phone}/>
              <MetaCell label="Service area" value={brand.serviceArea}/>
              <MetaCell label="Palette" value={
                <div style={{ display:'flex', gap:3 }}>
                  {(brand.colors || []).slice(0, 4).map((c, i) => (
                    <span key={i} title={c} style={{ width:16, height:16, borderRadius:3, background:c, border:'1px solid var(--border)' }}/>
                  ))}
                </div>
              }/>
              <MetaCell label="Type" value={<span style={{ fontFamily:`${brand.fontHead}, sans-serif`, fontSize:'.74rem' }}>{brand.fontHead} / <span style={{ fontFamily:`${brand.fontBody}, sans-serif`, color:'var(--dim)' }}>{brand.fontBody}</span></span>}/>
            </div>
          </div>
        </div>

        {/* ── Tab nav ─────────────────────────────────────────── */}
        <div className="card" style={{ marginBottom:16 }}>
          <div style={{ display:'flex', borderBottom:'1px solid var(--border)' }}>
            {[
              { id:'templates', label:'Templates', icon:'modules',  hint:`${allItems.length} templates` },
              { id:'canvas',    label:'Canvas',    icon:'edit',     hint: selected ? 'Editing ' + allItems.find(i => i.id === selected)?.label : 'Pick a template' },
              { id:'orders',    label:'Orders',    icon:'archive',  hint:'3 recent jobs' },
            ].map(t => {
              const active = tab === t.id;
              return (
                <button key={t.id} onClick={() => setTab(t.id)}
                  style={{
                    padding:'12px 18px', cursor:'pointer', background:'transparent', border:'none',
                    borderBottom: active ? '2px solid var(--beam)' : '2px solid transparent',
                    color: active ? 'var(--text)' : 'var(--muted)',
                    fontWeight: active ? 600 : 500, fontSize:'.8rem', fontFamily:'inherit',
                    display:'flex', alignItems:'center', gap:8,
                  }}>
                  <Icon name={t.icon} size={14}/>{t.label}
                  <span style={{ fontSize:'.62rem', color:'var(--dim)', fontWeight:400 }}>· {t.hint}</span>
                </button>
              );
            })}
          </div>
        </div>

        {tab === 'templates' && (
          <TemplatesView
            brand={brand}
            groups={CATALOG}
            filtered={filtered}
            q={q} setQ={setQ}
            groupFilter={groupFilter} setGroupFilter={setGroupFilter}
            onPick={(id) => { setSelected(id); setTab('canvas'); }}
          />
        )}
        {tab === 'canvas' && (
          <CanvasView
            brand={brand}
            item={allItems.find(i => i.id === selected) || null}
            onBack={() => setTab('templates')}
          />
        )}
        {tab === 'orders' && <OrdersView brand={brand}/>}
      </div>
    );
  }

  /* ── Brand mini-logo (reads brand.logoVariant) ───────────────── */
  function MiniLogo({ brand }) {
    const markColor = brand.colors?.[0] || 'var(--orange)';
    return (
      <div style={{
        width:90, height:56, borderRadius:6,
        background: brand.logoVariant === 'black' ? '#0a0a0a' : (brand.logoVariant === 'white' ? '#ffffff' : 'var(--surface-2)'),
        border:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'center', gap:6, padding:'0 10px',
      }}>
        {/* glyph */}
        <svg width="22" height="22" viewBox="0 0 24 24" style={{ flexShrink:0 }}>
          <circle cx="12" cy="12" r="10" fill={markColor}/>
          <rect x="8" y="8" width="8" height="8" rx="1.5" fill={brand.logoVariant === 'white' ? '#0a0a0a' : '#fff'}/>
        </svg>
        <div style={{
          fontFamily:`${brand.fontHead}, sans-serif`, fontWeight:900,
          fontSize:'.78rem', letterSpacing:'-.02em',
          color: brand.logoVariant === 'white' ? '#0a0a0a' : (brand.logoVariant === 'black' ? '#fff' : 'var(--text)'),
          lineHeight:1, textTransform:'uppercase',
        }}>
          {(brand.companyName || 'BRAND').split(' ')[0]}
        </div>
      </div>
    );
  }

  function MetaCell({ label, value }) {
    return (
      <div>
        <div style={{ fontSize:'.54rem', color:'var(--dim)', textTransform:'uppercase', letterSpacing:'.08em', fontWeight:700, marginBottom:2 }}>{label}</div>
        <div style={{ fontSize:'.74rem', color:'var(--text)', fontWeight:500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{value || '—'}</div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════
     TEMPLATES VIEW — search + grid of template thumbnails
  ═══════════════════════════════════════════════════════════ */
  function TemplatesView({ brand, groups, filtered, q, setQ, groupFilter, setGroupFilter, onPick }) {
    const Icon = window.Icon;
    return (
      <>
        {/* Export validation — matches WPHealth / Scanner density */}
        <div className="card" style={{ marginBottom:16 }}>
          <div className="card-head">
            <h3 className="card-title">Export validation · run on every download</h3>
            <span className="tag" style={{ color:'var(--dim)' }}>4 checks</span>
          </div>
          <div className="card-body" style={{ padding:'10px 14px', display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(220px, 1fr))', gap:10 }}>
            {[
              { icon:'accessibility', label:'ADA',              hint:'4.5:1 text contrast · min body size' },
              { icon:'printer',       label:'Print-CMYK',       hint:'300 DPI · bleed + crop marks' },
              { icon:'brand',         label:'Brand-consistent', hint:'Logo clear-space · palette lock' },
              { icon:'map-pin',       label:'Local-SEO / NAP',  hint:'NAP matches Brand Profile' },
            ].map(p => (
              <div key={p.label} style={{ display:'flex', alignItems:'flex-start', gap:8, fontSize:'.72rem' }}>
                <Icon name={p.icon} size={13} color="var(--muted)" style={{ marginTop:2, flexShrink:0 }}/>
                <div style={{ minWidth:0 }}>
                  <div style={{ color:'var(--text)', fontWeight:500 }}>{p.label}</div>
                  <div style={{ color:'var(--dim)', fontSize:'.6rem' }}>{p.hint}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Filter bar */}
        <div className="card" style={{ marginBottom:16 }}>
          <div className="card-body" style={{ padding:'10px 14px', display:'flex', gap:10, alignItems:'center', flexWrap:'wrap' }}>
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Search templates…" style={{ flex:1, minWidth:180 }}/>
            <select value={groupFilter} onChange={e=>setGroupFilter(e.target.value)} style={{ minWidth:180 }}>
              <option value="all">All categories</option>
              {groups.map(g => <option key={g.group} value={g.group}>{g.group}</option>)}
            </select>
            <span className="tag" style={{ color:'var(--dim)' }}>{filtered.length} shown</span>
          </div>
        </div>

        {/* Grouped grid */}
        {groups.map(g => {
          const items = filtered.filter(f => f.group === g.group);
          if (!items.length) return null;
          return (
            <div key={g.group} className="card" style={{ marginBottom:16 }}>
              <div className="card-head">
                <h3 className="card-title" style={{ fontSize:'.72rem' }}>{g.group}</h3>
                <span className="tag" style={{ color:'var(--dim)' }}>{items.length}</span>
              </div>
              <div className="card-body" style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(220px, 1fr))', gap:14 }}>
                {items.map(it => (
                  <button key={it.id} onClick={() => onPick(it.id)} style={{
                    padding:0, border:'1px solid var(--border)', borderRadius:6, background:'var(--surface)',
                    cursor:'pointer', overflow:'hidden', textAlign:'left', display:'flex', flexDirection:'column',
                    transition:'border-color .12s', fontFamily:'inherit',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--beam)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; }}
                  >
                    <div style={{ height:104, background:'var(--surface-2)', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'center', position:'relative' }}>
                      <MiniPreview brand={brand} item={it}/>
                      <div style={{ position:'absolute', top:5, right:5 }}>
                        <span className="tag" style={{ fontSize:'.52rem', color: it.cmyk ? 'var(--orange)' : 'var(--beam)' }}>
                          {it.cmyk ? 'CMYK' : 'RGB'}
                        </span>
                      </div>
                    </div>
                    <div style={{ padding:'9px 11px' }}>
                      <div style={{ fontSize:'.76rem', color:'var(--text)', fontWeight:500, marginBottom:2 }}>{it.label}</div>
                      <div style={{ fontSize:'.6rem', color:'var(--dim)', marginBottom:5 }}>{it.blurb}</div>
                      <div style={{ display:'flex', justifyContent:'space-between', fontSize:'.56rem', color:'var(--dim)', fontFamily:'var(--font-mono)' }}>
                        <span>{it.size}</span>
                        <span>bleed {it.bleed}</span>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          );
        })}
      </>
    );
  }

  /* ── Mini preview (tiny stylized thumbnail) ──────────────────── */
  function MiniPreview({ brand, item }) {
    const c1 = brand.colors?.[0] || 'var(--orange)';
    const c2 = brand.colors?.[1] || '#0F172A';
    const L = item.layout;
    // One stylized svg per layout family
    if (L === 'bizcard') {
      return (
        <svg width="140" height="84" viewBox="0 0 140 84">
          <rect width="140" height="84" rx="4" fill="#fff" stroke="#ddd"/>
          <rect x="0" y="0" width="46" height="84" fill={c2}/>
          <circle cx="23" cy="32" r="10" fill={c1}/>
          <rect x="54" y="14" width="70" height="5" fill={c2} rx="1"/>
          <rect x="54" y="24" width="44" height="3" fill="#999" rx="1"/>
          <rect x="54" y="48" width="60" height="2" fill="#aaa"/>
          <rect x="54" y="54" width="48" height="2" fill="#aaa"/>
          <rect x="54" y="60" width="54" height="2" fill="#aaa"/>
        </svg>
      );
    }
    if (L === 'letterhead' || L === 'invoice' || L === 'flyer') {
      return (
        <svg width="80" height="104" viewBox="0 0 80 104">
          <rect width="80" height="104" rx="2" fill="#fff" stroke="#ddd"/>
          <rect x="0" y="0" width="80" height="16" fill={c1}/>
          <circle cx="10" cy="8" r="3" fill="#fff"/>
          <rect x="18" y="6" width="24" height="4" fill="#fff" rx="1"/>
          {[22,30,38,46,54,62,70,78,86].map((y,i) => <rect key={i} x="8" y={y} width={60 - (i%3)*8} height="1.4" fill="#bbb"/>)}
        </svg>
      );
    }
    if (L === 'yardsign' || L === 'postcard' || L === 'rackcard' || L === 'brochure' || L === 'door-hanger') {
      const w = L === 'rackcard' || L === 'door-hanger' ? 50 : 120;
      const h = L === 'rackcard' || L === 'door-hanger' ? 104 : 84;
      return (
        <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`}>
          <rect width={w} height={h} rx="3" fill={c2}/>
          <rect x="6" y="6" width={w-12} height={h*0.45} fill={c1} rx="2"/>
          <rect x="6" y={h*0.55} width={w-12} height="4" fill="#fff" rx="1"/>
          <rect x="6" y={h*0.65} width={(w-12)*0.7} height="2" fill="#fff" opacity=".8"/>
          <rect x="6" y={h*0.73} width={(w-12)*0.85} height="2" fill="#fff" opacity=".6"/>
          <rect x="6" y={h-16} width={(w-12)*0.5} height="5" fill={c1} rx="1"/>
        </svg>
      );
    }
    if (L === 'banner' || L === 'banner-wide' || L === 'wrap' || L === 'booth') {
      return (
        <svg width="156" height="46" viewBox="0 0 156 46">
          <rect width="156" height="46" rx="2" fill={c2}/>
          <circle cx="22" cy="23" r="10" fill={c1}/>
          <rect x="40" y="14" width="80" height="5" fill="#fff" rx="1"/>
          <rect x="40" y="24" width="60" height="3" fill="#fff" opacity=".7"/>
          <rect x="40" y="31" width="46" height="3" fill={c1} rx="1"/>
        </svg>
      );
    }
    if (L === 'og' || L === 'square' || L === 'story') {
      const size = L === 'story' ? {w:52,h:94} : L === 'og' ? {w:124,h:66} : {w:80,h:80};
      return (
        <svg width={size.w} height={size.h} viewBox={`0 0 ${size.w} ${size.h}`}>
          <rect width={size.w} height={size.h} rx="3" fill={c2}/>
          <rect x="6" y="6" width={size.w-12} height={size.h * 0.58} fill={c1} opacity=".9" rx="2"/>
          <rect x="6" y={size.h*0.66} width={size.w-12} height="4" fill="#fff" rx="1"/>
          <rect x="6" y={size.h*0.76} width={(size.w-12)*0.7} height="3" fill="#fff" opacity=".7"/>
        </svg>
      );
    }
    if (L === 'envelope') {
      return (
        <svg width="160" height="68" viewBox="0 0 160 68">
          <rect width="160" height="68" rx="2" fill="#fff" stroke="#ddd"/>
          <rect x="8" y="10" width="6" height="6" fill={c1}/>
          <rect x="18" y="10" width="50" height="2" fill="#888"/>
          <rect x="18" y="16" width="40" height="2" fill="#888"/>
          <rect x="18" y="22" width="44" height="2" fill="#888"/>
        </svg>
      );
    }
    if (L === 'emailsig') {
      return (
        <div style={{ padding:8, fontSize:'.58rem', lineHeight:1.3, color:'#333', fontFamily:'Arial,sans-serif', background:'#fff', borderRadius:4, width:180 }}>
          <div style={{ display:'flex', gap:6, alignItems:'center' }}>
            <div style={{ width:24, height:24, borderRadius:'50%', background:c1 }}/>
            <div>
              <div style={{ color:c2, fontWeight:700 }}>{brand.contactName}</div>
              <div style={{ color:'#666', fontSize:'.52rem' }}>{brand.contactTitle}</div>
            </div>
          </div>
          <div style={{ marginTop:4, borderTop:`1px solid ${c1}`, paddingTop:3, color:'#666', fontSize:'.5rem' }}>
            {brand.phone} · {brand.website}
          </div>
        </div>
      );
    }
    return (
      <svg width="100" height="72" viewBox="0 0 100 72">
        <rect width="100" height="72" rx="3" fill={c2}/>
        <rect x="8" y="8" width="84" height="56" rx="2" fill={c1} opacity=".4"/>
      </svg>
    );
  }

  /* ═══════════════════════════════════════════════════════════
     CANVAS VIEW — full-preview + edit + send-to-print
  ═══════════════════════════════════════════════════════════ */
  function CanvasView({ brand, item, onBack }) {
    const Icon = window.Icon;
    const [overrides, setOverrides] = useState({
      headline: '', sub: '', offer: '', cta: 'Call today', showQR:true,
    });
    if (!item) {
      return (
        <div className="card" style={{ marginBottom:16 }}>
          <div className="card-body" style={{ padding:40, textAlign:'center', color:'var(--dim)' }}>
            <Icon name="modules" size={28}/>
            <p style={{ marginTop:8 }}>Pick a template from the Templates tab to start editing.</p>
            <button className="btn btn-beam btn-sm" onClick={onBack} style={{ marginTop:8 }}>Back to templates</button>
          </div>
        </div>
      );
    }
    const partners = PRINT_PARTNERS.filter(p => p.kinds === 'all' || p.kinds.includes(item.id));

    return (
      <div className="grid" style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:16 }}>
        {/* Preview */}
        <div className="card">
          <div className="card-head">
            <h3 className="card-title">{item.label}</h3>
            <div style={{ display:'flex', gap:6 }}>
              <button className="btn btn-ghost btn-sm" onClick={onBack}><Icon name="chevron-left" size={12}/>All templates</button>
              <button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.('Preview refreshed', 'beam')}><Icon name="refresh" size={12}/>Refresh</button>
            </div>
          </div>
          <div className="card-body" style={{ padding:32, background:'var(--surface-2)', display:'flex', alignItems:'center', justifyContent:'center', minHeight:420 }}>
            <div style={{ boxShadow:'0 20px 60px rgba(0,0,0,.4)' }}>
              <MiniPreview brand={brand} item={item}/>
            </div>
          </div>
          <div className="card-body" style={{ padding:'12px 16px', borderTop:'1px solid var(--border)', display:'flex', gap:14, fontSize:'.64rem', color:'var(--dim)', fontFamily:'var(--font-mono)', flexWrap:'wrap' }}>
            <span>SIZE · {item.size}</span><span>BLEED · {item.bleed}</span>
            {item.cmyk && <span style={{ color:'var(--orange)' }}>CMYK · 300 DPI</span>}
            <span style={{ color:'var(--mint)' }}>✓ ADA contrast pass</span>
            <span style={{ color:'var(--mint)' }}>✓ NAP matches Brand Profile</span>
          </div>
        </div>
        {/* Side panel */}
        <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
          <div className="card">
            <div className="card-head"><h3 className="card-title">Content overrides</h3></div>
            <div className="card-body" style={{ padding:'12px 14px', display:'grid', gap:10 }}>
              <div className="field"><label>Headline</label><input value={overrides.headline} onChange={e=>setOverrides({...overrides, headline:e.target.value})} placeholder="Auto: slogan"/></div>
              <div className="field"><label>Sub / offer</label><input value={overrides.sub} onChange={e=>setOverrides({...overrides, sub:e.target.value})} placeholder="Auto: tagline"/></div>
              <div className="field"><label>CTA</label><input value={overrides.cta} onChange={e=>setOverrides({...overrides, cta:e.target.value})}/></div>
              <label style={{ display:'flex', alignItems:'center', gap:8, fontSize:'.72rem' }}>
                <input type="checkbox" checked={overrides.showQR} onChange={e=>setOverrides({...overrides, showQR:e.target.checked})}/>
                Include QR code to website
              </label>
            </div>
          </div>
          <div className="card">
            <div className="card-head"><h3 className="card-title">Send to print partner</h3></div>
            <div className="card-body" style={{ padding:'12px 14px', display:'grid', gap:6 }}>
              {partners.map(p => (
                <button key={p.id} className="btn btn-ghost btn-sm" style={{ justifyContent:'space-between', width:'100%' }}
                  onClick={() => window.wpsbToast?.(`Sent "${item.label}" to ${p.label}`, 'beam')}>
                  <span>{p.label}</span>
                  <span style={{ fontSize:'.56rem', color:'var(--dim)' }}>{p.desc}</span>
                </button>
              ))}
            </div>
          </div>
          <div className="card">
            <div className="card-head"><h3 className="card-title" style={{ color:'var(--mint)' }}>Pre-press checks</h3></div>
            <div className="card-body" style={{ padding:'12px 14px', display:'grid', gap:6, fontSize:'.68rem' }}>
              {[
                { ok:true,  msg:`Logo clear-space: ${Math.round(18)}px min ✓` },
                { ok:true,  msg:'Text contrast AA 4.5:1 ✓' },
                { ok:item.cmyk, msg:item.cmyk ? 'CMYK color profile locked ✓' : 'RGB — digital only' },
                { ok:true,  msg:`NAP matches Brand Profile ✓` },
                { ok:true,  msg:'Bleed marks + crop marks present ✓' },
              ].map((c,i) => (
                <div key={i} style={{ display:'flex', gap:6, alignItems:'center', color: c.ok ? 'var(--mint)' : 'var(--dim)' }}>
                  <Icon name={c.ok ? 'check' : 'circle'} size={12}/>{c.msg}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════
     ORDERS VIEW — demo order history
  ═══════════════════════════════════════════════════════════ */
  function OrdersView({ brand }) {
    const Icon = window.Icon;
    const orders = [
      { id:'ORD-1042', date:'Mar 18, 2026', item:'Business Card',      qty:500, partner:'Moo',         total:'$89',  status:'Delivered',  tracking:'1Z999AA10123456784' },
      { id:'ORD-1039', date:'Feb 22, 2026', item:'Yard sign × 20',     qty:20,  partner:'Signs.com',   total:'$312', status:'Delivered',  tracking:'9400111202555555555' },
      { id:'ORD-1033', date:'Jan 04, 2026', item:'Tri-fold brochure',  qty:1000,partner:'VistaPrint',  total:'$245', status:'In transit', tracking:'1Z999AA19876543210' },
    ];
    return (
      <div className="card">
        <div className="card-head">
          <h3 className="card-title">Recent print jobs · {brand.companyName}</h3>
          <button className="btn btn-ghost btn-sm"><Icon name="download" size={12}/>Export CSV</button>
        </div>
        <div className="card-body" style={{ padding:0 }}>
          <table className="data-table" style={{ width:'100%' }}>
            <thead>
              <tr>
                <th>Order</th><th>Date</th><th>Item</th><th>Qty</th><th>Partner</th><th>Total</th><th>Status</th><th>Tracking</th><th></th>
              </tr>
            </thead>
            <tbody>
              {orders.map(o => (
                <tr key={o.id}>
                  <td style={{ fontFamily:'var(--font-mono)' }}>{o.id}</td>
                  <td style={{ color:'var(--dim)' }}>{o.date}</td>
                  <td>{o.item}</td>
                  <td>{o.qty}</td>
                  <td>{o.partner}</td>
                  <td style={{ fontFamily:'var(--font-mono)' }}>{o.total}</td>
                  <td><span className="tag" style={{ color: o.status==='Delivered' ? 'var(--mint)' : 'var(--warn)' }}>{o.status}</span></td>
                  <td style={{ fontFamily:'var(--font-mono)', fontSize:'.6rem', color:'var(--dim)' }}>{o.tracking}</td>
                  <td><button className="btn btn-ghost btn-sm" onClick={() => window.wpsbToast?.(`Reorder "${o.item}" queued`, 'beam')}>Reorder</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    );
  }

  /* ═══════════════════════════════════════════════════════════
     BUILD STATUS BANNER — honest about what's demo vs. live
     Same pattern as BusinessMetrics' deploy checklist.
  ═══════════════════════════════════════════════════════════ */
  function BuildStatusBanner() {
    const Icon = window.Icon;
    const [expanded, setExpanded] = useState(false);
    const ITEMS = [
      { name:'Template catalog + specs',              status:'done',    notes:'24 templates · sizes / bleed / CMYK flags correct' },
      { name:'Brand Profile auto-populate',           status:'done',    notes:'Reads wpsb-brand-profile from localStorage' },
      { name:'Partner routing (Moo / VP / Signs.com)', status:'done',   notes:'Kind-gated · shows only compatible partners per template' },
      { name:'Pre-press validation checklist',        status:'done',    notes:'Client-side contrast + NAP check against Brand Profile' },
      { name:'Template thumbnails (grid)',            status:'demo',    notes:'SVG stylized previews — not print-accurate renders' },
      { name:'Full-preview canvas render',            status:'demo',    notes:'Needs html2canvas or server-side Chromium for real output' },
      { name:'PDF / CMYK TIFF export',                status:'pending', notes:'Requires Ghostscript on Railway · ~6 hrs to wire' },
      { name:'QR-code generation',                    status:'pending', notes:'Client-side via qrcode.js — ~30 min' },
      { name:'Partner API (order submission)',        status:'pending', notes:'Moo / VistaPrint / Signs.com each need OAuth + order payload' },
      { name:'Order history + tracking',              status:'demo',    notes:'Table UI done · needs Supabase print_orders table' },
    ];
    const done    = ITEMS.filter(i => i.status === 'done').length;
    const demo    = ITEMS.filter(i => i.status === 'demo').length;
    const pending = ITEMS.filter(i => i.status === 'pending').length;
    return (
      <div className="card" style={{ marginBottom:16, borderColor:'var(--orange-dim)' }}>
        <div className="card-head" style={{ background:'var(--orange-dim)' }}>
          <h3 className="card-title" style={{ color:'var(--orange)' }}>
            <Icon name="circle" size={11} style={{ marginRight:6 }}/>
            Implementation status · {done} working · {demo} demo · {pending} pending backend
          </h3>
          <button className="btn btn-ghost btn-sm" onClick={() => setExpanded(!expanded)}>
            {expanded ? 'Hide details' : "What's real vs. demo?"}
          </button>
        </div>
        {expanded && (
          <div className="card-body" style={{ padding:0 }}>
            <table className="data-table" style={{ width:'100%' }}>
              <thead>
                <tr>
                  <th>Feature</th>
                  <th style={{ width:90, textAlign:'center' }}>Status</th>
                  <th>Notes</th>
                </tr>
              </thead>
              <tbody>
                {ITEMS.map((item, i) => {
                  const color = item.status === 'done' ? 'var(--mint)'
                              : item.status === 'demo' ? 'var(--orange)'
                              : 'var(--warn)';
                  return (
                    <tr key={i}>
                      <td style={{ color:'var(--text)', fontWeight:500 }}>{item.name}</td>
                      <td style={{ textAlign:'center' }}>
                        <span className="tag" style={{ color, fontSize:'.56rem', letterSpacing:'.08em', fontWeight:700 }}>
                          {item.status.toUpperCase()}
                        </span>
                      </td>
                      <td style={{ fontSize:'.66rem', color:'var(--dim)' }}>{item.notes}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            <div style={{ padding:'10px 16px', borderTop:'1px solid var(--border)', background:'var(--surface-2)', fontSize:'.64rem', color:'var(--muted)', display:'flex', justifyContent:'space-between', flexWrap:'wrap', gap:8 }}>
              <span><strong style={{ color:'var(--mint)' }}>DONE</strong> fully functional · <strong style={{ color:'var(--orange)' }}>DEMO</strong> UI works, output not print-accurate · <strong style={{ color:'var(--warn)' }}>PENDING</strong> needs backend</span>
              <span style={{ fontFamily:'var(--font-mono)' }}>Full deploy est: ~12 hrs (PDF 6h · partner APIs 4h · orders schema 2h)</span>
            </div>
          </div>
        )}
      </div>
    );
  }

  window.MarketingMaterials = MarketingMaterials;
})();
