// Channels screen — paid media connection + unified performance

const ChChannelCard = ({ brand, color, logo, accountId, tokenInfo, lastSync, stats, connected,
                         onSync = () => {}, onDisconnect = () => {} }) => {
  if (!connected) return (
    <div className="card" style={{border: '2px dashed var(--border-strong)', background: 'var(--bg-1)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: 240, gap: 10}}>
      <div style={{width: 40, height: 40, borderRadius: 10, background: 'var(--bg-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-4)'}}><Icon name="plus" size={20}/></div>
      <div style={{fontSize: 14, color: 'var(--text-3)', fontWeight: 500}}>Connect a Channel</div>
      <div style={{fontSize: 11, color: 'var(--text-4)', textAlign: 'center'}}>TikTok Ads, LinkedIn Ads, Pinterest —<br/>coming soon</div>
      <button className="btn ghost" style={{color: 'var(--accent)', fontSize: 11, marginTop: 6}}>Request Integration →</button>
    </div>
  );
  return (
    <div className="card" style={{padding: 0, overflow: 'hidden'}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '12px 16px', borderBottom: '1px solid var(--border)', background: 'var(--bg-3)'}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
          <div style={{width: 28, height: 28, borderRadius: 8, background: color, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 14}}>{logo}</div>
          <div style={{fontSize: 14, fontWeight: 600}}>{brand}</div>
        </div>
        <span className="badge green"><span className="dot" style={{width: 6, height: 6}}></span>Connected</span>
      </div>
      <div style={{padding: 16, display: 'flex', flexDirection: 'column', gap: 10}}>
        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 12}}>
          <span style={{color: 'var(--text-3)'}}>Account ID</span>
          <span className="mono" style={{color: '#c4b5fd'}}>{accountId}</span>
        </div>
        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 12}}>
          <span style={{color: 'var(--text-3)'}}>Token</span>
          <span className="mono" style={{color: tokenInfo.expiring ? 'var(--amber)' : 'var(--text-2)', fontSize: 11}}>{tokenInfo.value}</span>
        </div>
        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 12}}>
          <span style={{color: 'var(--text-3)'}}>Last synced</span>
          <span style={{color: 'var(--text-2)'}}>{lastSync}</span>
        </div>
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, paddingTop: 10, borderTop: '1px solid var(--border)', marginTop: 4}}>
          {stats.map(s => (
            <div key={s.label} style={{textAlign: 'center'}}>
              <div style={{fontSize: 16, fontWeight: 600, color: 'var(--text-1)'}}>{s.value}</div>
              <div style={{fontSize: 10, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.05em'}}>{s.label}</div>
            </div>
          ))}
        </div>
      </div>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px 16px', borderTop: '1px solid var(--border)', background: 'var(--bg-1)'}}>
        <button className="btn ghost" style={{color: 'var(--emerald)', fontSize: 11, padding: '4px 8px'}} onClick={onSync}><Icon name="refresh" size={11}/>Sync Now</button>
        <button className="btn ghost" style={{color: 'var(--rose)', fontSize: 11, padding: '4px 8px'}} onClick={onDisconnect}>Disconnect</button>
      </div>
    </div>
  );
};

const ChKpi = ({ label, value, delta, dir, sparkSeed, color }) => (
  <div className="metric">
    <div className="metric-label">{label}</div>
    <div className="metric-value">{value}</div>
    {delta && (
      <div className={`metric-delta ${dir}`}>
        <Icon name={dir === 'up' ? 'up' : 'down'} size={10} />
        <span>{delta}</span>
        <span style={{color: 'var(--text-4)', marginLeft: 4}}>vs prior</span>
      </div>
    )}
    <Spark data={MOCK.spark(sparkSeed)} color={color || 'var(--accent)'} w={130} h={30} />
  </div>
);

const ChDualChart = () => {
  const w = 640, h = 220, pad = 28;
  const n = 30;
  const spend = MOCK.spark(21).map(v => v * 0.8 + 0.4);
  const conv = MOCK.spark(22).map(v => v * 0.9 + 0.3);
  const maxS = Math.max(...spend), maxC = Math.max(...conv);
  const X = i => pad + (i / (n - 1)) * (w - pad * 2);
  const Ys = v => h - pad - (v / maxS) * (h - pad * 2);
  const Yc = v => h - pad - (v / maxC) * (h - pad * 2);
  const areaD = 'M' + X(0) + ' ' + Ys(spend[0]) + spend.slice(1).map((v, i) => ' L' + X(i + 1) + ' ' + Ys(v)).join('') + ` L ${X(n-1)} ${h-pad} L ${X(0)} ${h-pad} Z`;
  const lineD = 'M' + X(0) + ' ' + Yc(conv[0]) + conv.slice(1).map((v, i) => ' L' + X(i + 1) + ' ' + Yc(v)).join('');
  return (
    <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      {[0, 0.25, 0.5, 0.75, 1].map(t => <line key={t} x1={pad} x2={w-pad} y1={pad + t*(h-pad*2)} y2={pad + t*(h-pad*2)} stroke="#232A3B" strokeDasharray="2 3" />)}
      <path d={areaD} fill="var(--accent)" fillOpacity="0.2"/>
      <path d={lineD} stroke="var(--cyan)" strokeWidth="1.5" fill="none"/>
      {conv.map((v, i) => <circle key={i} cx={X(i)} cy={Yc(v)} r="2" fill="var(--cyan)"/>)}
      <line x1={pad} x2={w-pad} y1={pad + 0.35*(h-pad*2)} y2={pad + 0.35*(h-pad*2)} stroke="var(--amber)" strokeDasharray="4 3" strokeWidth="1" opacity="0.6"/>
    </svg>
  );
};

const ChDonut = () => {
  const cx = 90, cy = 90, r = 60, sw = 18;
  const segs = [
    { pct: 62, color: 'var(--accent)', label: 'Meta' },
    { pct: 38, color: 'var(--cyan)', label: 'Google' },
  ];
  let off = 0;
  const circ = 2 * Math.PI * r;
  return (
    <svg width="180" height="180" viewBox="0 0 180 180">
      {segs.map(s => {
        const len = (s.pct / 100) * circ;
        const el = <circle key={s.label} cx={cx} cy={cy} r={r} fill="none" stroke={s.color} strokeWidth={sw}
          strokeDasharray={`${len} ${circ - len}`} strokeDashoffset={-off} transform={`rotate(-90 ${cx} ${cy})`}/>;
        off += len;
        return el;
      })}
      <text x={cx} y={cy - 4} textAnchor="middle" fill="var(--text-3)" fontSize="10" fontFamily="var(--mono)">CONVERSIONS</text>
      <text x={cx} y={cy + 16} textAnchor="middle" fill="var(--text-1)" fontSize="22" fontWeight="600">1,247</text>
    </svg>
  );
};

// ── Multi-platform, multi-sub-tab table ──────────────────────────────────────
const ChCampaignsTable = ({ platform = 'meta', sub = 'campaigns', statusFilter = 'all' }) => {
  const sf = statusFilter;
  const ctrC = v => v >= 2 ? 'var(--emerald)' : v >= 1 ? 'var(--amber)' : 'var(--rose)';
  const roasC = v => v >= 3 ? '#c4b5fd' : v >= 1 ? 'var(--amber)' : 'var(--rose)';

  const META_CAMPAIGNS = [
    ['Q2 Prospecting — US',       'active', 'CONVERSIONS', 8420, 892000, 18400, 2.06, 412, 20.44, 4.2],
    ['Spring Retarget (meta)',    'active', 'CONVERSIONS', 5124, 412000, 11240, 2.73, 318, 16.11, 5.8],
    ['Lookalike 1% · Cart',       'active', 'CONVERSIONS', 4218, 389000,  7420, 1.91, 214, 19.71, 3.3],
    ['Brand Awareness — APAC',    'paused', 'REACH',       2980,1240000,  4210, 0.34,  18,165.55, 0.4],
    ['Holiday creative test',     'active', 'TRAFFIC',     1890, 184000,  5120, 2.78,  94, 20.11, 2.1],
    ['Cold audiences · Mobile',   'active', 'CONVERSIONS', 1215,  98000,  1840, 1.88,  52, 23.37, 2.8],
  ];
  const META_ADSETS = [
    ['US Prospecting · 25-44',      'Q2 Prospecting',       'active', 3200, 412000, 2.06, 182, 22.10],
    ['Retarget · Cart Abandoners',  'Spring Retarget',      'active', 1800, 298000, 1.84, 124, 14.52],
    ['Lookalike 1% · Purchasers',   'Q2 Prospecting',       'active', 2140, 184000, 2.73, 106, 20.19],
    ['Brand · 18-35 APAC',          'Brand Awareness APAC', 'paused',  980,1240000, 0.34,  18, 54.44],
    ['Cold · Mobile Shoppers',      'Cold · Mobile',        'active',  640,  98000, 1.88,  52, 12.31],
  ];
  const META_ADS = [
    ['Video 30s · Product Demo',   'US Prospecting · 25-44',     'active', 'VIDEO',      2840, 1.80, 98, 28.98],
    ['Carousel · 5 Products',      'Retarget · Cart Abandoners', 'active', 'CAROUSEL',   1920, 2.40,124, 15.48],
    ['Single Image · Price Promo', 'Lookalike 1%',               'active', 'IMAGE',      1102, 1.56, 64, 17.22],
    ['Story · Brand Awareness',    'Brand · 18-35 APAC',         'paused', 'STORY',       402, 0.28,  8, 50.25],
    ['Collection · Summer',        'Cold · Mobile',              'active', 'COLLECTION',  890, 1.91, 48, 18.54],
  ];
  const META_AUDIENCES = [
    ['Lookalike 1% · Purchasers',       '2.1M',  'Lookalike', 'active', 412, 4.2],
    ['Custom · Website Visitors 30d',   '48K',   'Custom',    'active', 318, 5.8],
    ['Lookalike 2% · Engagers',         '4.8M',  'Lookalike', 'active', 214, 3.3],
    ['Saved · Brand Interest 25-44',    '12.4M', 'Saved',     'active',  94, 2.1],
    ['Custom · Cart Abandoners 14d',    '8.2K',  'Custom',    'paused',  52, 2.8],
  ];
  const GOOGLE_CAMPAIGNS = [
    ['Brand Search — US',           'active', 'SEARCH',   3124, 182000, 8420, 4.62, 284, 11.00, 6.2],
    ['Non-brand · Product Keywords','active', 'SEARCH',   2840,  98000, 4210, 4.30, 198, 14.34, 4.8],
    ['Shopping · All Products',     'active', 'SHOPPING', 2012, 412000, 5120, 1.24, 124, 16.23, 3.6],
    ['Performance Max · Summer',    'active', 'PMAX',     1840, 892000, 6840, 0.77,  84, 21.90, 3.1],
    ['RLSA · Past Purchasers',      'paused', 'SEARCH',    820,  28000, 1240, 4.43,  48, 17.08, 2.9],
    ['YouTube · Prospecting',       'active', 'VIDEO',     420,1240000, 2840, 0.23,  18, 23.33, 1.8],
  ];
  const GOOGLE_KEYWORDS = [
    ['marketing analytics software',  'Exact',  8, 412, 2.84, 48, 11.65, '$16.44'],
    ['customer journey tracking',     'Phrase', 7, 284, 2.40, 38, 13.38, '$17.74'],
    ['attribution software',          'Exact',  9, 198, 3.12, 32, 16.16, '$18.75'],
    ['ad performance dashboard',      'Broad',  6, 892, 1.84, 68,  7.62, '$24.12'],
    ['marketing os platform',         'Exact',  8, 124, 4.03, 22, 17.74, '$16.36'],
    ['multi-touch attribution',       'Phrase', 7, 312, 2.56, 40, 12.82, '$19.50'],
  ];
  const GOOGLE_SEARCH = [
    ['best marketing analytics tool 2025',   'Phrase', 284, 8420, 38, '$9.42'],
    ['customer journey analytics platform',  'Exact',  198, 4210, 32,'$14.38'],
    ['ad attribution tracking software',     'Broad',  124, 5120, 18,'$19.44'],
    ['multi-channel marketing analytics',    'Phrase', 312, 9840, 44,'$11.36'],
    ['marketing automation with AI',         'Broad',  892,28400, 64,'$13.94'],
    ['conversion tracking dashboard',        'Exact',  412,12000, 52, '$8.27'],
  ];
  const GOOGLE_EXTENSIONS = [
    ['Sitelink',          'Free Trial →',                              1240, 3.84, 'active'],
    ['Sitelink',          'Pricing →',                                  892, 2.76, 'active'],
    ['Callout',           'AI-Powered Insights',                          0, 0.00, 'active'],
    ['Structured Snippet','Features: Journey Map, Anomaly, AI Insights',   0, 0.00, 'active'],
    ['Image',             'Dashboard Hero',                              412, 1.28, 'active'],
    ['Lead Form',         'Book a Demo',                                 284, 0.88, 'paused'],
  ];

  const key = `${platform}:${sub}`;

  if (sub === 'campaigns') {
    const rows = (platform === 'meta' ? META_CAMPAIGNS : GOOGLE_CAMPAIGNS).filter(r => sf === 'all' || r[1] === sf);
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr>
            <th>Campaign</th><th>Status</th><th>Objective</th>
            <th style={{textAlign:'right'}}>Spend</th><th style={{textAlign:'right'}}>Impr.</th>
            <th style={{textAlign:'right'}}>Clicks</th><th style={{textAlign:'right'}}>CTR</th>
            <th style={{textAlign:'right'}}>Conv.</th><th style={{textAlign:'right'}}>CPA</th>
            <th style={{textAlign:'right'}}>ROAS</th><th></th>
          </tr></thead>
          <tbody>{rows.map((r,i) => (
            <tr key={i}>
              <td style={{color:'var(--text-1)',fontWeight:500}}>{r[0]}</td>
              <td><span className={`badge ${r[1]==='active'?'green':r[1]==='paused'?'amber':'plain'}`}>{r[1]}</span></td>
              <td><span className="badge cyan">{r[2]}</span></td>
              <td className="mono" style={{textAlign:'right'}}>${r[3].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right'}}>{(r[4]/1000).toFixed(0)}k</td>
              <td className="mono" style={{textAlign:'right'}}>{r[5].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right',color:ctrC(r[6])}}>{r[6].toFixed(2)}%</td>
              <td className="mono" style={{textAlign:'right',color:'var(--emerald)',fontWeight:600}}>{r[7]}</td>
              <td className="mono" style={{textAlign:'right'}}>${r[8].toFixed(2)}</td>
              <td className="mono" style={{textAlign:'right',color:roasC(r[9]),fontWeight:600}}>{r[9].toFixed(1)}x</td>
              <td style={{textAlign:'right',color:'var(--text-4)'}}>•••</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  if (key === 'meta:adsets') {
    const rows = META_ADSETS.filter(r => sf === 'all' || r[2] === sf);
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr><th>Ad Set</th><th>Campaign</th><th>Status</th><th style={{textAlign:'right'}}>Budget/d</th><th style={{textAlign:'right'}}>Reach</th><th style={{textAlign:'right'}}>CTR</th><th style={{textAlign:'right'}}>Conv.</th><th style={{textAlign:'right'}}>CPA</th></tr></thead>
          <tbody>{rows.map((r,i) => (
            <tr key={i}>
              <td style={{color:'var(--text-1)',fontWeight:500}}>{r[0]}</td>
              <td style={{color:'var(--text-3)',fontSize:11}}>{r[1]}</td>
              <td><span className={`badge ${r[2]==='active'?'green':'amber'}`}>{r[2]}</span></td>
              <td className="mono" style={{textAlign:'right'}}>${r[3].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right'}}>{(r[4]/1000).toFixed(0)}k</td>
              <td className="mono" style={{textAlign:'right',color:ctrC(r[5])}}>{r[5].toFixed(2)}%</td>
              <td className="mono" style={{textAlign:'right',color:'var(--emerald)',fontWeight:600}}>{r[6]}</td>
              <td className="mono" style={{textAlign:'right'}}>${r[7].toFixed(2)}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  if (key === 'meta:ads') {
    const rows = META_ADS.filter(r => sf === 'all' || r[2] === sf);
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr><th>Ad Creative</th><th>Ad Set</th><th>Status</th><th>Format</th><th style={{textAlign:'right'}}>Clicks</th><th style={{textAlign:'right'}}>CTR</th><th style={{textAlign:'right'}}>Conv.</th><th style={{textAlign:'right'}}>CPA</th></tr></thead>
          <tbody>{rows.map((r,i) => (
            <tr key={i}>
              <td style={{color:'var(--text-1)',fontWeight:500}}>{r[0]}</td>
              <td style={{color:'var(--text-3)',fontSize:11}}>{r[1]}</td>
              <td><span className={`badge ${r[2]==='active'?'green':'amber'}`}>{r[2]}</span></td>
              <td><span className="badge plain" style={{fontSize:10}}>{r[3]}</span></td>
              <td className="mono" style={{textAlign:'right'}}>{r[4].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right',color:ctrC(r[5])}}>{r[5].toFixed(2)}%</td>
              <td className="mono" style={{textAlign:'right',color:'var(--emerald)',fontWeight:600}}>{r[6]}</td>
              <td className="mono" style={{textAlign:'right'}}>${r[7].toFixed(2)}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  if (key === 'meta:audiences') {
    const rows = META_AUDIENCES.filter(r => sf === 'all' || r[3] === sf);
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr><th>Audience Name</th><th>Size</th><th>Type</th><th>Status</th><th style={{textAlign:'right'}}>Conv.</th><th style={{textAlign:'right'}}>ROAS</th></tr></thead>
          <tbody>{rows.map((r,i) => (
            <tr key={i}>
              <td style={{color:'var(--text-1)',fontWeight:500}}>{r[0]}</td>
              <td className="mono" style={{color:'var(--text-2)'}}>{r[1]}</td>
              <td><span className="badge plain" style={{fontSize:10}}>{r[2]}</span></td>
              <td><span className={`badge ${r[3]==='active'?'green':'amber'}`}>{r[3]}</span></td>
              <td className="mono" style={{textAlign:'right',color:'var(--emerald)',fontWeight:600}}>{r[4]}</td>
              <td className="mono" style={{textAlign:'right',color:'#c4b5fd',fontWeight:600}}>{r[5].toFixed(1)}x</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  if (key === 'google:keywords') {
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr><th>Keyword</th><th>Match</th><th style={{textAlign:'right'}}>QS</th><th style={{textAlign:'right'}}>Clicks</th><th style={{textAlign:'right'}}>CPC</th><th style={{textAlign:'right'}}>Conv.</th><th style={{textAlign:'right'}}>Conv. Rate</th><th style={{textAlign:'right'}}>CPA</th></tr></thead>
          <tbody>{GOOGLE_KEYWORDS.map((r,i) => (
            <tr key={i}>
              <td style={{color:'var(--text-1)',fontWeight:500}}>{r[0]}</td>
              <td><span className="badge plain" style={{fontSize:10}}>{r[1]}</span></td>
              <td className="mono" style={{textAlign:'right',color:r[2]>=8?'var(--emerald)':r[2]>=6?'var(--amber)':'var(--rose)',fontWeight:600}}>{r[2]}/10</td>
              <td className="mono" style={{textAlign:'right'}}>{r[3].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right',color:'var(--text-2)'}}>${r[4].toFixed(2)}</td>
              <td className="mono" style={{textAlign:'right',color:'var(--emerald)',fontWeight:600}}>{r[5]}</td>
              <td className="mono" style={{textAlign:'right'}}>{r[6].toFixed(2)}%</td>
              <td className="mono" style={{textAlign:'right'}}>{r[7]}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  if (key === 'google:search') {
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr><th>Search Term</th><th>Match Type</th><th style={{textAlign:'right'}}>Clicks</th><th style={{textAlign:'right'}}>Impr.</th><th style={{textAlign:'right'}}>Conv.</th><th style={{textAlign:'right'}}>CPA</th></tr></thead>
          <tbody>{GOOGLE_SEARCH.map((r,i) => (
            <tr key={i}>
              <td style={{color:'var(--text-1)',fontWeight:500}}>{r[0]}</td>
              <td><span className="badge plain" style={{fontSize:10}}>{r[1]}</span></td>
              <td className="mono" style={{textAlign:'right'}}>{r[2].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right'}}>{r[3].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right',color:'var(--emerald)',fontWeight:600}}>{r[4]}</td>
              <td className="mono" style={{textAlign:'right'}}>{r[5]}</td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  if (key === 'google:extensions') {
    const rows = GOOGLE_EXTENSIONS.filter(r => sf === 'all' || r[4] === sf);
    return (
      <div style={{overflow:'auto'}}>
        <table className="data-table">
          <thead><tr><th>Type</th><th>Content</th><th style={{textAlign:'right'}}>Clicks</th><th style={{textAlign:'right'}}>CTR</th><th>Status</th></tr></thead>
          <tbody>{rows.map((r,i) => (
            <tr key={i}>
              <td><span className="badge cyan" style={{fontSize:10}}>{r[0]}</span></td>
              <td style={{color:'var(--text-1)'}}>{r[1]}</td>
              <td className="mono" style={{textAlign:'right'}}>{r[2].toLocaleString()}</td>
              <td className="mono" style={{textAlign:'right',color:ctrC(r[3])}}>{r[3].toFixed(2)}%</td>
              <td><span className={`badge ${r[4]==='active'?'green':'amber'}`}>{r[4]}</span></td>
            </tr>
          ))}</tbody>
        </table>
      </div>
    );
  }

  return <div style={{padding:20,color:'var(--text-3)',textAlign:'center',fontSize:12}}>No data available for this view.</div>;
};

const ChannelsScreen = () => {
  const [tab, setTab] = React.useState('meta');
  const [sub, setSub] = React.useState('campaigns');
  const [dr, setDr] = React.useState('30d');
  const [syncing, setSyncing] = React.useState(false);
  const [channelStatus, setChannelStatus] = React.useState(null);
  const [lastSync, setLastSync] = React.useState('2 hours ago');
  const [syncError, setSyncError] = React.useState(null);
  const [performanceData, setPerformanceData] = React.useState(null);
  const [aiDismissed, setAiDismissed] = React.useState(false);
  const [statusFilter, setStatusFilter] = React.useState('all');
  const [showAddModal, setShowAddModal] = React.useState(false);
  const [vsPrior, setVsPrior] = React.useState(true);
  const [requestingChannel, setRequestingChannel] = React.useState(null);
  const [requestSent, setRequestSent] = React.useState(false);

  React.useEffect(() => {
    arFetch('/v1/channels/status')
      .then(d => { if (d && typeof d === 'object') setChannelStatus(d); })
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    const days = dr === '7d' ? 7 : dr === '90d' ? 90 : 30;
    const end = new Date();
    const start = new Date(end.getTime() - days * 86400000);
    const fmt = d => d.toISOString().slice(0, 10);
    arFetch('/v1/channels/performance?start_date=' + fmt(start) + '&end_date=' + fmt(end))
      .then(d => { if (Array.isArray(d) && d.length) setPerformanceData(d); })
      .catch(() => {});
  }, [dr]);

  const handleSyncAll = () => {
    setSyncing(true);
    setSyncError(null);
    arFetch('/v1/channels/sync', { method: 'POST', body: JSON.stringify({}) })
      .then(() => arFetch('/v1/channels/status'))
      // FIX: only set lastSync after both fetches succeed
      .then(d => { if (d) setChannelStatus(d); setLastSync('just now'); })
      .catch(err => {
        console.error('Channel sync failed:', err);
        setSyncError('Channel sync failed — API server offline. Showing cached data. (Pending: backend /v1/channels/sync endpoint)');
      })
      .finally(() => setSyncing(false));
  };

  // Switch platform tab and reset sub + filter to defaults
  const switchTab = (t) => { setTab(t); setSub('campaigns'); setStatusFilter('all'); };

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 20}}>

      {/* Header */}
      <div style={{display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16}}>
        <div>
          <div style={{fontSize: 11, color: 'var(--text-4)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6}}>Platform / Channels</div>
          <div style={{fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em'}}>Channels</div>
          <div style={{fontSize: 13, color: 'var(--text-3)', marginTop: 2}}>Manage paid media connections and AI-attributed performance</div>
        </div>
        <div style={{display: 'flex', gap: 8}}>
          <button className="btn" style={{color: 'var(--emerald)', borderColor: 'rgba(16,185,129,0.3)'}} onClick={handleSyncAll} disabled={syncing}><Icon name="refresh" size={12}/>{syncing ? 'Syncing…' : 'Sync All'}</button>
          <button className="btn primary" onClick={() => setShowAddModal(true)}><Icon name="plus" size={12}/>Add Channel</button>
        </div>
      </div>

      {syncError && (
        <div style={{padding: '10px 14px', background: 'rgba(244,63,94,0.1)', border: '1px solid rgba(244,63,94,0.3)', borderRadius: 8, fontSize: 12, color: 'var(--rose)', display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
          <span>⚠ {syncError}</span>
          <span style={{cursor: 'pointer', color: 'var(--text-4)'}} onClick={() => setSyncError(null)}>✕</span>
        </div>
      )}

      {/* Status strip */}
      <div style={{display: 'flex', alignItems: 'center', gap: 16, padding: '10px 16px', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 10, fontSize: 12}}>
        <span style={{color: 'var(--text-3)'}}>Last sync: {channelStatus?.last_sync || lastSync}</span>
        <div style={{flex: 1, display: 'flex', justifyContent: 'center', gap: 8}}>
          <span className="badge green"><span className="dot" style={{width: 6, height: 6}}></span>Meta Ads</span>
          <span className="badge green"><span className="dot" style={{width: 6, height: 6}}></span>Google Ads</span>
          <span className="badge plain"><span className="dot" style={{width: 6, height: 6, background: 'var(--text-4)'}}></span>TikTok Ads</span>
        </div>
        <span style={{color: 'var(--text-3)'}}>Next auto-sync: Tonight 02:00 UTC</span>
      </div>

      {/* Connection cards */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14}}>
        <ChChannelCard connected brand="Meta Ads" color="#1877F2" logo="f"
          accountId="act_123456789"
          tokenInfo={{value: '●●●● expires Jun 12', expiring: false}}
          lastSync="2h ago"
          stats={[{label: 'Campaigns', value: 12}, {label: 'Ad Sets', value: 47}, {label: 'Ads', value: 183}]}
          onSync={handleSyncAll}
          onDisconnect={() => window.alert('Meta Ads disconnect is not yet available. Contact support to revoke access.')} />
        <ChChannelCard connected brand="Google Ads" color="#4285F4" logo="G"
          accountId="123-456-7890"
          tokenInfo={{value: '●●●●●●●●', expiring: false}}
          lastSync="4h ago"
          stats={[{label: 'Campaigns', value: 8}, {label: 'Groups', value: 34}, {label: 'Keywords', value: 892}]}
          onSync={handleSyncAll}
          onDisconnect={() => window.alert('Google Ads disconnect is not yet available. Contact support to revoke access.')} />
        <ChChannelCard connected={false} />
      </div>

      {/* Performance overview header */}
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10}}>
        <div style={{fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em'}}>Performance Overview</div>
        <div style={{display: 'flex', gap: 10, alignItems: 'center'}}>
          <div className="seg">
            {['7d','30d','90d','Custom'].map(d => <button key={d} className={dr===d?'active':''} onClick={() => setDr(d)}>{d}</button>)}
          </div>
          <span style={{fontSize: 11, color: 'var(--text-3)'}}>vs prior period</span>
          <div className={`toggle ${vsPrior ? 'on' : ''}`} onClick={() => setVsPrior(v => !v)} style={{cursor: 'pointer'}}/>
        </div>
      </div>

      {/* KPI row */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 12}}>
        <ChKpi label="Total Spend" value="$24,847" delta={vsPrior ? "2.1%" : ""} dir="down" sparkSeed={11} color="var(--text-3)"/>
        <ChKpi label="Impressions" value="4.2M" delta={vsPrior ? "8.7%" : ""} dir="up" sparkSeed={12} color="var(--cyan)"/>
        <ChKpi label="Clicks" value="87,432" delta={vsPrior ? "5.3%" : ""} dir="up" sparkSeed={13} color="var(--cyan)"/>
        <ChKpi label="Avg CTR" value="2.08%" delta={vsPrior ? "0.3pp" : ""} dir="up" sparkSeed={14} color="var(--cyan)"/>
        <ChKpi label="Conversions" value="1,247" delta={vsPrior ? "18.2%" : ""} dir="up" sparkSeed={15} color="var(--emerald)"/>
        <ChKpi label="Blended ROAS" value="3.8x" delta={vsPrior ? "0.4x" : ""} dir="up" sparkSeed={16} color="var(--accent)"/>
      </div>

      {/* AI Insights callout */}
      {!aiDismissed && (
        <AICallout>
          <b>Meta Ads contributed to 62% of conversions</b> via multi-touch attribution — however, <b>Google Search drove 3.1x higher-intent actors</b> into your journey graph (avg 2.3 touchpoints before conversion). Consider reallocating 15% of Meta budget to Google Search.
          <div style={{marginTop: 10, display: 'flex', gap: 8}}>
            <button className="btn" style={{background: 'var(--cyan)', color: '#001', borderColor: 'var(--cyan)', fontSize: 11}}
              onClick={() => { if (window.AR_NAVIGATE) window.AR_NAVIGATE('decisions'); }}>Create Budget Decision →</button>
            <button className="btn ghost" style={{fontSize: 11}} onClick={() => setAiDismissed(true)}>Dismiss</button>
          </div>
        </AICallout>
      )}

      {/* Charts */}
      <div style={{display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 14}}>
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">Spend vs Conversions</div>
              <div className="card-sub">Last {dr === '7d' ? 7 : dr === '90d' ? 90 : 30} days · daily</div>
            </div>
            <div style={{display: 'flex', gap: 14, alignItems: 'center', fontSize: 11, color: 'var(--text-3)'}}>
              <span><span style={{display:'inline-block',width:8,height:8,background:'var(--accent)',borderRadius:2,marginRight:6}}></span>Spend</span>
              <span><span style={{display:'inline-block',width:8,height:8,background:'var(--cyan)',borderRadius:'50%',marginRight:6}}></span>Conv.</span>
              <span><span style={{display:'inline-block',width:12,height:1,background:'var(--amber)',marginRight:6,verticalAlign:'middle'}}></span>ROAS target</span>
            </div>
          </div>
          <div style={{display: 'flex', gap: 6, marginBottom: 10}}>
            {['All','Meta Ads','Google Ads'].map(f => (
              <button key={f} className={`filter-chip ${f===tab||(f==='All'&&tab==='all')?'active':''}`}
                onClick={() => f === 'All' ? switchTab('all') : switchTab(f === 'Meta Ads' ? 'meta' : 'google')}>
                {f}
              </button>
            ))}
          </div>
          <ChDualChart />
        </div>
        <div className="card">
          <div className="card-header">
            <div className="card-title">Channel Mix</div>
            <div className="card-sub">Last 30 days</div>
          </div>
          <div style={{display: 'flex', alignItems: 'center', justifyContent: 'center'}}><ChDonut /></div>
          <div style={{marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10}}>
            <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 12}}>
              <span style={{display:'flex',alignItems:'center',gap:6}}><span style={{width:8,height:8,borderRadius:2,background:'var(--accent)'}}></span>Meta Ads</span>
              <span className="mono" style={{color: 'var(--text-2)'}}>62% · 773 · 3.9x</span>
            </div>
            <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 12}}>
              <span style={{display:'flex',alignItems:'center',gap:6}}><span style={{width:8,height:8,borderRadius:2,background:'var(--cyan)'}}></span>Google Ads</span>
              <span className="mono" style={{color: 'var(--text-2)'}}>38% · 474 · 3.6x</span>
            </div>
          </div>
          <div style={{marginTop: 14, paddingTop: 10, borderTop: '1px dashed var(--border)', fontSize: 10, color: 'var(--text-4)'}}>Based on last-touch + AstraReach multi-touch model</div>
        </div>
      </div>

      {/* Deep dive tabs */}
      <div className="card" style={{padding: 0}}>
        <div style={{display: 'flex', borderBottom: '1px solid var(--border)', padding: '0 16px'}}>
          {['meta','google'].map(t => (
            <button key={t} onClick={() => switchTab(t)} style={{padding: '14px 16px', fontSize: 13, fontWeight: 500, color: tab===t?'var(--text-1)':'var(--text-3)', borderBottom: tab===t?'2px solid var(--accent)':'2px solid transparent', marginBottom: -1}}>
              {t === 'meta' ? 'Meta Ads' : 'Google Ads'}
            </button>
          ))}
        </div>
        <div style={{padding: 16}}>
          <div style={{display: 'flex', gap: 6, marginBottom: 14}}>
            {(tab==='meta' ? ['campaigns','adsets','ads','audiences'] : ['campaigns','keywords','search','extensions']).map(s => (
              <button key={s} onClick={() => { setSub(s); setStatusFilter('all'); }} className={`filter-chip ${sub===s?'active':''}`}>{s}</button>
            ))}
          </div>
          <div style={{display: 'flex', gap: 10, marginBottom: 12, alignItems: 'center'}}>
            <div style={{flex: 1, display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8, maxWidth: 320}}>
              <Icon name="search" size={12} style={{color: 'var(--text-3)'}}/>
              <input placeholder={`Search ${sub}…`} style={{flex: 1, background: 'transparent', border: 'none', color: 'var(--text-1)', fontSize: 12, outline: 'none'}}/>
            </div>
            <div style={{display: 'flex', gap: 6}}>
              {['all','active','paused'].map(f => (
                <button key={f} className={`filter-chip ${statusFilter===f?'active':''}`} onClick={() => setStatusFilter(f)} style={{textTransform:'capitalize'}}>{f}</button>
              ))}
            </div>
          </div>
          <ChCampaignsTable platform={tab} sub={sub} statusFilter={statusFilter} />
        </div>
      </div>

      {/* Add Channel Modal */}
      {showAddModal && (
        <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,0.65)',zIndex:1000,display:'flex',alignItems:'center',justifyContent:'center'}} onClick={() => { setShowAddModal(false); setRequestingChannel(null); setRequestSent(false); }}>
          <div style={{background:'var(--bg-0)',border:'1px solid var(--border)',borderRadius:12,padding:24,width:440,maxWidth:'90vw'}} onClick={e => e.stopPropagation()}>
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:16}}>
              <div style={{fontSize:18,fontWeight:700}}>Add Channel</div>
              <button className="btn ghost" style={{fontSize:11}} onClick={() => { setShowAddModal(false); setRequestingChannel(null); setRequestSent(false); }}>✕</button>
            </div>

            {requestSent ? (
              <div style={{textAlign:'center',padding:'24px 0'}}>
                <div style={{fontSize:36,marginBottom:12}}>✅</div>
                <div style={{fontWeight:600,fontSize:15,marginBottom:8}}>Request received!</div>
                <div style={{fontSize:13,color:'var(--text-3)',marginBottom:20}}>We'll contact you within 2 business days about <strong>{requestingChannel}</strong> integration.</div>
                <button className="btn primary" onClick={() => { setShowAddModal(false); setRequestingChannel(null); setRequestSent(false); }}>Close</button>
              </div>
            ) : requestingChannel ? (
              <div>
                <div style={{fontSize:13,color:'var(--text-3)',marginBottom:16}}>Request early access to <strong>{requestingChannel}</strong> integration. We'll configure your OAuth credentials and notify you when it's ready.</div>
                <div style={{display:'flex',flexDirection:'column',gap:12}}>
                  <div>
                    <label style={{fontSize:11,color:'var(--text-3)',display:'block',marginBottom:5}}>Your email *</label>
                    <input id="ch-email" type="email" defaultValue={localStorage.getItem('ar_user_email')||''} placeholder="you@company.com" style={{width:'100%',boxSizing:'border-box',background:'var(--bg-3)',border:'1px solid var(--border)',borderRadius:6,padding:'8px 10px',color:'var(--text-1)',fontSize:13,outline:'none'}}/>
                  </div>
                  <div>
                    <label style={{fontSize:11,color:'var(--text-3)',display:'block',marginBottom:5}}>{requestingChannel} account ID (optional)</label>
                    <input type="text" placeholder="Your ad account ID" style={{width:'100%',boxSizing:'border-box',background:'var(--bg-3)',border:'1px solid var(--border)',borderRadius:6,padding:'8px 10px',color:'var(--text-1)',fontSize:13,outline:'none'}}/>
                  </div>
                </div>
                <div style={{display:'flex',gap:8,marginTop:16,justifyContent:'flex-end'}}>
                  <button className="btn ghost" onClick={() => setRequestingChannel(null)}>← Back</button>
                  <button className="btn primary" style={{justifyContent:'center',minWidth:140}}
                    onClick={() => {
                      arFetch('/v1/contact', {method:'POST',body:JSON.stringify({channel:requestingChannel,type:'channel_request'})}).catch(()=>{});
                      setRequestSent(true);
                    }}>
                    Request Early Access →
                  </button>
                </div>
              </div>
            ) : (
              <>
                <div style={{fontSize:12,color:'var(--text-3)',marginBottom:14}}>Connect additional paid media platforms to unify performance data and AI attribution.</div>
                {[
                  {name:'TikTok Ads',    logo:'♪',  color:'#fff', bg:'#FE2C55', status:'early_access'},
                  {name:'LinkedIn Ads',  logo:'in', color:'#fff', bg:'#0A66C2', status:'early_access'},
                  {name:'Pinterest Ads', logo:'P',  color:'#fff', bg:'#E60023', status:'early_access'},
                  {name:'Snapchat Ads',  logo:'👻', color:'#000', bg:'#FFFC00', status:'coming_soon'},
                  {name:'Twitter/X Ads', logo:'𝕏',  color:'#fff', bg:'#000',    status:'coming_soon'},
                ].map(ch => (
                  <div key={ch.name} style={{display:'flex',alignItems:'center',gap:12,padding:'10px 14px',background:'var(--bg-2)',border:'1px solid var(--border)',borderRadius:8,marginBottom:8}}>
                    <div style={{width:28,height:28,borderRadius:8,background:ch.bg,display:'flex',alignItems:'center',justifyContent:'center',color:ch.color,fontSize:12,fontWeight:700,flexShrink:0}}>{ch.logo}</div>
                    <span style={{flex:1,fontWeight:500}}>{ch.name}</span>
                    {ch.status === 'early_access' ? (
                      <button className="btn ghost" style={{fontSize:11,color:'var(--accent)',borderColor:'rgba(139,92,246,0.4)',padding:'4px 10px'}}
                        onClick={() => setRequestingChannel(ch.name)}>
                        Request Access →
                      </button>
                    ) : (
                      <span className="badge amber" style={{fontSize:10}}>Coming Soon</span>
                    )}
                  </div>
                ))}
              </>
            )}
          </div>
        </div>
      )}

    </div>
  );
};

window.ChannelsScreen = ChannelsScreen;
