// SP13 / M13 — Email Studio
// Transactional + marketing email management: templates, composer, drip campaigns,
// send log, deliverability. Lives inside the CMS admin shell.

const EmailStudio = ({ setPage }) => {
  const [view, setView] = React.useState('dashboard');
  const [tplId, setTplId] = React.useState(null);

  return (
    <div style={{
      display:'grid', gridTemplateColumns:'240px 1fr',
      minHeight:'100vh', background:'#070708', color:'var(--ink)', fontSize:14
    }}>
      <EmailSidebar view={view} setView={setView} setPage={setPage} setTplId={setTplId}/>
      <div style={{display:'flex',flexDirection:'column',minWidth:0}}>
        <EmailTopbar view={view} tplId={tplId}/>
        <div style={{flex:1, overflow:'auto'}}>
          {view === 'dashboard' && <EmailDashboard setView={setView} setTplId={setTplId}/>}
          {view === 'templates' && !tplId && <TemplateLibrary onOpen={setTplId}/>}
          {view === 'templates' && tplId && <TemplateEditor id={tplId} onBack={()=>setTplId(null)}/>}
          {view === 'campaigns' && <Campaigns/>}
          {view === 'log' && <SendLog/>}
          {view === 'audiences' && <Audiences/>}
          {view === 'deliverability' && <Deliverability/>}
          {view === 'settings' && <EmailSettings/>}
        </div>
      </div>
    </div>
  );
};

// ── DATA ─────────────────────────────────────────────────────────

const EMAIL_TEMPLATES = [
  { id:'verify', name:'Verify your email', kind:'transactional', cat:'Auth', sent24:847, opens:92, status:'live', updated:'2h ago', subject:'Confirm your SolidAtoms email', c:'#7c9bff' },
  { id:'reset', name:'Reset password', kind:'transactional', cat:'Auth', sent24:124, opens:96, status:'live', updated:'1d', subject:'Reset your SolidAtoms password', c:'#7c9bff' },
  { id:'magic', name:'Magic link login', kind:'transactional', cat:'Auth', sent24:312, opens:98, status:'live', updated:'2d', subject:'Your sign-in link', c:'#7c9bff' },
  { id:'mfa', name:'MFA code', kind:'transactional', cat:'Auth', sent24:1041, opens:99, status:'live', updated:'3d', subject:'Your code: {{code}}', c:'#7c9bff' },
  { id:'invoice', name:'Invoice paid', kind:'transactional', cat:'Billing', sent24:42, opens:88, status:'live', updated:'1w', subject:'Receipt for {{invoice}}', c:'#fde047' },
  { id:'inv-due', name:'Invoice due', kind:'transactional', cat:'Billing', sent24:18, opens:74, status:'live', updated:'1w', subject:'Invoice {{invoice}} is due in 3 days', c:'#fde047' },
  { id:'sow', name:'SOW ready to sign', kind:'transactional', cat:'Sales', sent24:6, opens:100, status:'live', updated:'2w', subject:'Your SOW is ready', c:'#a78bfa' },
  { id:'kickoff', name:'Project kickoff', kind:'transactional', cat:'Project', sent24:3, opens:100, status:'live', updated:'2w', subject:'Welcome to your SolidAtoms project', c:'#d4ff3a' },
  { id:'demo', name:'Demo reminder', kind:'transactional', cat:'Project', sent24:8, opens:87, status:'live', updated:'3w', subject:'Demo tomorrow at {{time}}', c:'#d4ff3a' },
  { id:'review', name:'Review requested', kind:'transactional', cat:'Project', sent24:14, opens:78, status:'live', updated:'3w', subject:'{{author}} wants your review', c:'#d4ff3a' },
  { id:'atoms', name:'Atoms newsletter #18', kind:'marketing', cat:'Newsletter', sent24:0, scheduled:'Fri 09:00', opens:0, status:'scheduled', updated:'30m ago', subject:'How we rebuilt a 14-year-old monolith', c:'#ff8a3a' },
  { id:'atoms17', name:'Atoms newsletter #17', kind:'marketing', cat:'Newsletter', sent24:0, opens:48, sent:3214, status:'sent', updated:'1w', subject:'RAG is dead. Long live agents.', c:'#ff8a3a' },
  { id:'welcome', name:'Welcome — new lead', kind:'drip', cat:'Sales', sent24:14, opens:71, status:'live', step:'Step 1 of 4', updated:'4d', subject:'Thanks for the brief, {{name}}', c:'#a78bfa' },
];

const SEND_EVENTS = [
  ['09:42','verify','sarah@northbound.io','delivered','#7ee787'],
  ['09:41','mfa','jane@ledgerline.io','delivered','#7ee787'],
  ['09:40','review','bilal@solidatoms.com','opened','#d4ff3a'],
  ['09:38','demo','jane@ledgerline.io','delivered','#7ee787'],
  ['09:33','verify','noreply@invalid.test','bounced','#ff5a3a'],
  ['09:30','reset','amir@solidatoms.com','clicked','#d4ff3a'],
  ['09:28','invoice','billing@verge.shop','delivered','#7ee787'],
  ['09:24','magic','hassan@solidatoms.com','opened','#d4ff3a'],
  ['09:22','sow','contact@atlasdocs.org','delivered','#7ee787'],
  ['09:20','mfa','jane@ledgerline.io','delivered','#7ee787'],
  ['09:18','verify','old@bounce.invalid','bounced','#ff5a3a'],
  ['09:15','demo','team@claro.ai','delivered','#7ee787'],
];

// ── SIDEBAR + TOPBAR ─────────────────────────────────────────────

const EmailSidebar = ({ view, setView, setPage, setTplId }) => {
  const NAV = [
    {section:'Workspace', items:[
      ['dashboard','◐','Dashboard'],
      ['log','◌','Send log',null,12],
    ]},
    {section:'Templates', items:[
      ['templates','▤','All templates',EMAIL_TEMPLATES.length],
    ]},
    {section:'Campaigns', items:[
      ['campaigns','◇','Drip campaigns',3],
      ['audiences','◍','Audiences',5],
    ]},
    {section:'Admin', items:[
      ['deliverability','◔','Deliverability'],
      ['settings','◯','Settings & DNS'],
    ]},
  ];

  return (
    <aside style={{borderRight:'1px solid var(--line)',background:'#0a0a0b',display:'flex',flexDirection:'column',position:'sticky',top:0,height:'100vh'}}>
      <div style={{padding:'16px 18px',borderBottom:'1px solid var(--line)',display:'flex',alignItems:'center',gap:10}}>
        <span style={{display:'inline-flex',alignItems:'center',justifyContent:'center',width:28,height:28,border:'1px solid var(--line-2)',borderRadius:8,color:'var(--accent)'}}>{Icon.atom()}</span>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontWeight:600,fontSize:13,letterSpacing:'-0.005em',lineHeight:1.1}}>Email Studio</div>
          <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginTop:2}}>M13 · POWERED BY RESEND</div>
        </div>
        <button onClick={()=>setPage('cms')} title="Back to CMS" style={{padding:5,borderRadius:6,color:'var(--ink-3)'}}>↗</button>
      </div>

      <div style={{padding:'14px 12px',display:'flex',flexDirection:'column',gap:2,flex:1,overflow:'auto'}}>
        {NAV.map((g,gi) => (
          <React.Fragment key={g.section}>
            <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.08em',padding:'12px 10px 6px',textTransform:'uppercase'}}>{g.section}</div>
            {g.items.map(([id,ic,l,count,hot]) => (
              <button key={id} onClick={()=>{setView(id); setTplId(null);}} style={{
                display:'flex',alignItems:'center',gap:10,padding:'7px 10px',borderRadius:7,
                background: view===id ? 'rgba(212,255,58,0.08)' : 'transparent',
                color: view===id ? 'var(--accent)' : 'var(--ink-2)',
                fontSize:13, fontWeight: view===id ? 500 : 400, textAlign:'left'
              }}>
                <span style={{width:14,fontSize:11,color: view===id ? 'var(--accent)' : 'var(--ink-3)'}}>{ic}</span>
                <span style={{flex:1}}>{l}</span>
                {hot && <span className="mono" style={{fontSize:9,padding:'2px 5px',borderRadius:4,background:'var(--accent)',color:'#0a0a0a',fontWeight:600}}>{hot}</span>}
                {count != null && <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{count}</span>}
              </button>
            ))}
          </React.Fragment>
        ))}
      </div>

      <div style={{padding:'12px',borderTop:'1px solid var(--line)'}}>
        <div style={{display:'flex',alignItems:'center',gap:10,padding:'8px 10px',borderRadius:8,background:'rgba(126,231,135,0.04)',border:'1px solid rgba(126,231,135,0.18)'}}>
          <span style={{width:6,height:6,borderRadius:'50%',background:'var(--ok)',boxShadow:'0 0 0 3px rgba(126,231,135,0.18)'}}/>
          <div style={{flex:1,minWidth:0,fontSize:11,color:'var(--ink-2)'}}>
            <div style={{fontWeight:500}}>API · operational</div>
            <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginTop:1}}>RESEND · 99.97% UPTIME</div>
          </div>
        </div>
      </div>
    </aside>
  );
};

const EmailTopbar = ({ view, tplId }) => {
  const labels = {
    dashboard:'Dashboard',
    templates: tplId ? `Templates / ${tplId}` : 'Templates',
    campaigns:'Drip campaigns',
    log:'Send log',
    audiences:'Audiences',
    deliverability:'Deliverability',
    settings:'Settings & DNS',
  };
  return (
    <header style={{
      display:'flex',alignItems:'center',justifyContent:'space-between',
      padding:'12px 24px',borderBottom:'1px solid var(--line)',
      background:'rgba(10,10,11,0.7)',backdropFilter:'blur(12px)',
      position:'sticky',top:0,zIndex:20
    }}>
      <div style={{display:'flex',alignItems:'center',gap:10,fontSize:13,color:'var(--ink-3)'}}>
        <span>Email Studio</span>
        <span style={{color:'var(--ink-4)'}}>/</span>
        <span style={{color:'var(--ink-2)'}}>{labels[view]}</span>
      </div>
      <div style={{display:'flex',alignItems:'center',gap:10}}>
        <div style={{display:'flex',alignItems:'center',gap:8,padding:'7px 12px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)',width:240}}>
          <span style={{color:'var(--ink-3)',fontSize:12}}>⌕</span>
          <input placeholder="Search templates, sends…" style={{flex:1,background:'transparent',border:0,color:'var(--ink)',outline:'none',fontSize:12,fontFamily:'var(--sans)'}}/>
        </div>
        <button className="btn btn-ghost" style={{padding:'7px 11px',fontSize:12}}>Send test</button>
        <button className="btn btn-primary" style={{padding:'7px 12px',fontSize:12}}>+ New template</button>
      </div>
    </header>
  );
};

// ── DASHBOARD ────────────────────────────────────────────────────

const EmailDashboard = ({ setView, setTplId }) => (
  <div style={{padding:'28px 32px'}}>
    <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:24}}>
      <div>
        <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:6}}>Email Studio</h1>
        <div style={{fontSize:13,color:'var(--ink-3)'}}>{EMAIL_TEMPLATES.length} templates · 2,431 emails sent in the last 24h</div>
      </div>
      <div style={{display:'flex',gap:8}}>
        <button className="btn btn-ghost" style={{padding:'8px 12px',fontSize:12}}>Last 24h ▾</button>
        <button className="btn btn-ghost" style={{padding:'8px 12px',fontSize:12}}>Export</button>
      </div>
    </div>

    {/* Stat row */}
    <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:14,marginBottom:20}}>
      <StatCard label="Sent" value="2,431" delta="+12.4% vs yesterday" trend="up"/>
      <StatCard label="Delivered" value="99.6%" delta="2,421 of 2,431" trend="up"/>
      <StatCard label="Open rate" value="68.4%" delta="+2.1 pts" trend="up"/>
      <StatCard label="Click rate" value="34.2%" delta="−0.6 pts" trend="down"/>
      <StatCard label="Bounces" value="10" delta="0.4% — within limit" trend="warn"/>
    </div>

    {/* Volume chart */}
    <div className="card" style={{padding:'24px 28px',marginBottom:20}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:18}}>
        <div>
          <div className="mono" style={{fontSize:10,color:'var(--accent)',letterSpacing:'0.06em',marginBottom:6}}>● VOLUME · 7 DAYS</div>
          <div style={{fontSize:24,fontWeight:500,letterSpacing:'-0.02em'}}>14,283 emails sent this week</div>
        </div>
        <div style={{display:'flex',gap:12,fontSize:11}}>
          {[['Delivered','#d4ff3a'],['Bounced','#ff5a3a'],['Complained','#ffb43a']].map(([l,c]) => (
            <div key={l} style={{display:'flex',alignItems:'center',gap:6,color:'var(--ink-3)'}}>
              <span style={{width:10,height:10,borderRadius:3,background:c}}/>{l}
            </div>
          ))}
        </div>
      </div>
      <VolumeChart/>
      <div style={{display:'grid',gridTemplateColumns:'repeat(7,1fr)',gap:0,marginTop:8}}>
        {['Mon','Tue','Wed','Thu','Fri','Sat','Sun'].map(d => (
          <div key={d} className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em',textAlign:'center'}}>{d}</div>
        ))}
      </div>
    </div>

    {/* Two-col */}
    <div style={{display:'grid',gridTemplateColumns:'1.5fr 1fr',gap:14}}>
      <CMSCard title="Top templates · last 24h" action="All →" onAction={()=>setView('templates')}>
        {EMAIL_TEMPLATES.filter(t=>t.kind==='transactional').slice(0,5).map((t,i) => (
          <div key={t.id} onClick={()=>{setView('templates'); setTplId(t.id);}} className="clickable" style={{display:'grid',gridTemplateColumns:'30px 1fr 80px 70px 60px',gap:14,padding:'12px 4px',borderBottom: i<4 ? '1px solid var(--line)' : 'none',alignItems:'center'}}>
            <span style={{width:26,height:26,borderRadius:6,background:`linear-gradient(135deg, ${t.c}55, ${t.c}22)`,border:`1px solid ${t.c}44`,display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--mono)',fontSize:9,fontWeight:600,color:t.c}}>{t.cat.slice(0,2).toUpperCase()}</span>
            <div style={{minWidth:0}}>
              <div style={{fontSize:13,fontWeight:500,letterSpacing:'-0.005em'}}>{t.name}</div>
              <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em',marginTop:2,textTransform:'uppercase'}}>{t.cat}</div>
            </div>
            <span style={{fontSize:13,fontWeight:500,color:'var(--ink)',textAlign:'right'}}>{t.sent24.toLocaleString()}</span>
            <span style={{fontSize:13,color:'var(--accent)',textAlign:'right'}}>{t.opens}%</span>
            <span style={{color:'var(--ink-3)',justifySelf:'end'}}>{Icon.arrow()}</span>
          </div>
        ))}
      </CMSCard>

      <CMSCard title="Live activity" action="Send log →" onAction={()=>setView('log')}>
        {SEND_EVENTS.slice(0,5).map((e,i) => (
          <div key={i} style={{display:'grid',gridTemplateColumns:'42px 1fr auto',gap:10,padding:'10px 4px',alignItems:'center',borderBottom: i<4 ? '1px solid var(--line)' : 'none'}}>
            <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{e[0]}</span>
            <div style={{minWidth:0}}>
              <div style={{fontSize:12,color:'var(--ink-2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                <span style={{color:'var(--ink)',fontWeight:500}}>{e[1]}</span> → {e[2]}
              </div>
            </div>
            <span className="mono" style={{fontSize:9,color:e[4],padding:'2px 6px',borderRadius:4,background:`${e[4]}11`,border:`1px solid ${e[4]}33`,letterSpacing:'0.06em',textTransform:'uppercase'}}>{e[3]}</span>
          </div>
        ))}
      </CMSCard>

      <CMSCard title="Scheduled" pad>
        <div style={{display:'flex',flexDirection:'column',gap:10}}>
          {[
            ['Fri 09:00','Atoms newsletter #18','3,214 subs','#ff8a3a'],
            ['Mon 10:00','Sprint 12 kickoff','5 recipients','#d4ff3a'],
            ['Wed 14:00','Q2 client update','41 recipients','#a78bfa'],
          ].map(([t,n,r,c],i) => (
            <div key={i} style={{display:'grid',gridTemplateColumns:'80px 1fr 90px',gap:12,alignItems:'center',padding:'8px 10px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)'}}>
              <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{t}</span>
              <div style={{display:'flex',alignItems:'center',gap:8,minWidth:0}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:c,flexShrink:0}}/>
                <span style={{fontSize:12,fontWeight:500,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{n}</span>
              </div>
              <span className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',textAlign:'right'}}>{r.toUpperCase()}</span>
            </div>
          ))}
        </div>
      </CMSCard>

      <CMSCard title="Deliverability snapshot" action="Full report →" onAction={()=>setView('deliverability')}>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,marginBottom:14}}>
          {[
            ['SPF','PASS','#7ee787'],
            ['DKIM','PASS','#7ee787'],
            ['DMARC','PASS','#7ee787'],
            ['REPUTATION','99/100','#d4ff3a'],
          ].map(([l,v,c]) => (
            <div key={l} style={{padding:'12px 14px',borderRadius:8,background:'var(--bg-3)',border:`1px solid ${c}33`}}>
              <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:6}}>{l}</div>
              <div style={{fontSize:14,fontWeight:500,color:c}}>{v}</div>
            </div>
          ))}
        </div>
        <div style={{padding:'10px 12px',borderRadius:7,background:'rgba(126,231,135,0.06)',border:'1px solid rgba(126,231,135,0.2)',fontSize:11,color:'var(--ink-2)'}}>
          ● All systems operational. No domains under throttling.
        </div>
      </CMSCard>
    </div>
  </div>
);

const VolumeChart = () => {
  const days = [1850, 2120, 1980, 2310, 2431, 1620, 1972];
  const max = Math.max(...days);
  return (
    <svg viewBox="0 0 700 160" style={{width:'100%',height:160}}>
      <defs>
        <linearGradient id="vchg" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor="#d4ff3a" stopOpacity="0.4"/>
          <stop offset="100%" stopColor="#d4ff3a" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {[0,40,80,120].map(y => <line key={y} x1="0" x2="700" y1={y} y2={y} stroke="var(--line)" strokeDasharray="2 4"/>)}
      {days.map((v,i) => {
        const x = 50 + i*100;
        const h = (v/max) * 130;
        return (
          <g key={i}>
            <rect x={x-22} y={150-h} width="44" height={h} fill={`url(#vchg)`} stroke="#d4ff3a" strokeWidth="1.5" rx="3"/>
            <text x={x} y={150-h-6} fontFamily="JetBrains Mono" fontSize="10" fill="var(--ink-2)" textAnchor="middle">{v.toLocaleString()}</text>
            {/* tiny stripe of bounces */}
            <rect x={x-22} y={144} width="44" height="4" fill="#ff5a3a" opacity="0.35" rx="2"/>
          </g>
        );
      })}
    </svg>
  );
};

// ── TEMPLATE LIBRARY ─────────────────────────────────────────────

const TemplateLibrary = ({ onOpen }) => {
  const [kind, setKind] = React.useState('all');
  const [cat, setCat] = React.useState('all');
  const kinds = [['all','All'],['transactional','Transactional'],['marketing','Marketing'],['drip','Drip']];
  const cats = ['all','Auth','Billing','Sales','Project','Newsletter'];
  const filtered = EMAIL_TEMPLATES.filter(t =>
    (kind==='all' || t.kind===kind) &&
    (cat==='all' || t.cat===cat)
  );

  return (
    <div style={{padding:'28px 32px'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:20}}>
        <div>
          <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:4}}>Templates</h1>
          <div style={{fontSize:13,color:'var(--ink-3)'}}>{EMAIL_TEMPLATES.length} templates · {EMAIL_TEMPLATES.filter(t=>t.status==='live').length} live</div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <button className="btn btn-ghost" style={{padding:'8px 12px',fontSize:12}}>Import HTML</button>
          <button className="btn btn-primary" style={{padding:'8px 14px',fontSize:12}}>+ New template</button>
        </div>
      </div>

      {/* Filters */}
      <div style={{display:'flex',gap:24,alignItems:'center',marginBottom:18,paddingBottom:14,borderBottom:'1px solid var(--line)',flexWrap:'wrap'}}>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em'}}>KIND</span>
          <div style={{display:'flex',gap:4}}>
            {kinds.map(([k,l]) => (
              <button key={k} onClick={()=>setKind(k)} style={{
                padding:'5px 10px',borderRadius:6,fontSize:12,
                background: kind===k ? 'rgba(255,255,255,0.06)' : 'transparent',
                color: kind===k ? 'var(--ink)' : 'var(--ink-3)',
                border:'1px solid', borderColor: kind===k ? 'var(--line-2)' : 'transparent'
              }}>{l}</button>
            ))}
          </div>
        </div>
        <div style={{width:1,height:24,background:'var(--line)'}}/>
        <div style={{display:'flex',alignItems:'center',gap:8}}>
          <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em'}}>CATEGORY</span>
          <div style={{display:'flex',gap:4}}>
            {cats.map(c => (
              <button key={c} onClick={()=>setCat(c)} style={{
                padding:'5px 10px',borderRadius:6,fontSize:12,
                background: cat===c ? 'rgba(255,255,255,0.06)' : 'transparent',
                color: cat===c ? 'var(--ink)' : 'var(--ink-3)',
                border:'1px solid', borderColor: cat===c ? 'var(--line-2)' : 'transparent',
                textTransform:'capitalize'
              }}>{c}</button>
            ))}
          </div>
        </div>
        <div style={{flex:1}}/>
        <span className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.06em'}}>{filtered.length} OF {EMAIL_TEMPLATES.length}</span>
      </div>

      {/* Grid of preview cards */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(280px,1fr))',gap:14}}>
        {filtered.map(t => (
          <button key={t.id} onClick={()=>onOpen(t.id)} className="card clickable" style={{padding:0,overflow:'hidden',textAlign:'left',display:'flex',flexDirection:'column'}}>
            <div style={{position:'relative',aspectRatio:'4/5',padding:18,background:`linear-gradient(135deg, ${t.c}11, var(--bg-2))`,borderBottom:'1px solid var(--line)'}}>
              {/* mini email preview */}
              <div style={{background:'#fff',color:'#111',borderRadius:6,padding:'14px 14px',height:'100%',fontFamily:'system-ui',fontSize:8,display:'flex',flexDirection:'column',gap:6,boxShadow:'0 8px 20px rgba(0,0,0,0.4)'}}>
                <div style={{display:'flex',alignItems:'center',gap:4,marginBottom:4}}>
                  <span style={{width:14,height:14,borderRadius:4,background:t.c,display:'flex',alignItems:'center',justifyContent:'center',color:'#fff',fontWeight:700,fontSize:7}}>S</span>
                  <span style={{fontWeight:600,fontSize:8}}>SolidAtoms</span>
                </div>
                <div style={{fontSize:11,fontWeight:600,color:'#000',marginBottom:2,letterSpacing:'-0.01em'}}>{t.subject.replace(/\{\{[^}]+\}\}/g,'•••')}</div>
                <div style={{height:1,background:'#eee',margin:'2px 0'}}/>
                <div style={{fontSize:7,color:'#555',lineHeight:1.5}}>Hi {`{{name}}`}, …</div>
                <div style={{fontSize:7,color:'#555',lineHeight:1.5}}>{'Lorem ipsum dolor sit amet, consectetur adipiscing.'}</div>
                <div style={{flex:1}}/>
                <div style={{display:'inline-block',padding:'4px 8px',background:'#0a0a0a',color:'#fff',borderRadius:3,fontSize:7,fontWeight:600,width:'fit-content'}}>{t.cat==='Auth'?'Verify':t.cat==='Billing'?'View receipt':'Continue →'}</div>
              </div>
              <span style={{position:'absolute',top:8,right:8}}>
                <Tag accent={t.status==='live'}>{t.status}</Tag>
              </span>
            </div>
            <div style={{padding:'14px 16px',display:'flex',flexDirection:'column',gap:8}}>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                <Tag>{t.cat}</Tag>
                <span className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',textTransform:'uppercase'}}>{t.kind}</span>
              </div>
              <div style={{fontSize:14,fontWeight:500,letterSpacing:'-0.005em',lineHeight:1.25}}>{t.name}</div>
              <div style={{display:'flex',justifyContent:'space-between',paddingTop:8,borderTop:'1px solid var(--line)',fontSize:11,color:'var(--ink-3)'}}>
                <span className="mono" style={{letterSpacing:'0.04em'}}>{t.sent24.toLocaleString()} sent · 24h</span>
                <span style={{color: t.opens > 80 ? 'var(--ok)' : 'var(--accent)'}}>{t.opens > 0 ? `${t.opens}% open` : t.scheduled || ''}</span>
              </div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
};

// ── TEMPLATE EDITOR ──────────────────────────────────────────────

const TemplateEditor = ({ id, onBack }) => {
  const t = EMAIL_TEMPLATES.find(x => x.id === id) || EMAIL_TEMPLATES[0];
  const [tab, setTab] = React.useState('design');
  const [previewMode, setPreviewMode] = React.useState('desktop');

  return (
    <div>
      {/* Editor topbar */}
      <div style={{padding:'12px 24px',borderBottom:'1px solid var(--line)',display:'flex',justifyContent:'space-between',alignItems:'center',position:'sticky',top:53,zIndex:10,background:'rgba(10,10,11,0.85)',backdropFilter:'blur(12px)'}}>
        <div style={{display:'flex',alignItems:'center',gap:14}}>
          <button onClick={onBack} style={{padding:'5px 10px',borderRadius:6,color:'var(--ink-2)',fontSize:12,border:'1px solid var(--line)'}}>← Templates</button>
          <div style={{display:'flex',alignItems:'center',gap:10}}>
            <span style={{width:8,height:8,borderRadius:'50%',background:'var(--warn)'}}/>
            <span style={{fontSize:13,fontWeight:500}}>{t.name}</span>
            <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em'}}>· v4 · unsaved</span>
          </div>
        </div>
        <div style={{display:'flex',gap:8}}>
          <div style={{display:'flex',padding:2,borderRadius:8,border:'1px solid var(--line)',gap:2}}>
            {[['desktop','▭'],['mobile','▯']].map(([m,ic]) => (
              <button key={m} onClick={()=>setPreviewMode(m)} style={{padding:'4px 9px',borderRadius:5,fontSize:12,background: previewMode===m ? 'var(--bg-3)' : 'transparent',color: previewMode===m ? 'var(--ink)' : 'var(--ink-3)'}}>{ic}</button>
            ))}
          </div>
          <button className="btn btn-ghost" style={{padding:'7px 11px',fontSize:12}}>Send test</button>
          <button className="btn btn-ghost" style={{padding:'7px 11px',fontSize:12}}>Preview ↗</button>
          <button className="btn btn-primary" style={{padding:'7px 13px',fontSize:12}}>Publish</button>
        </div>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'380px 1fr 280px',minHeight:'calc(100vh - 105px)'}}>
        {/* Left: editor controls */}
        <aside style={{borderRight:'1px solid var(--line)',background:'#0a0a0b',padding:'20px 22px',overflow:'auto'}}>
          <div style={{display:'flex',gap:2,marginBottom:18,borderBottom:'1px solid var(--line)'}}>
            {[['design','Design'],['code','HTML/MJML'],['variables','Variables']].map(([k,l]) => (
              <button key={k} onClick={()=>setTab(k)} style={{
                padding:'8px 12px',fontSize:12,
                color: tab===k ? 'var(--ink)' : 'var(--ink-3)',
                borderBottom:'2px solid', borderColor: tab===k ? 'var(--accent)' : 'transparent', marginBottom:-1
              }}>{l}</button>
            ))}
          </div>

          {tab === 'design' && (
            <div style={{display:'flex',flexDirection:'column',gap:18}}>
              <EditField label="From" value="Hassan from SolidAtoms <hi@solidatoms.com>" mono/>
              <EditField label="Reply-to" value="hi@solidatoms.com" mono/>
              <EditField label="Subject line" value={t.subject}/>
              <EditField label="Preheader" value="The next step in setting up your SolidAtoms account."/>

              <div>
                <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:8,textTransform:'uppercase'}}>Blocks</div>
                <div style={{display:'flex',flexDirection:'column',gap:6}}>
                  {[
                    ['Logo + brand bar','◉'],
                    ['Heading · "Verify your email"','H'],
                    ['Body · Hi {{name}}, please confirm…','¶'],
                    ['CTA button · Verify email','▭'],
                    ['Body · This link expires in 24h.','¶'],
                    ['Signature block','✉'],
                    ['Footer · address + unsubscribe','▱'],
                  ].map(([n,ic],i)=>(
                    <div key={i} style={{display:'grid',gridTemplateColumns:'24px 1fr auto',gap:10,padding:'8px 10px',borderRadius:7,background:'var(--bg-3)',border:'1px solid var(--line)',alignItems:'center'}}>
                      <span style={{width:22,height:22,borderRadius:5,background:'rgba(212,255,58,0.08)',border:'1px solid rgba(212,255,58,0.2)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:11,color:'var(--accent)'}}>{ic}</span>
                      <span style={{fontSize:12,color:'var(--ink-2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{n}</span>
                      <span style={{color:'var(--ink-3)',fontSize:11,cursor:'grab'}}>⋮⋮</span>
                    </div>
                  ))}
                  <button style={{padding:'8px 10px',borderRadius:7,fontSize:12,color:'var(--ink-3)',border:'1px dashed var(--line-2)',background:'transparent',marginTop:4}}>+ Add block</button>
                </div>
              </div>
            </div>
          )}

          {tab === 'code' && (
            <div>
              <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:10,textTransform:'uppercase'}}>MJML SOURCE</div>
              <pre style={{padding:'14px 16px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)',fontSize:11,fontFamily:'var(--mono)',color:'var(--ink-2)',lineHeight:1.5,overflow:'auto'}}>{`<mjml>
  <mj-head>
    <mj-title>${t.subject}</mj-title>
    <mj-attributes>
      <mj-all font-family="Inter, system-ui" />
    </mj-attributes>
  </mj-head>
  <mj-body background-color="#fff">
    <mj-section padding="32px 24px">
      <mj-column>
        <mj-image src="/logo.png" width="32px" align="left"/>
        <mj-text font-size="24px" font-weight="500" padding-top="24px">
          Verify your email
        </mj-text>
        <mj-text>
          Hi {{name}}, please confirm…
        </mj-text>
        <mj-button background-color="#0a0a0a" color="#d4ff3a" href="{{url}}">
          Verify email
        </mj-button>
      </mj-column>
    </mj-section>
  </mj-body>
</mjml>`}</pre>
            </div>
          )}

          {tab === 'variables' && (
            <div style={{display:'flex',flexDirection:'column',gap:8}}>
              <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:6,textTransform:'uppercase'}}>Template variables</div>
              {[
                ['name','string','User\'s display name','Jane Cooper'],
                ['email','string','User\'s email','jane@ledgerline.io'],
                ['url','url','Verification URL','https://solid…?t=abc123'],
                ['code','string','6-digit code','842913'],
                ['expires_in','duration','Token validity','24 hours'],
              ].map(([n,t2,d,sample]) => (
                <div key={n} style={{padding:'12px 14px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)'}}>
                  <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:4}}>
                    <span className="mono" style={{fontSize:12,color:'var(--accent)'}}>{`{{${n}}}`}</span>
                    <span className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.04em',textTransform:'uppercase'}}>{t2}</span>
                  </div>
                  <div style={{fontSize:11,color:'var(--ink-3)',marginBottom:4}}>{d}</div>
                  <div className="mono" style={{fontSize:10,color:'var(--ink-2)',padding:'4px 8px',borderRadius:4,background:'rgba(255,255,255,0.03)',border:'1px solid var(--line)'}}>SAMPLE · {sample}</div>
                </div>
              ))}
              <button style={{padding:'8px 10px',borderRadius:7,fontSize:12,color:'var(--ink-3)',border:'1px dashed var(--line-2)',background:'transparent',marginTop:4}}>+ Add variable</button>
            </div>
          )}
        </aside>

        {/* Middle: live preview */}
        <div style={{padding:'28px 32px',background:'#0c0c0e',display:'flex',justifyContent:'center',overflow:'auto'}}>
          <EmailPreview t={t} previewMode={previewMode}/>
        </div>

        {/* Right: stats + version history */}
        <aside style={{borderLeft:'1px solid var(--line)',background:'#0a0a0b',padding:'20px 22px',display:'flex',flexDirection:'column',gap:18,overflow:'auto'}}>
          <Panel title="Performance · last 30d">
            <Row label="Sent" value={(t.sent24*30).toLocaleString()}/>
            <Row label="Delivered" value="99.6%"/>
            <Row label="Open rate" value={<span style={{color:'var(--accent)'}}>{t.opens}%</span>}/>
            <Row label="Click rate" value="42.1%"/>
            <Row label="Bounce" value={<span style={{color:'var(--warn)'}}>0.4%</span>}/>
          </Panel>

          <Panel title="Triggered by">
            <div style={{padding:'10px 12px',borderRadius:7,background:'var(--bg-3)',border:'1px solid var(--line)'}}>
              <div className="mono" style={{fontSize:11,color:'var(--accent)',marginBottom:6}}>auth.user.signed_up</div>
              <div style={{fontSize:11,color:'var(--ink-3)'}}>Fires when a user creates an account but hasn't verified.</div>
            </div>
          </Panel>

          <Panel title="A/B tests">
            <div style={{padding:'12px 14px',borderRadius:7,background:'rgba(212,255,58,0.05)',border:'1px solid rgba(212,255,58,0.2)'}}>
              <div style={{fontSize:12,fontWeight:500,color:'var(--ink)',marginBottom:4}}>"Verify your email" vs "Confirm your account"</div>
              <div style={{fontSize:11,color:'var(--ink-3)',marginBottom:8}}>50/50 split · 1,420 / 1,418 sent</div>
              <div style={{display:'flex',gap:10,fontSize:11}}>
                <span style={{color:'var(--ink-2)'}}>A: 92% · B: <span style={{color:'var(--accent)'}}>94%</span></span>
              </div>
            </div>
          </Panel>

          <Panel title="Version history" small>
            {[
              ['v4','You','Edited subject line','12m ago'],
              ['v3','Hassan A.','Tweaked CTA copy','3d'],
              ['v2','Sana R.','Updated brand bar','1w'],
              ['v1','Hassan A.','Initial template','3w'],
            ].map(([v,w,m,t2],i) => (
              <div key={v} style={{display:'grid',gridTemplateColumns:'30px 1fr 60px',gap:8,padding:'8px 0',borderTop: i>0 ? '1px solid var(--line)' : 'none',fontSize:11}}>
                <span className="mono" style={{color: i===0 ? 'var(--accent)' : 'var(--ink-3)',letterSpacing:'0.04em'}}>{v}</span>
                <div>
                  <div style={{color:'var(--ink-2)'}}>{m}</div>
                  <div style={{color:'var(--ink-3)',fontSize:10,marginTop:2}}>{w}</div>
                </div>
                <span className="mono" style={{color:'var(--ink-3)',fontSize:9,letterSpacing:'0.04em',textAlign:'right'}}>{t2}</span>
              </div>
            ))}
          </Panel>
        </aside>
      </div>
    </div>
  );
};

const EmailPreview = ({ t, previewMode }) => {
  const width = previewMode === 'mobile' ? 360 : 560;
  return (
    <div style={{width:'100%',maxWidth:width,transition:'max-width .2s ease'}}>
      <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:10,padding:'8px 14px',borderRadius:7,background:'var(--bg-3)',border:'1px solid var(--line)',fontSize:11,color:'var(--ink-3)'}}>
        <span style={{padding:'2px 8px',borderRadius:4,background:'#a4a0ff22',border:'1px solid #a4a0ff44',color:'#a4a0ff',fontFamily:'var(--mono)',fontSize:9,fontWeight:600,letterSpacing:'0.04em'}}>INBOX PREVIEW</span>
        <span>Hassan from SolidAtoms &lt;hi@solidatoms.com&gt;</span>
        <div style={{flex:1}}/>
        <span className="mono" style={{fontSize:10,letterSpacing:'0.04em'}}>9:42 AM</span>
      </div>
      <div style={{
        background:'#fff',borderRadius:8,overflow:'hidden',
        fontFamily:'system-ui, -apple-system, sans-serif',
        boxShadow:'0 24px 60px rgba(0,0,0,0.5), 0 4px 12px rgba(0,0,0,0.3)'
      }}>
        {/* Brand bar */}
        <div style={{padding:'24px 36px 0',color:'#111'}}>
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:32}}>
            <span style={{width:24,height:24,borderRadius:6,background:'#0a0a0a',display:'flex',alignItems:'center',justifyContent:'center',color:'#d4ff3a',fontSize:13,fontWeight:700}}>◉</span>
            <span style={{fontWeight:600,fontSize:14,letterSpacing:'-0.005em',color:'#111'}}>SolidAtoms</span>
          </div>

          <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:600,lineHeight:1.15,marginBottom:18,color:'#0a0a0a'}}>
            {t.cat === 'Auth' ? 'Verify your email address' :
             t.cat === 'Billing' ? 'Receipt for your payment' :
             t.cat === 'Project' ? 'Welcome to your project' :
             'A new update from SolidAtoms'}
          </h1>

          <p style={{fontSize:15,lineHeight:1.55,color:'#374151',marginBottom:14}}>Hi <strong style={{color:'#0a0a0a'}}>Jane</strong>,</p>

          {t.cat === 'Auth' && (
            <>
              <p style={{fontSize:15,lineHeight:1.55,color:'#374151',marginBottom:14}}>Thanks for signing up to SolidAtoms. To finish setting up your account, please confirm your email address by clicking the button below.</p>
            </>
          )}
          {t.cat === 'Billing' && (
            <>
              <p style={{fontSize:15,lineHeight:1.55,color:'#374151',marginBottom:14}}>This is your receipt for invoice <strong>INV-0042</strong>, paid on May 1, 2026. A copy is attached for your records.</p>
            </>
          )}
          {t.cat === 'Project' && (
            <>
              <p style={{fontSize:15,lineHeight:1.55,color:'#374151',marginBottom:14}}>Your project kicks off Monday at 10am. Here's where everything lives.</p>
            </>
          )}
          {t.cat === 'Newsletter' && (
            <>
              <p style={{fontSize:15,lineHeight:1.55,color:'#374151',marginBottom:14}}>This week we shipped one essay, one tool, and one case study you might find useful.</p>
            </>
          )}
          {t.cat === 'Sales' && (
            <>
              <p style={{fontSize:15,lineHeight:1.55,color:'#374151',marginBottom:14}}>Your SOW is ready to sign. Take a look — the scope, the timeline, the price are all in there.</p>
            </>
          )}

          {/* CTA */}
          <div style={{marginTop:24,marginBottom:24}}>
            <a style={{display:'inline-block',padding:'12px 22px',background:'#0a0a0a',color:'#d4ff3a',borderRadius:8,fontSize:14,fontWeight:500,letterSpacing:'-0.005em',textDecoration:'none'}}>
              {t.cat === 'Auth' ? 'Verify email →' :
               t.cat === 'Billing' ? 'View receipt →' :
               t.cat === 'Project' ? 'Open your portal →' :
               t.cat === 'Newsletter' ? 'Read the essay →' :
               'Review SOW →'}
            </a>
          </div>

          <p style={{fontSize:13,lineHeight:1.55,color:'#6b7280',marginBottom:24}}>This link expires in 24 hours. If you didn't sign up for SolidAtoms, you can safely ignore this email.</p>

          <div style={{padding:'14px 16px',borderRadius:8,background:'#f6f6f4',marginBottom:24}}>
            <div style={{fontSize:11,color:'#6b7280',marginBottom:6,fontFamily:'JetBrains Mono, monospace'}}>OR PASTE THIS URL</div>
            <div style={{fontSize:12,color:'#0a0a0a',fontFamily:'JetBrains Mono, monospace',wordBreak:'break-all'}}>https://solidatoms.com/verify?t=abc123def456ghi789</div>
          </div>
        </div>

        {/* Signature */}
        <div style={{padding:'0 36px 24px',color:'#111'}}>
          <p style={{fontSize:14,color:'#374151',marginBottom:14}}>— Hassan, founder at SolidAtoms</p>
        </div>

        {/* Footer */}
        <div style={{borderTop:'1px solid #e5e7eb',padding:'18px 36px',background:'#fafaf7'}}>
          <div style={{display:'flex',alignItems:'center',gap:8,marginBottom:8}}>
            <span style={{width:18,height:18,borderRadius:4,background:'#0a0a0a',display:'flex',alignItems:'center',justifyContent:'center',color:'#d4ff3a',fontSize:10}}>◉</span>
            <span style={{fontSize:11,fontWeight:600,color:'#374151'}}>SolidAtoms Studio</span>
          </div>
          <p style={{fontSize:10,color:'#9ca3af',lineHeight:1.5,marginBottom:8}}>Karachi → Remote · solidatoms.com</p>
          <div style={{display:'flex',gap:10,fontSize:10}}>
            <a style={{color:'#6b7280'}}>Unsubscribe</a>
            <span style={{color:'#d1d5db'}}>·</span>
            <a style={{color:'#6b7280'}}>Manage preferences</a>
            <span style={{color:'#d1d5db'}}>·</span>
            <a style={{color:'#6b7280'}}>View in browser</a>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── CAMPAIGNS (DRIP) ─────────────────────────────────────────────

const Campaigns = () => {
  const campaigns = [
    {n:'Welcome — new lead',steps:4,enr:142,conv:38,c:'#a78bfa',active:true,trigger:'contact_form.submitted'},
    {n:'Trial → paid (Studio)',steps:5,enr:48,conv:12,c:'#d4ff3a',active:true,trigger:'subscription.trial_started'},
    {n:'Onboarding · day 1, 3, 7',steps:3,enr:21,conv:18,c:'#7c9bff',active:true,trigger:'workspace.created'},
  ];

  return (
    <div style={{padding:'28px 32px'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:24}}>
        <div>
          <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:4}}>Drip campaigns</h1>
          <div style={{fontSize:13,color:'var(--ink-3)'}}>3 active sequences · 211 contacts enrolled</div>
        </div>
        <button className="btn btn-primary" style={{padding:'8px 14px',fontSize:12}}>+ New campaign</button>
      </div>

      <div style={{display:'flex',flexDirection:'column',gap:16}}>
        {campaigns.map((c,ci) => (
          <div key={c.n} className="card" style={{padding:'24px 28px'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:18}}>
              <div>
                <div style={{display:'flex',alignItems:'center',gap:10,marginBottom:8}}>
                  <span style={{width:8,height:8,borderRadius:'50%',background: c.active ? 'var(--ok)' : 'var(--ink-3)'}}/>
                  <h3 style={{fontSize:18,fontWeight:500,letterSpacing:'-0.015em'}}>{c.n}</h3>
                </div>
                <div style={{display:'flex',gap:14,fontSize:12,color:'var(--ink-3)'}}>
                  <span className="mono" style={{color:'var(--accent)'}}>{c.trigger}</span>
                  <span>·</span>
                  <span>{c.enr} enrolled</span>
                  <span>·</span>
                  <span style={{color:'var(--ok)'}}>{c.conv} converted</span>
                </div>
              </div>
              <div style={{display:'flex',gap:6}}>
                <button className="btn btn-ghost" style={{padding:'5px 10px',fontSize:11}}>Pause</button>
                <button className="btn btn-ghost" style={{padding:'5px 10px',fontSize:11}}>Edit</button>
              </div>
            </div>

            {/* Steps timeline */}
            <div style={{display:'grid',gridTemplateColumns:`repeat(${c.steps*2-1}, 1fr)`,gap:0,alignItems:'center'}}>
              {Array.from({length:c.steps},(_,i)=>i).map((i, ii) => (
                <React.Fragment key={i}>
                  <div style={{padding:'14px 14px',borderRadius:8,border:'1px solid var(--line)',background:'var(--bg-3)'}}>
                    <div className="mono" style={{fontSize:9,color:c.c,letterSpacing:'0.06em',marginBottom:6}}>STEP {i+1}</div>
                    <div style={{fontSize:13,fontWeight:500,marginBottom:6,letterSpacing:'-0.005em'}}>{
                      ci===0 ? ['Thanks for the brief','Why we ask what we ask','Case study you might like','Wanna chat?'][i] :
                      ci===1 ? ['Welcome to Studio','Set up your domain','Connect Stripe','One week left','Last day — upgrade?'][i] :
                      ['Day 1: First steps','Day 3: Invite team','Day 7: Power user tips'][i]
                    }</div>
                    <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{
                      i === 0 ? 'IMMEDIATE' : `WAIT ${[2,3,7][Math.min(i-1,2)]}D`
                    }</div>
                  </div>
                  {ii*2+1 < c.steps*2-1 && (
                    <div style={{display:'flex',justifyContent:'center',color:'var(--ink-3)'}}>→</div>
                  )}
                </React.Fragment>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ── SEND LOG ─────────────────────────────────────────────────────

const SendLog = () => {
  const filter = ['All','Delivered','Opened','Clicked','Bounced','Complained'];
  const [active, setActive] = React.useState('All');
  return (
    <div style={{padding:'28px 32px'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:18}}>
        <div>
          <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:4}}>Send log</h1>
          <div style={{fontSize:13,color:'var(--ink-3)'}}>Realtime · every send, every event, every webhook</div>
        </div>
        <button className="btn btn-ghost" style={{padding:'8px 12px',fontSize:12}}>Export CSV</button>
      </div>

      <div style={{display:'flex',gap:6,marginBottom:14}}>
        {filter.map(f => (
          <button key={f} onClick={()=>setActive(f)} style={{
            padding:'5px 10px',borderRadius:6,fontSize:12,
            background: active===f ? 'rgba(255,255,255,0.06)' : 'transparent',
            color: active===f ? 'var(--ink)' : 'var(--ink-3)',
            border:'1px solid', borderColor: active===f ? 'var(--line-2)' : 'transparent'
          }}>{f}</button>
        ))}
      </div>

      <div style={{border:'1px solid var(--line)',borderRadius:10,overflow:'hidden'}}>
        <div style={{display:'grid',gridTemplateColumns:'80px 140px 1.5fr 1fr 110px 60px',gap:14,padding:'10px 18px',background:'rgba(255,255,255,0.02)',borderBottom:'1px solid var(--line)'}}>
          {['Time','Template','To','Subject','Status',''].map(h => (
            <div key={h} className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.08em',textTransform:'uppercase'}}>{h}</div>
          ))}
        </div>
        {SEND_EVENTS.concat(SEND_EVENTS).map((e,i) => {
          const tpl = EMAIL_TEMPLATES.find(t => t.id === e[1]) || EMAIL_TEMPLATES[0];
          return (
            <div key={i} style={{display:'grid',gridTemplateColumns:'80px 140px 1.5fr 1fr 110px 60px',gap:14,padding:'12px 18px',alignItems:'center',borderTop: i>0 ? '1px solid var(--line)' : 'none'}}>
              <span className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{e[0]}</span>
              <div style={{display:'flex',alignItems:'center',gap:8,minWidth:0}}>
                <span style={{width:6,height:6,borderRadius:'50%',background:tpl.c,flexShrink:0}}/>
                <span className="mono" style={{fontSize:11,color:'var(--ink-2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{e[1]}</span>
              </div>
              <span style={{fontSize:12,color:'var(--ink-2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{e[2]}</span>
              <span style={{fontSize:12,color:'var(--ink-3)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{tpl.subject}</span>
              <span className="mono" style={{fontSize:9,color:e[4],padding:'3px 8px',borderRadius:5,background:`${e[4]}11`,border:`1px solid ${e[4]}33`,letterSpacing:'0.06em',textTransform:'uppercase',width:'fit-content'}}>{e[3]}</span>
              <span style={{color:'var(--ink-3)',justifySelf:'end'}}>{Icon.arrow()}</span>
            </div>
          );
        })}
      </div>

      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginTop:14,fontSize:12,color:'var(--ink-3)'}}>
        <span>Showing 24 of 2,431 events</span>
        <div style={{display:'flex',gap:6}}>
          <button style={{padding:'5px 9px',borderRadius:6,border:'1px solid var(--line)',color:'var(--ink-3)'}}>‹</button>
          <button style={{padding:'5px 9px',borderRadius:6,border:'1px solid var(--line)',color:'var(--ink-3)'}}>›</button>
        </div>
      </div>
    </div>
  );
};

// ── AUDIENCES ────────────────────────────────────────────────────

const Audiences = () => {
  const audiences = [
    {n:'Newsletter subscribers',size:3214,growth:'+24 this week',c:'#ff8a3a'},
    {n:'Active clients',size:14,growth:'+1 this month',c:'#d4ff3a'},
    {n:'Past clients',size:27,growth:'no change',c:'#a78bfa'},
    {n:'New leads · last 30d',size:42,growth:'+8 vs prev period',c:'#7c9bff'},
    {n:'Tools — paid users',size:218,growth:'+12 this week',c:'#fde047'},
  ];
  return (
    <div style={{padding:'28px 32px'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-end',marginBottom:24}}>
        <div>
          <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:4}}>Audiences</h1>
          <div style={{fontSize:13,color:'var(--ink-3)'}}>5 audiences · 3,515 unique contacts</div>
        </div>
        <button className="btn btn-primary" style={{padding:'8px 14px',fontSize:12}}>+ New audience</button>
      </div>

      <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(320px,1fr))',gap:14}}>
        {audiences.map(a => (
          <div key={a.n} className="card clickable" style={{padding:'22px 24px'}}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:18}}>
              <span style={{width:34,height:34,borderRadius:8,background:`${a.c}22`,border:`1px solid ${a.c}55`,display:'flex',alignItems:'center',justifyContent:'center',color:a.c,fontWeight:600,fontFamily:'var(--mono)',fontSize:13}}>{a.n[0]}</span>
              <button style={{color:'var(--ink-3)',fontSize:14}}>⋯</button>
            </div>
            <div style={{fontSize:15,fontWeight:500,letterSpacing:'-0.005em',marginBottom:14,lineHeight:1.3}}>{a.n}</div>
            <div style={{display:'flex',alignItems:'baseline',gap:8,marginBottom:6}}>
              <span style={{fontSize:28,fontWeight:500,letterSpacing:'-0.02em'}}>{a.size.toLocaleString()}</span>
              <span style={{fontSize:12,color:'var(--ink-3)'}}>contacts</span>
            </div>
            <div className="mono" style={{fontSize:10,color: a.growth.startsWith('+') ? 'var(--ok)' : 'var(--ink-3)',letterSpacing:'0.04em'}}>{a.growth.toUpperCase()}</div>
          </div>
        ))}
        <button style={{padding:'22px 24px',borderRadius:'var(--radius)',border:'1px dashed var(--line-2)',background:'transparent',color:'var(--ink-3)',fontSize:13,display:'flex',alignItems:'center',justifyContent:'center',gap:8}}>
          + Build segment
        </button>
      </div>
    </div>
  );
};

// ── DELIVERABILITY ───────────────────────────────────────────────

const Deliverability = () => (
  <div style={{padding:'28px 32px',maxWidth:1100}}>
    <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:4}}>Deliverability</h1>
    <div style={{fontSize:13,color:'var(--ink-3)',marginBottom:24}}>DNS configuration, reputation, and where your mail is actually landing.</div>

    {/* DNS */}
    <div className="card" style={{padding:'28px 32px',marginBottom:18}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',marginBottom:18}}>
        <div className="mono" style={{fontSize:10,color:'var(--accent)',letterSpacing:'0.06em'}}>● DNS · ALL VERIFIED</div>
        <button className="btn btn-ghost" style={{padding:'6px 10px',fontSize:11}}>Re-verify</button>
      </div>

      <div style={{display:'flex',flexDirection:'column',gap:10}}>
        {[
          ['SPF','TXT','solidatoms.com','v=spf1 include:_spf.resend.com -all','✓ Verified'],
          ['DKIM','CNAME','resend._domainkey.solidatoms.com','resend._domainkey.resend.com','✓ Verified'],
          ['DMARC','TXT','_dmarc.solidatoms.com','v=DMARC1; p=quarantine; rua=mailto:dmarc@…','✓ Verified'],
          ['Return-Path','MX','bounce.solidatoms.com','feedback-smtp.us-east-1.amazonses.com','✓ Verified'],
        ].map(([n,t,host,val,s],i) => (
          <div key={n} style={{display:'grid',gridTemplateColumns:'80px 80px 1fr 1fr 100px',gap:14,padding:'14px 16px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)',alignItems:'center'}}>
            <span style={{fontSize:13,fontWeight:500}}>{n}</span>
            <span className="mono" style={{fontSize:10,color:'var(--ink-3)',padding:'2px 6px',borderRadius:4,background:'rgba(255,255,255,0.04)',border:'1px solid var(--line)',letterSpacing:'0.04em',width:'fit-content'}}>{t}</span>
            <span className="mono" style={{fontSize:11,color:'var(--ink-2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{host}</span>
            <span className="mono" style={{fontSize:11,color:'var(--ink-3)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{val}</span>
            <span style={{fontSize:11,color:'var(--ok)'}}>{s}</span>
          </div>
        ))}
      </div>
    </div>

    {/* Reputation */}
    <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,marginBottom:18}}>
      <div className="card" style={{padding:'24px 28px'}}>
        <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:14}}>SENDER REPUTATION</div>
        <div style={{display:'flex',alignItems:'baseline',gap:8,marginBottom:14}}>
          <span style={{fontSize:42,fontWeight:500,letterSpacing:'-0.025em',color:'var(--accent)'}}>99</span>
          <span style={{fontSize:14,color:'var(--ink-3)'}}>/ 100</span>
        </div>
        <div style={{height:6,background:'var(--bg-3)',borderRadius:3,marginBottom:14}}>
          <div style={{width:'99%',height:'100%',background:'linear-gradient(90deg,#ff5a3a 0%,#ffb43a 30%,#7ee787 60%,#d4ff3a 100%)',borderRadius:3}}/>
        </div>
        <div style={{fontSize:12,color:'var(--ink-3)',lineHeight:1.5}}>Excellent. You're in the top 1% of senders by domain reputation.</div>
      </div>

      <div className="card" style={{padding:'24px 28px'}}>
        <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:14}}>INBOX PLACEMENT · 7 DAYS</div>
        {[
          ['Gmail','98%','#7ee787'],
          ['Apple Mail','99%','#7ee787'],
          ['Outlook 365','94%','#7ee787'],
          ['Yahoo','91%','#ffb43a'],
        ].map(([p,v,c]) => (
          <div key={p} style={{display:'grid',gridTemplateColumns:'80px 1fr 50px',gap:12,padding:'8px 0',alignItems:'center'}}>
            <span style={{fontSize:13,color:'var(--ink-2)'}}>{p}</span>
            <div style={{height:4,background:'var(--bg-3)',borderRadius:2}}>
              <div style={{width:v,height:'100%',background:c,borderRadius:2}}/>
            </div>
            <span className="mono" style={{fontSize:11,color:c,textAlign:'right',fontWeight:500}}>{v}</span>
          </div>
        ))}
      </div>
    </div>

    {/* Bounce types */}
    <div className="card" style={{padding:'24px 28px'}}>
      <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:14}}>BOUNCES & COMPLAINTS · 30 DAYS</div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:14}}>
        {[
          ['Hard bounces',18,'0.05%','#ff5a3a'],
          ['Soft bounces',7,'0.02%','#ffb43a'],
          ['Complaints',2,'0.01%','#a78bfa'],
          ['Suppressions',25,'auto-managed','#7c9bff'],
        ].map(([l,v,p,c]) => (
          <div key={l} style={{padding:'14px 16px',borderRadius:8,background:'var(--bg-3)',border:`1px solid ${c}33`}}>
            <div className="mono" style={{fontSize:9,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:8,textTransform:'uppercase'}}>{l}</div>
            <div style={{fontSize:22,fontWeight:500,letterSpacing:'-0.02em',marginBottom:4,color:c}}>{v}</div>
            <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{p}</div>
          </div>
        ))}
      </div>
    </div>
  </div>
);

// ── SETTINGS ─────────────────────────────────────────────────────

const EmailSettings = () => (
  <div style={{padding:'28px 32px',maxWidth:880}}>
    <h1 style={{fontSize:28,letterSpacing:'-0.025em',fontWeight:500,marginBottom:24}}>Settings & DNS</h1>

    <div style={{display:'flex',flexDirection:'column',gap:18}}>
      <div className="card" style={{padding:'24px 28px'}}>
        <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:14}}>SENDING DOMAINS</div>
        {[
          ['solidatoms.com','Primary','✓ Verified','12,283 sent / mo'],
          ['mail.solidatoms.com','Transactional','✓ Verified','2,431 sent / day'],
          ['news.solidatoms.com','Marketing','✓ Verified','3,214 subscribers'],
        ].map(([d,t,s,sent],i)=>(
          <div key={d} style={{display:'grid',gridTemplateColumns:'1.6fr 110px 1fr 1fr 36px',gap:14,padding:'14px 16px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)',alignItems:'center',marginTop: i===0 ? 0 : 10}}>
            <span className="mono" style={{fontSize:13,color:'var(--ink)'}}>{d}</span>
            <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em',textTransform:'uppercase'}}>{t}</span>
            <span style={{fontSize:12,color:'var(--ok)'}}>{s}</span>
            <span className="mono" style={{fontSize:11,color:'var(--ink-3)',letterSpacing:'0.04em'}}>{sent}</span>
            <span style={{color:'var(--ink-3)',justifySelf:'end'}}>⋯</span>
          </div>
        ))}
        <button className="btn btn-ghost" style={{padding:'8px 12px',fontSize:12,marginTop:12}}>+ Add domain</button>
      </div>

      <div className="card" style={{padding:'24px 28px'}}>
        <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:14}}>WEBHOOK ENDPOINTS</div>
        {[
          ['https://api.solidatoms.com/webhooks/email','all events','99.8% delivered'],
          ['https://hooks.slack.com/services/T0…','bounce, complaint','100% delivered'],
        ].map(([u,ev,d],i)=>(
          <div key={u} style={{display:'grid',gridTemplateColumns:'1.5fr 1fr 1fr',gap:14,padding:'14px 16px',borderRadius:8,background:'var(--bg-3)',border:'1px solid var(--line)',marginTop: i===0 ? 0 : 10}}>
            <span className="mono" style={{fontSize:11,color:'var(--ink-2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{u}</span>
            <span className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.04em',textTransform:'uppercase'}}>{ev}</span>
            <span style={{fontSize:12,color:'var(--ok)'}}>{d}</span>
          </div>
        ))}
      </div>

      <div className="card" style={{padding:'24px 28px'}}>
        <div className="mono" style={{fontSize:10,color:'var(--ink-3)',letterSpacing:'0.06em',marginBottom:14}}>SUPPRESSION LIST</div>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
          <div>
            <div style={{fontSize:14,fontWeight:500,marginBottom:4}}>1,247 addresses suppressed</div>
            <div style={{fontSize:12,color:'var(--ink-3)'}}>Unsubscribes · 1,194 · Bounces · 38 · Complaints · 15</div>
          </div>
          <button className="btn btn-ghost" style={{padding:'7px 11px',fontSize:12}}>Manage list</button>
        </div>
      </div>
    </div>
  </div>
);

window.EmailStudio = EmailStudio;
