// ============================================================
// CHANNELS — Social automation hub for the Console
// ============================================================
// Broadcast posting · messaging bots · creator-platform sessions
// AI content generator · account warmup · proxy & identity
// Workflow engine
// ============================================================

const ConsoleChannelGlyph = ({ kind, size = 22 }) => {
  const common = { viewBox: '0 0 40 40', xmlns: 'http://www.w3.org/2000/svg', width: size, height: size };
  const s = 'currentColor';
  const cy = 'var(--cyan)';
  const glyphs = {
    tiktok: <svg {...common}><path d="M 14 8 L 14 26 A 4 4 0 1 1 10 22" fill="none" stroke={s} strokeWidth="2"/><path d="M 14 8 Q 18 14 24 14" fill="none" stroke={cy} strokeWidth="2"/></svg>,
    instagram: <svg {...common}><rect x="8" y="8" width="24" height="24" rx="6" fill="none" stroke={s} strokeWidth="1.5"/><circle cx="20" cy="20" r="6" fill="none" stroke={s} strokeWidth="1.5"/><circle cx="27" cy="13" r="1.4" fill={s}/></svg>,
    youtube: <svg {...common}><rect x="6" y="12" width="28" height="16" rx="3" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 17 16 L 25 20 L 17 24 Z" fill={s}/></svg>,
    facebook: <svg {...common}><circle cx="20" cy="20" r="13" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 22 12 L 22 16 L 19 16 L 19 19 L 22 19 L 22 30" fill="none" stroke={s} strokeWidth="2" strokeLinecap="square"/><line x1="17" y1="22" x2="24" y2="22" stroke={s} strokeWidth="2"/></svg>,
    linkedin: <svg {...common}><rect x="7" y="7" width="26" height="26" rx="3" fill="none" stroke={s} strokeWidth="1.5"/><circle cx="13" cy="14" r="1.6" fill={s}/><line x1="13" y1="18" x2="13" y2="27" stroke={s} strokeWidth="2"/><path d="M 18 27 L 18 18 M 18 22 Q 18 17 23 17 Q 27 17 27 22 L 27 27" fill="none" stroke={s} strokeWidth="2"/></svg>,
    x: <svg {...common}><path d="M 10 9 L 30 31 M 30 9 L 10 31" stroke={s} strokeWidth="2.6" strokeLinecap="square"/></svg>,
    threads: <svg {...common}><path d="M 28 14 Q 25 9 20 9 Q 11 9 11 20 Q 11 31 20 31 Q 26 31 28 26" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 16 20 Q 16 16 20 16 Q 24 16 24 20 Q 24 24 20 24" fill="none" stroke={s} strokeWidth="1.5"/><circle cx="20" cy="20" r="1.6" fill={cy}/></svg>,
    bluesky: <svg {...common}><path d="M 10 12 Q 14 8 20 14 Q 26 8 30 12 Q 26 22 20 24 Q 14 22 10 12 Z" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 10 20 Q 14 26 20 28 Q 26 26 30 20" fill="none" stroke={cy} strokeWidth="1.2" opacity="0.7"/></svg>,
    pinterest: <svg {...common}><circle cx="20" cy="20" r="13" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 17 32 L 20 19 M 20 19 Q 20 13 25 13 Q 28 13 28 17 Q 28 22 23 22 Q 19 22 19 19" fill="none" stroke={s} strokeWidth="1.5"/></svg>,
    telegram: <svg {...common}><circle cx="20" cy="20" r="13" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 11 19 L 29 13 L 25 28 L 19 23 L 16 27 L 17 22 L 25 13" fill="none" stroke={s} strokeWidth="1.4" strokeLinejoin="round"/></svg>,
    whatsapp: <svg {...common}><path d="M 9 31 L 11 25 Q 8 21 8 17 Q 8 9 17 9 Q 26 9 26 17 Q 26 25 17 25 Q 14 25 12 24 L 9 31 Z" fill="none" stroke={s} strokeWidth="1.5"/><path d="M 13 16 Q 13 21 18 21" fill="none" stroke={cy} strokeWidth="1.4"/></svg>,
    onlyfans: <svg {...common}><circle cx="20" cy="20" r="13" fill="none" stroke={s} strokeWidth="1.5"/><circle cx="17" cy="20" r="5" fill="none" stroke={s} strokeWidth="1.8"/><path d="M 24 14 Q 28 14 28 18" fill="none" stroke={s} strokeWidth="1.4"/><circle cx="27" cy="15" r="1.2" fill={s}/></svg>,
    fanvue: <svg {...common}><path d="M 10 10 L 16 10 L 16 30 L 12 30 L 12 22 L 22 22" fill="none" stroke={s} strokeWidth="2"/><path d="M 22 10 L 30 30 L 26 30 L 22 18 Z" fill="none" stroke={s} strokeWidth="1.6"/></svg>
  };
  return glyphs[kind] || null;
};

// Channel inventory ---------------------------------------------------------
const CHANNELS = [
  { id: 'tiktok',    name: 'TikTok',    group: 'broadcast', total: 6, active: 4, warming: 1, paused: 1, errors: 0, accounts: 6, scheduled: 42, published24: 28, reach24h: '184k', eng: '5.4%', status: 'live',     tone: '#4be8ff', last: '12m', next: 'in 14m'  },
  { id: 'instagram', name: 'Instagram', group: 'broadcast', total: 7, active: 5, warming: 1, paused: 0, errors: 1, accounts: 7, scheduled: 64, published24: 41, reach24h: '212k', eng: '4.1%', status: 'live',     tone: '#ff7ad9', last: '4m',  next: 'in 26m'  },
  { id: 'youtube',   name: 'YouTube',   group: 'broadcast', total: 2, active: 2, warming: 0, paused: 0, errors: 0, accounts: 2, scheduled: 18, published24: 6,  reach24h: '94k',  eng: '7.2%', status: 'live',     tone: '#ff5d6e', last: '1h',  next: '3:00 PM' },
  { id: 'facebook',  name: 'Facebook',  group: 'broadcast', total: 2, active: 2, warming: 0, paused: 0, errors: 0, accounts: 2, scheduled: 24, published24: 18, reach24h: '38k',  eng: '1.8%', status: 'live',     tone: '#4be8ff', last: '22m', next: 'in 38m'  },
  { id: 'linkedin',  name: 'LinkedIn',  group: 'broadcast', total: 4, active: 3, warming: 1, paused: 0, errors: 0, accounts: 4, scheduled: 38, published24: 24, reach24h: '74k',  eng: '6.1%', status: 'live',     tone: '#8b6bff', last: '6m',  next: 'in 12m'  },
  { id: 'x',         name: 'X',         group: 'broadcast', total: 2, active: 2, warming: 0, paused: 0, errors: 0, accounts: 2, scheduled: 56, published24: 42, reach24h: '88k',  eng: '3.4%', status: 'live',     tone: '#eaecf5', last: '2m',  next: 'in 8m'   },
  { id: 'threads',   name: 'Threads',   group: 'broadcast', total: 2, active: 0, warming: 2, paused: 0, errors: 0, accounts: 2, scheduled: 28, published24: 11, reach24h: '32k',  eng: '4.6%', status: 'warming',  tone: '#eaecf5', last: '18m', next: 'in 42m'  },
  { id: 'bluesky',   name: 'Bluesky',   group: 'broadcast', total: 1, active: 0, warming: 1, paused: 0, errors: 0, accounts: 1, scheduled: 14, published24: 4,  reach24h: '8k',   eng: '5.2%', status: 'warming',  tone: '#4be8ff', last: '32m', next: 'in 1h'   },
  { id: 'pinterest', name: 'Pinterest', group: 'broadcast', total: 1, active: 1, warming: 0, paused: 0, errors: 0, accounts: 1, scheduled: 22, published24: 14, reach24h: '54k',  eng: '2.8%', status: 'live',     tone: '#ff5d6e', last: '14m', next: 'in 26m'  },
  { id: 'telegram',  name: 'Telegram',  group: 'bot',       total: 2, active: 2, warming: 0, paused: 0, errors: 0, accounts: 2, scheduled: 0,  published24: 184, reach24h: '4.2k', eng: '14.2%', status: 'live', tone: '#4be8ff', last: '1m',  next: '—',     kind: 'bot' },
  { id: 'whatsapp',  name: 'WhatsApp',  group: 'bot',       total: 1, active: 1, warming: 0, paused: 0, errors: 0, accounts: 1, scheduled: 0,  published24: 412, reach24h: '1.8k', eng: '22.4%', status: 'live', tone: '#5dffb0', last: '<1m', next: '—',     kind: 'bot' },
  { id: 'onlyfans',  name: 'OnlyFans',  group: 'creator',   total: 1, active: 1, warming: 0, paused: 0, errors: 0, accounts: 1, scheduled: 8,  published24: 3,  reach24h: '480',  eng: '12.4%', status: 'session', tone: '#ffb14b', last: '2h',  next: '8:00 PM' },
  { id: 'fanvue',    name: 'Fanvue',    group: 'creator',   total: 1, active: 1, warming: 0, paused: 0, errors: 0, accounts: 1, scheduled: 6,  published24: 2,  reach24h: '320',  eng: '11.1%', status: 'session', tone: '#ffb14b', last: '3h',  next: '9:00 PM' }
];

const Spark = ({ data, color }) => {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 100}`).join(' ');
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{width: '100%', height: '100%'}}>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4" vectorEffect="non-scaling-stroke" opacity="0.85"/>
    </svg>
  );
};

function ChannelCard({ ch, onOpen }) {
  const sparkData = React.useMemo(
    () => Array.from({length: 24}, (_, i) => 30 + Math.sin(i * 0.7) * 12 + Math.random() * 8),
    []
  );
  const statusMap = {
    live:     { lbl: 'LIVE',     color: 'var(--cyan)',   bg: 'rgba(75,232,255,0.08)',  border: 'rgba(75,232,255,0.3)' },
    warming:  { lbl: 'WARMING',  color: 'var(--warn)',   bg: 'rgba(255,177,75,0.08)',  border: 'rgba(255,177,75,0.3)' },
    session:  { lbl: 'SESSION',  color: 'var(--warn)',   bg: 'rgba(255,177,75,0.08)',  border: 'rgba(255,177,75,0.3)' },
    paused:   { lbl: 'PAUSED',   color: 'var(--text-dim)', bg: 'rgba(255,255,255,0.04)', border: 'rgba(255,255,255,0.12)' }
  };
  const st = statusMap[ch.status] || statusMap.live;
  const isBot = ch.kind === 'bot';
  const isCreator = ch.group === 'creator';

  return (
    <div
      className={`ch-card frame ${isCreator ? 'creator' : ''}`}
      role="button"
      tabIndex={0}
      onClick={() => onOpen(ch)}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(ch); }}}
      style={{borderColor: isCreator ? 'rgba(255,177,75,0.18)' : undefined, cursor: 'pointer'}}
    >
      <span className="br-bl"></span>
      <span className="br-br"></span>
      <div className="ch-card-hd">
        <div className="ch-card-glyph" style={{color: ch.tone}}>
          <ConsoleChannelGlyph kind={ch.id} size={28}/>
        </div>
        <div className="ch-card-info">
          <div className="ch-card-name">{ch.name}</div>
          <div className="ch-card-sub">
            <span>{ch.total} account{ch.total > 1 ? 's' : ''}</span>
            <span style={{color: 'var(--text-faint)'}}>·</span>
            <span>{isBot ? 'bot' : isCreator ? 'session' : 'broadcast'}</span>
          </div>
        </div>
        <div className="ch-card-status" style={{color: st.color, background: st.bg, borderColor: st.border}}>
          <span className="pip" style={{background: st.color, boxShadow: ch.status === 'paused' ? 'none' : `0 0 6px ${st.color}`}}></span>
          {st.lbl}
        </div>
      </div>

      {/* Account state pills */}
      <div className="ch-card-states">
        <div className="ch-state"><span className="v" style={{color:'var(--cyan)'}}>{ch.active}</span><span className="l">active</span></div>
        <div className="ch-state"><span className="v" style={{color:'var(--warn)'}}>{ch.warming}</span><span className="l">warming</span></div>
        <div className="ch-state"><span className="v" style={{color:'var(--text-dim)'}}>{ch.paused}</span><span className="l">paused</span></div>
        <div className="ch-state"><span className="v" style={{color: ch.errors > 0 ? 'var(--danger)' : 'var(--text-faint)'}}>{ch.errors}</span><span className="l">errors</span></div>
      </div>

      <div className="ch-card-metrics">
        <div className="ch-metric">
          <div className="lbl">Scheduled</div>
          <div className="val">{ch.scheduled}</div>
        </div>
        <div className="ch-metric">
          <div className="lbl">Published 24h</div>
          <div className="val">{ch.published24}</div>
        </div>
        <div className="ch-metric">
          <div className="lbl">{isBot ? 'Reply rate' : 'Engagement'}</div>
          <div className="val" style={{color: 'var(--cyan)'}}>{ch.eng}</div>
        </div>
      </div>

      <div className="ch-card-spark"><Spark data={sparkData} color={ch.tone}/></div>

      <div className="ch-card-foot">
        <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.1em'}}>
          last <span style={{color: 'var(--text-dim)'}}>{ch.last}</span> · next <span style={{color: 'var(--cyan)'}}>{ch.next}</span>
        </span>
        <span className="ch-card-open">Open control center <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M9 6l6 6-6 6"/></svg></span>
      </div>
      <div className="ch-card-hover-glow"></div>
    </div>
  );
}

// AI Content Generator ------------------------------------------------------
function AIContentGenerator() {
  const [tab, setTab] = React.useState('text');
  const [prompt, setPrompt] = React.useState('');
  const [generating, setGenerating] = React.useState(false);
  const [result, setResult] = React.useState(null);
  const [variant, setVariant] = React.useState(0);

  const presets = {
    text: 'Founder story · LinkedIn · 280 char hook',
    image: 'IG carousel · 5 slides · brand palette',
    video: 'TikTok · 15s · hook + payoff',
    avatar: 'Avatar · 30s VO · script + lipsync'
  };

  const handleGenerate = async () => {
    if (!prompt.trim()) return;
    setGenerating(true);
    setResult(null);
    // Use built-in Claude call for a real-feel demo
    try {
      const text = await window.claude.complete({
        messages: [{
          role: 'user',
          content: `You are Calliope, the Demiurge content operator. Produce 3 variants for: "${prompt}". Output: 3 numbered options, each under 60 words, distinct angles, no preamble.`
        }]
      });
      setResult(text);
      setVariant(0);
    } catch (e) {
      setResult('1. Network unavailable in preview. The real Calliope ships through redundant model gateways with sub-second failover.\n\n2. Connection blocked. Live deployments use SOC-2 isolated runners with full audit logs.\n\n3. Demo offline. Real generations stream as tokens with side-by-side previews per platform.');
    }
    setGenerating(false);
  };

  return (
    <div className="panel frame">
      <span className="br-bl"></span>
      <span className="br-br"></span>
      <span className="coord">AI · CONTENT · CALLIOPE</span>
      <div className="panel-hd">
        <h3><Icon.Sparkles style={{width: 14, height: 14, color: 'var(--cyan)'}}/> AI Content Generator</h3>
        <span className="panel-meta">2.4M / 5M TOKENS · MAY</span>
      </div>
      <div className="panel-body" style={{display: 'flex', flexDirection: 'column', gap: 14}}>
        <div className="segmented">
          {['text', 'image', 'video', 'avatar'].map(k => (
            <button key={k} className={tab === k ? 'active' : ''} onClick={() => setTab(k)}>
              {k}
            </button>
          ))}
        </div>
        <div style={{
          background: 'rgba(0,0,0,0.35)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--radius)',
          padding: 12,
          display: 'flex',
          flexDirection: 'column',
          gap: 10
        }}>
          <input
            value={prompt}
            onChange={e => setPrompt(e.target.value)}
            placeholder={presets[tab]}
            style={{
              fontSize: 13,
              padding: '6px 0',
              width: '100%',
              color: 'var(--text)',
              fontFamily: 'var(--font-mono)'
            }}
            onKeyDown={e => { if (e.key === 'Enter') handleGenerate(); }}
          />
          <div style={{display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap'}}>
            {tab === 'text' && ['LinkedIn', 'X', 'IG caption', 'Threads', 'Email'].map(p => (
              <button key={p} className="channel-chip" onClick={() => setPrompt(`${tab}: ${p}`)}>{p}</button>
            ))}
            {tab === 'image' && ['Square', 'Vertical', 'Carousel', 'Story', 'Brand palette'].map(p => (
              <button key={p} className="channel-chip" onClick={() => setPrompt(`${tab}: ${p}`)}>{p}</button>
            ))}
            {tab === 'video' && ['TikTok 15s', 'Reels 30s', 'Shorts 60s', 'Long-form'].map(p => (
              <button key={p} className="channel-chip" onClick={() => setPrompt(`${tab}: ${p}`)}>{p}</button>
            ))}
            {tab === 'avatar' && ['Voice clone', 'Face avatar', 'Both · VO + lipsync'].map(p => (
              <button key={p} className="channel-chip" onClick={() => setPrompt(`${tab}: ${p}`)}>{p}</button>
            ))}
            <button className="btn primary sm" style={{marginLeft: 'auto'}} onClick={handleGenerate} disabled={generating}>
              {generating ? 'Generating…' : `Generate ${tab}`}
            </button>
          </div>
        </div>
        {result && (
          <div style={{
            background: 'rgba(75,232,255,0.04)',
            border: '1px solid rgba(75,232,255,0.18)',
            borderRadius: 'var(--radius)',
            padding: 14,
            fontFamily: 'var(--font-ui)',
            fontSize: 13,
            lineHeight: 1.5,
            color: 'var(--text)',
            whiteSpace: 'pre-wrap',
            maxHeight: 220,
            overflow: 'auto'
          }}>
            {result}
          </div>
        )}
        {(tab === 'video' || tab === 'avatar') && (
          <div style={{
            fontFamily: 'var(--font-mono)',
            fontSize: 10,
            letterSpacing: '0.1em',
            color: 'var(--text-faint)',
            textTransform: 'uppercase',
            padding: '8px 12px',
            border: '1px dashed rgba(255,255,255,0.08)',
            borderRadius: 'var(--radius)'
          }}>
            <span style={{color: 'var(--warn)'}}>● </span>
            {tab === 'video' ? 'Video synthesis · optional · add-on tier' : 'Avatar / clone · optional · creator-explicit consent required'}
          </div>
        )}
      </div>
    </div>
  );
}

// Account Warmup ------------------------------------------------------------
function AccountWarmup() {
  const accounts = [
    { name: '@demiurge_uk',  platform: 'tiktok',    day: 14, of: 30, score: 0.84, status: 'on_track' },
    { name: 'demiurge.ops',  platform: 'instagram', day: 22, of: 30, score: 0.91, status: 'on_track' },
    { name: '@demiurge',     platform: 'threads',   day: 6,  of: 21, score: 0.62, status: 'cool' },
    { name: 'demiurge.eu',   platform: 'bluesky',   day: 3,  of: 21, score: 0.41, status: 'cool' },
    { name: '@d_studio',     platform: 'x',         day: 28, of: 30, score: 0.96, status: 'ready' }
  ];
  return (
    <div className="panel frame violet">
      <span className="br-bl"></span>
      <span className="br-br"></span>
      <span className="coord violet">WARMUP · ATLAS</span>
      <div className="panel-hd">
        <h3>Account warmup</h3>
        <span className="panel-meta">5 IN PROGRESS · 12 GRADUATED</span>
      </div>
      <div className="panel-body" style={{padding: 0}}>
        {accounts.map((a, i) => {
          const statusColor = a.status === 'ready' ? 'var(--good)' : a.status === 'on_track' ? 'var(--cyan)' : 'var(--warn)';
          return (
            <div key={i} style={{
              display: 'grid',
              gridTemplateColumns: '22px 1fr 90px 70px',
              gap: 12,
              padding: '11px 18px',
              borderBottom: i < accounts.length - 1 ? '1px solid var(--border)' : 'none',
              alignItems: 'center'
            }}>
              <div style={{color: 'var(--text-dim)'}}><ConsoleChannelGlyph kind={a.platform} size={18}/></div>
              <div style={{display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0}}>
                <span style={{fontSize: 12.5, color: 'var(--text)'}}>{a.name}</span>
                <span className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase'}}>day {a.day} of {a.of} · {a.status.replace('_', ' ')}</span>
              </div>
              <div className="bar-track" style={{width: 80}}>
                <div className="bar-fill" style={{
                  width: `${(a.day / a.of) * 100}%`,
                  background: statusColor,
                  boxShadow: `0 0 6px ${statusColor}`
                }}/>
              </div>
              <span className="mono" style={{fontSize: 11, color: statusColor, textAlign: 'right'}}>{(a.score * 100).toFixed(0)}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// Proxy / Identity ----------------------------------------------------------
function ProxyIdentity() {
  const regions = [
    { name: 'UK',     pool: 64, active: 38, lat: '14ms' },
    { name: 'EU-DE',  pool: 42, active: 22, lat: '22ms' },
    { name: 'US-E',   pool: 38, active: 18, lat: '48ms' },
    { name: 'US-W',   pool: 28, active: 14, lat: '68ms' },
    { name: 'AU',     pool: 12, active: 4,  lat: '184ms' }
  ];
  return (
    <div className="panel frame">
      <span className="br-bl"></span>
      <span className="br-br"></span>
      <span className="coord">PROXY · NET</span>
      <div className="panel-hd">
        <h3>Proxy & identity</h3>
        <span className="panel-meta">184 IPs · 5 REGIONS · RESIDENTIAL</span>
      </div>
      <div className="panel-body" style={{padding: 0}}>
        <div style={{padding: '14px 18px', borderBottom: '1px solid var(--border)', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16}}>
          <div>
            <div className="mono faint" style={{fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase'}}>Active</div>
            <div className="huge" style={{fontSize: 24, marginTop: 4, color: 'var(--cyan)'}}>96</div>
          </div>
          <div>
            <div className="mono faint" style={{fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase'}}>Pool</div>
            <div className="huge" style={{fontSize: 24, marginTop: 4}}>184</div>
          </div>
          <div>
            <div className="mono faint" style={{fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase'}}>Rotation</div>
            <div className="huge" style={{fontSize: 24, marginTop: 4, color: 'var(--good)'}}>24m</div>
          </div>
        </div>
        {regions.map((r, i) => (
          <div key={r.name} style={{
            display: 'grid',
            gridTemplateColumns: '60px 1fr auto auto',
            gap: 14,
            padding: '10px 18px',
            borderBottom: i < regions.length - 1 ? '1px solid var(--border)' : 'none',
            alignItems: 'center'
          }}>
            <span className="mono" style={{fontSize: 11, color: 'var(--text)', letterSpacing: '0.1em'}}>{r.name}</span>
            <div className="bar-track">
              <div className="bar-fill cool" style={{width: `${(r.active / r.pool) * 100}%`}}/>
            </div>
            <span className="mono" style={{fontSize: 10.5, color: 'var(--text-dim)'}}>{r.active}/{r.pool}</span>
            <span className="mono" style={{fontSize: 10.5, color: 'var(--text-faint)', minWidth: 50, textAlign: 'right'}}>{r.lat}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// Main Channels page --------------------------------------------------------
function Channels() {
  const [filter, setFilter] = React.useState('all');
  const [selectedChannel, setSelectedChannel] = React.useState(null);

  // ESC to leave control center
  React.useEffect(() => {
    if (!selectedChannel) return;
    const onKey = (e) => { if (e.key === 'Escape') setSelectedChannel(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [selectedChannel]);

  if (selectedChannel) {
    return (
      <div className="ch-fade-in">
        <ChannelControlCenter channel={selectedChannel} onBack={() => setSelectedChannel(null)}/>
      </div>
    );
  }

  const filtered = filter === 'all' ? CHANNELS : CHANNELS.filter(c => c.group === filter);
  const totalAccounts = CHANNELS.reduce((s, c) => s + c.total, 0);
  const totalScheduled = CHANNELS.reduce((s, c) => s + c.scheduled, 0);
  const totalErrors = CHANNELS.reduce((s, c) => s + c.errors, 0);

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Social Automation · {CHANNELS.length} platforms · {totalAccounts} accounts</div>
          <h1 className="page-title"><em>Channels</em> <strong>& reach</strong></h1>
          <div className="page-sub">Broadcast, message, and respond natively across every surface your audience lives on. The operators ship content, warm new accounts, and rotate identity automatically.</div>
        </div>
        <div className="page-hd-r">
          <div className="segmented">
            {[
              ['all',       'All'],
              ['broadcast', 'Broadcast'],
              ['bot',       'Bots'],
              ['creator',   'Creator']
            ].map(([k, l]) => (
              <button key={k} className={filter === k ? 'active' : ''} onClick={() => setFilter(k)}>{l}</button>
            ))}
          </div>
          <button className="btn" data-handled="1" onClick={() => window.runAction('connect', { name: 'channel' })}><Icon.Plus className="icon"/>Add account</button>
          <button className="btn primary" data-handled="1" onClick={() => window.runAction('createContent')}><Icon.Sparkles className="icon"/>Compose with AI</button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{
        padding: '24px 32px',
        display: 'grid',
        gridTemplateColumns: 'repeat(4, 1fr)',
        gap: 14
      }}>
        <div className="kpi-block">
          <div className="kpi-label">Posts scheduled · 24h</div>
          <div className="kpi-val tnum">{totalScheduled}</div>
          <div className="kpi-meta"><span className="delta up">+47</span><span className="dim">vs yesterday</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Accounts active</div>
          <div className="kpi-val tnum">{totalAccounts}<span className="unit"> / 32</span></div>
          <div className="kpi-meta"><span className="delta up">+3</span><span className="dim">in warmup</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Reach · 24h</div>
          <div className="kpi-val tnum">812<span className="unit">k</span></div>
          <div className="kpi-meta"><span className="delta up">+18%</span><span className="dim">vs avg</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Account errors</div>
          <div className="kpi-val tnum" style={{color: totalErrors > 0 ? 'var(--danger)' : 'var(--text)'}}>{totalErrors}</div>
          <div className="kpi-meta"><span className="dim">{totalErrors > 0 ? 'needs attention' : 'all systems normal'}</span></div>
        </div>
      </div>

      {/* Channel grid */}
      <div style={{padding: '0 32px 24px'}}>
        <div className="ch-grid">
          {filtered.map(ch => <ChannelCard key={ch.id} ch={ch} onOpen={setSelectedChannel}/>)}
        </div>
      </div>

      {/* Bottom row — AI gen + Warmup + Proxy */}
      <div style={{
        padding: '0 32px 32px',
        display: 'grid',
        gridTemplateColumns: '1.4fr 1fr 1fr',
        gap: 14,
        alignItems: 'start'
      }}>
        <AIContentGenerator/>
        <AccountWarmup/>
        <ProxyIdentity/>
      </div>

      {/* Compliance footnote for session-based connectors */}
      <div style={{padding: '0 32px 36px'}}>
        <div style={{
          padding: '14px 18px',
          fontFamily: 'var(--font-mono)',
          fontSize: 11,
          lineHeight: 1.5,
          color: 'var(--text-dim)',
          letterSpacing: '0.04em',
          borderLeft: '2px solid rgba(255,177,75,0.4)',
          background: 'rgba(255,177,75,0.03)',
          borderRadius: '0 3px 3px 0'
        }}>
          <span style={{color: 'var(--warn)', fontWeight: 600, letterSpacing: '0.16em', textTransform: 'uppercase'}}>Session-based connectors</span> ·
          {' '}OnlyFans &amp; Fanvue run inside the creator's own authenticated session. Demiurge orchestrates only what the creator is permitted to do under each platform's ToS — no scraping, no bot impersonation, no automation of restricted actions. Use of session connectors requires creator-explicit consent and is logged for audit.
        </div>
      </div>
    </div>
  );
}
