// ============================================================
// FUNNEL CONTROL CENTER — per-funnel mission control
// Tabs: Overview · Stages · Automations · Traffic · Content · Analytics · Logs
// ============================================================

// Shared stage template — Traffic → Landing → Form → Qualify → Booking → Nurture → Close → Upsell → Retention
function buildStages(funnel) {
  const baseVisitors = funnel.leads ? Math.round(funnel.leads * 100 / (funnel.cvr || 5)) : 0;
  const seed = funnel.id.charCodeAt(3);
  const passRates = funnel.status === 'offline'
    ? [0, 0, 0, 0, 0, 0, 0, 0]
    : [0.62, 0.78, 0.54, 0.46, 0.74, 0.42, 0.32, 0.18];

  const stages = [];
  let prev = baseVisitors;
  const labels = ['Traffic', 'Landing', 'Lead form', 'Qualification', 'Booking', 'Nurture', 'Close', 'Upsell', 'Retention'];
  const kinds  = ['source',  'page',    'form',      'qualify',       'book',    'sequence', 'sale',  'upsell', 'retain'];

  stages.push({ name: labels[0], kind: kinds[0], val: prev, pass: null, drop: null, health: 0.92, idx: 0 });
  for (let i = 1; i < labels.length; i++) {
    const next = Math.max(0, Math.round(prev * passRates[i - 1] * (0.85 + ((seed + i) % 30) / 100)));
    const passPct = prev > 0 ? (next / prev) * 100 : 0;
    const health = passPct > 60 ? 0.9 : passPct > 40 ? 0.72 : passPct > 25 ? 0.5 : 0.32;
    stages.push({
      name: labels[i],
      kind: kinds[i],
      val: next,
      pass: passPct,
      drop: prev - next,
      health,
      idx: i,
      bottleneck: passPct < 30 && prev > 100
    });
    prev = next;
  }
  return stages;
}

// ===================== OVERVIEW TAB =====================
function FunnelOverviewTab({ funnel, stages, onPushToast, onAction }) {
  const type = FUNNEL_TYPES[funnel.type];
  const bottleneck = stages.find(s => s.bottleneck);

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
      {/* Action bar */}
      <div className="fcc-action-bar">
        <button className="btn primary sm" onClick={() => onAction('optimize')}>
          <Icon.Sparkles className="icon"/>Optimize funnel
        </button>
        <button className="btn sm" onClick={() => onAction('audit')}>Run AI audit</button>
        <button className="btn sm" onClick={() => onAction('duplicate')}>Duplicate</button>
        <button className="btn sm" onClick={() => onAction('split')}>Launch split test</button>
        <span style={{flex: 1}}/>
        <button className="btn sm" onClick={() => onAction('pause')}>
          {funnel.status === 'live' ? 'Pause funnel' : 'Resume funnel'}
        </button>
      </div>

      {/* AI recommendations + warnings strip */}
      {bottleneck && (
        <div className="fcc-alert warn">
          <span className="fcc-alert-icon">⚠</span>
          <div style={{flex: 1}}>
            <div className="fcc-alert-title">Bottleneck detected · {bottleneck.name}</div>
            <div className="fcc-alert-body">
              Pass-rate of {bottleneck.pass.toFixed(1)}% is below historical norm.
              {' '}{bottleneck.drop.toLocaleString()} prospects dropping out at this stage this period.
              {' '}<span style={{color: 'var(--cyan)'}}>AI recommends</span> rewriting the {bottleneck.kind} copy
              and reducing form fields from 7 → 4.
            </div>
          </div>
          <button className="btn sm" onClick={() => onPushToast('Recommendation queued for review')}>Review</button>
        </div>
      )}

      <div className="fcc-alert info">
        <span className="fcc-alert-icon" style={{color: 'var(--cyan)'}}>✦</span>
        <div style={{flex: 1}}>
          <div className="fcc-alert-title">Lead form abandonment increased +17% over 7 days</div>
          <div className="fcc-alert-body">
            Mobile drop-off accounts for 84% of the variance. Iris suggests a single-page form variant
            for mobile traffic — projected recovery: <span style={{color: 'var(--good)'}}>+42 booked / month</span>.
          </div>
        </div>
        <button className="btn sm" onClick={() => onPushToast('Variant created · pending approval')}>Build variant</button>
      </div>

      {/* The flow visualization */}
      <div className="fcc-flow">
        <div className="fcc-flow-hd">
          <span className="mono" style={{fontSize: 11, color: 'var(--brass-bright, #e8c98a)', letterSpacing: '0.18em', textTransform: 'uppercase'}}>
            Stage flow · live
          </span>
          <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase'}}>
            top: {stages[0].val.toLocaleString()} · end: {stages[stages.length-1].val.toLocaleString()} · e2e {((stages[stages.length-1].val / (stages[0].val || 1)) * 100).toFixed(2)}%
          </span>
        </div>
        <div className="fcc-flow-stages">
          {stages.map((s, i) => {
            const healthColor = s.health > 0.75 ? 'var(--good)' : s.health > 0.5 ? 'var(--warn)' : 'var(--danger)';
            const widthPct = i === 0 ? 100 : Math.max(8, (s.val / stages[0].val) * 100);
            return (
              <React.Fragment key={s.idx}>
                <div className={`fcc-stage ${s.bottleneck ? 'bottleneck' : ''}`}>
                  <div className="fcc-stage-bar" style={{
                    width: `${widthPct}%`,
                    background: `linear-gradient(90deg, ${type.hue}45, ${type.hue}10)`,
                    borderColor: s.bottleneck ? 'var(--danger)' : `${type.hue}50`
                  }}>
                    <div className="fcc-stage-bar-label">
                      <span style={{fontSize: 13, color: '#f5f1e6', fontWeight: 500}}>{s.name}</span>
                      <span className="mono" style={{fontSize: 11, color: 'var(--text-dim)', marginLeft: 'auto'}}>{s.val.toLocaleString()}</span>
                    </div>
                  </div>
                  <div className="fcc-stage-side">
                    {s.pass !== null && (
                      <>
                        <span className="mono" style={{fontSize: 11, color: 'var(--cyan)'}}>{s.pass.toFixed(1)}%</span>
                        <span className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase'}}>pass</span>
                      </>
                    )}
                    {s.idx === 0 && (
                      <span className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.1em', textTransform: 'uppercase'}}>top</span>
                    )}
                  </div>
                  <div className="fcc-stage-health">
                    <div className="bar-track" style={{width: 40, height: 3}}>
                      <div className="bar-fill flat" style={{width: `${s.health * 100}%`, background: healthColor}}/>
                    </div>
                    <span className="mono" style={{fontSize: 10, color: healthColor}}>{Math.round(s.health * 100)}</span>
                  </div>
                </div>
                {i < stages.length - 1 && (
                  <div className="fcc-stage-drop">
                    <span className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.12em'}}>
                      ↓ {((s.val - stages[i+1].val) / (s.val || 1) * 100).toFixed(1)}% drop · {(s.val - stages[i+1].val).toLocaleString()} lost
                    </span>
                    {s.bottleneck && (
                      <span style={{color: 'var(--danger)', fontFamily: 'var(--font-mono)', fontSize: 9.5, letterSpacing: '0.12em', textTransform: 'uppercase'}}>
                        · BOTTLENECK
                      </span>
                    )}
                  </div>
                )}
              </React.Fragment>
            );
          })}
        </div>
      </div>

      {/* Revenue attribution + AI insight cards */}
      <div className="fcc-overview-grid">
        <div className="fcc-mini-card">
          <div className="ccc-setting-hd" style={{borderBottom: 'none', padding: '14px 18px'}}>Revenue attribution</div>
          <div style={{padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 12}}>
            {[
              { stage: 'Close',      pct: 64, value: Math.round(funnel.revenue * 0.64) },
              { stage: 'Upsell',     pct: 22, value: Math.round(funnel.revenue * 0.22) },
              { stage: 'Retention',  pct: 12, value: Math.round(funnel.revenue * 0.12) },
              { stage: 'Booking',    pct: 2,  value: Math.round(funnel.revenue * 0.02) }
            ].map((r, i) => (
              <div key={i} style={{display: 'flex', flexDirection: 'column', gap: 5}}>
                <div style={{display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--font-mono)', fontSize: 11}}>
                  <span style={{color: 'var(--text)'}}>{r.stage}</span>
                  <span style={{color: 'var(--text)'}}>£{r.value.toLocaleString()} <span style={{color: 'var(--text-faint)'}}>· {r.pct}%</span></span>
                </div>
                <div className="bar-track" style={{height: 4}}>
                  <div className="bar-fill" style={{width: `${r.pct}%`, background: type.hue, boxShadow: `0 0 6px ${type.hue}`}}/>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="fcc-mini-card">
          <div className="ccc-setting-hd" style={{borderBottom: 'none', padding: '14px 18px'}}>AI recommendations</div>
          <div style={{padding: '0 18px 18px', display: 'flex', flexDirection: 'column', gap: 10}}>
            {[
              { p: 'high', text: 'Shorten form on mobile to 4 fields', impact: '+42 booked/mo' },
              { p: 'high', text: 'Add social proof video at qualification step', impact: '+8.4% pass' },
              { p: 'med',  text: 'Auto-personalize headline to source UTM', impact: '+3.2% landing' },
              { p: 'med',  text: 'Trigger missed-booking recovery after 4h', impact: '+18 recovered/mo' },
              { p: 'low',  text: 'Test brass-foil CTA on mobile', impact: '+0.8% CVR' }
            ].map((r, i) => (
              <div key={i} className="fcc-rec">
                <span className={`fcc-rec-p p-${r.p}`}>{r.p.toUpperCase()}</span>
                <span style={{flex: 1, fontSize: 12.5, color: 'var(--text)'}}>{r.text}</span>
                <span className="mono" style={{fontSize: 10, color: 'var(--good)', letterSpacing: '0.06em'}}>{r.impact}</span>
                <button className="ccc-iconbtn" onClick={() => onPushToast(`Queued: ${r.text}`)}>
                  <Icon.Plus style={{width: 12, height: 12}}/>
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ===================== STAGES TAB =====================
function FunnelStagesTab({ funnel, stages, onPushToast }) {
  const [editingStage, setEditingStage] = React.useState(null);
  const stageContent = {
    'Traffic':       { headline: 'Traffic sources tuned', sub: 'Routes from Google · Meta · TikTok · Organic',  fields: ['Active sources', 'UTM convention', 'Source caps'] },
    'Landing':       { headline: 'Run your business while you sleep.', sub: 'Hero block · social proof · single CTA above-fold', fields: ['Headline', 'Sub-headline', 'CTA copy', 'Hero asset', 'Trust badges'] },
    'Lead form':     { headline: 'See how Demiurge operates for you', sub: '4 fields · progressive disclosure · address-autofill',  fields: ['Field list', 'Validation', 'Progressive logic', 'Submit copy'] },
    'Qualification': { headline: 'A few quick questions',         sub: 'Score 0-100 · auto-route ≥ 70',                fields: ['Questions', 'Scoring rules', 'Route logic', 'Hot-lead notification'] },
    'Booking':       { headline: 'Pick your slot',                sub: 'Round-robin · 30-min slots · 48h horizon',     fields: ['Calendar', 'Availability', 'Buffer', 'Confirmation copy'] },
    'Nurture':       { headline: '6-touch sequence',              sub: 'D0 · D1 · D3 · D7 · D14 · D21 · D28',          fields: ['Touch cadence', 'Channel mix', 'Personalisation', 'Exit conditions'] },
    'Close':         { headline: 'The proposal',                  sub: 'Auto-generated · sent within 12 min of call',  fields: ['Template', 'Offer terms', 'Signing flow', 'Approval rules'] },
    'Upsell':        { headline: 'Expand the engagement',         sub: 'Triggered at day 21 post-close',               fields: ['Trigger', 'Offer', 'Discount rules', 'Cap'] },
    'Retention':     { headline: 'Quarterly business review',     sub: 'QBR · NPS · expansion path',                   fields: ['Cadence', 'QBR template', 'NPS trigger', 'Renewal flow'] }
  };

  return (
    <div className="fcc-stages">
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, flexWrap: 'wrap', gap: 12}}>
        <span className="mono faint" style={{fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase'}}>
          {stages.length} stages · drag to reorder · click to edit
        </span>
        <div style={{display: 'flex', gap: 8}}>
          <button className="btn sm">Import template</button>
          <button className="btn primary sm" onClick={() => onPushToast('Stage added to draft')}>
            <Icon.Plus className="icon"/>Add stage
          </button>
        </div>
      </div>

      <div className="fcc-stages-grid">
        {stages.map((s, i) => {
          const content = stageContent[s.name] || { headline: '—', sub: '', fields: [] };
          const healthColor = s.health > 0.75 ? 'var(--good)' : s.health > 0.5 ? 'var(--warn)' : 'var(--danger)';
          return (
            <div key={s.idx} className={`fcc-stage-card ${editingStage === s.idx ? 'editing' : ''}`} onClick={() => setEditingStage(editingStage === s.idx ? null : s.idx)}>
              <div className="fcc-stage-card-hd">
                <span className="fcc-stage-handle" title="Drag to reorder">⋮⋮</span>
                <span className="mono" style={{fontSize: 9.5, color: 'var(--text-faint)', letterSpacing: '0.16em'}}>/ {String(i + 1).padStart(2, '0')}</span>
                <span style={{fontSize: 14, color: 'var(--text)', flex: 1, fontFamily: 'var(--font-display)', fontStyle: 'italic'}}>{s.name}</span>
                <span className="mono" style={{fontSize: 10, color: healthColor, letterSpacing: '0.08em'}}>
                  health {Math.round(s.health * 100)}
                </span>
                <span className="mono faint" style={{fontSize: 10}}>{s.val.toLocaleString()}</span>
              </div>
              <div className="fcc-stage-card-body">
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 17, color: 'var(--text)', letterSpacing: '-0.01em'}}>
                    {content.headline}
                  </div>
                  <div className="mono faint" style={{fontSize: 10.5, marginTop: 4, letterSpacing: '0.04em'}}>{content.sub}</div>
                  {editingStage === s.idx && content.fields.length > 0 && (
                    <div className="fcc-stage-fields" onClick={e => e.stopPropagation()}>
                      {content.fields.map((f, fi) => (
                        <div key={fi} className="fcc-stage-field">
                          <span className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.14em', textTransform: 'uppercase'}}>{f}</span>
                          <input
                            type="text"
                            defaultValue={fi === 0 ? content.headline : ''}
                            placeholder={fi === 0 ? '' : `Edit ${f.toLowerCase()}…`}
                            style={{width: '100%', fontSize: 13, padding: '6px 0', fontFamily: 'var(--font-mono)', color: 'var(--text)', borderBottom: '1px solid var(--border)'}}
                          />
                        </div>
                      ))}
                    </div>
                  )}
                </div>
                <div className="fcc-stage-card-actions" onClick={e => e.stopPropagation()}>
                  <button className="btn primary sm" onClick={() => onPushToast(`AI improving stage · ${s.name}`)}>
                    <Icon.Sparkles className="icon"/>AI improve
                  </button>
                  <button className="btn sm" onClick={() => onPushToast(`Variant created · ${s.name}`)}>Split test</button>
                  <button className="btn sm" onClick={() => onPushToast(`Logic attached · ${s.name}`)}>Logic</button>
                  <button className="btn ghost sm" onClick={() => onPushToast(`Stage duplicated · ${s.name}`)}>Clone</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ===================== AUTOMATIONS TAB =====================
function FunnelAutomationsTab({ funnel, onPushToast }) {
  const AUTOMATIONS = [
    { id: 'nurture',       name: 'Lead nurture · 7 touches',      trigger: 'Form submit',                agent: 'Calliope', runs: 1284, success: 94, errors: 8,  status: 'live' },
    { id: 'missed_book',   name: 'Missed booking recovery',       trigger: 'Booked + no-show',           agent: 'Hermes',   runs: 142,  success: 76, errors: 4,  status: 'live' },
    { id: 'form_abandon',  name: 'Abandoned form recovery',       trigger: 'Form started + 4h idle',     agent: 'Hermes',   runs: 412,  success: 38, errors: 2,  status: 'live' },
    { id: 'email_seq',     name: 'Email sequence · D0-D28',       trigger: 'Lead created',               agent: 'Calliope', runs: 1804, success: 96, errors: 0,  status: 'live' },
    { id: 'sms_camp',      name: 'SMS campaign · last-chance',    trigger: 'Trial expiring · D14',       agent: 'Calliope', runs: 218,  success: 88, errors: 1,  status: 'live' },
    { id: 'retarget',      name: 'Retargeting · paid audiences',  trigger: 'Engaged + un-converted',     agent: 'Orion',    runs: 84,   success: 92, errors: 0,  status: 'live' },
    { id: 'cal_reminder',  name: 'Calendar reminders',            trigger: 'Booked + T-24h / T-1h',      agent: 'Hermes',   runs: 612,  success: 98, errors: 0,  status: 'live' },
    { id: 'ai_call_fu',    name: 'AI call follow-up',             trigger: 'Call ended + no decision',   agent: 'Hermes',   runs: 84,   success: 78, errors: 4,  status: 'paused' },
    { id: 'crm_sync',      name: 'CRM sync · two-way',            trigger: 'Stage change',               agent: 'system',   runs: 4218, success: 99, errors: 18, status: 'live' }
  ];

  const [selected, setSelected] = React.useState(new Set());
  const [states, setStates] = React.useState(() => Object.fromEntries(AUTOMATIONS.map(a => [a.id, a.status === 'live'])));

  const toggleOne = (id) => {
    setStates(s => ({...s, [id]: !s[id]}));
    onPushToast(`${states[id] ? 'Paused' : 'Resumed'} · ${AUTOMATIONS.find(a => a.id === id).name}`);
  };
  const toggleSel = (id) => {
    const n = new Set(selected);
    if (n.has(id)) n.delete(id); else n.add(id);
    setSelected(n);
  };
  const bulk = (action) => {
    onPushToast(`${action} · ${selected.size} automation${selected.size > 1 ? 's' : ''}`);
    setSelected(new Set());
  };

  return (
    <div>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14, flexWrap: 'wrap', gap: 12}}>
        <span className="mono faint" style={{fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase'}}>
          {Object.values(states).filter(Boolean).length} of {AUTOMATIONS.length} active · last run 2m ago
        </span>
        <button className="btn primary sm"><Icon.Plus className="icon"/>Attach automation</button>
      </div>

      {selected.size > 0 && (
        <div className="ccc-bulk">
          <span className="mono" style={{fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--cyan)'}}>
            {selected.size} selected
          </span>
          <span style={{flex: 1}}/>
          <button className="btn sm" onClick={() => bulk('Paused')}>Pause</button>
          <button className="btn sm" onClick={() => bulk('Resumed')}>Resume</button>
          <button className="btn sm" onClick={() => bulk('Cloned')}>Clone</button>
          <button className="btn sm" onClick={() => bulk('Re-assigned')}>Reassign</button>
          <button className="btn sm" onClick={() => bulk('Exported')}>Export</button>
          <button className="btn ghost sm" onClick={() => setSelected(new Set())}>✕</button>
        </div>
      )}

      <div className="fcc-auto-table">
        <div className="fcc-auto-row hd">
          <div className="c chk"></div>
          <div className="c">Automation</div>
          <div className="c">Trigger</div>
          <div className="c">Operator</div>
          <div className="c">Runs</div>
          <div className="c">Success</div>
          <div className="c">Errors</div>
          <div className="c">State</div>
          <div className="c">Actions</div>
        </div>
        {AUTOMATIONS.map(a => (
          <div key={a.id} className={`fcc-auto-row ${selected.has(a.id) ? 'sel' : ''}`}>
            <div className="c chk">
              <input type="checkbox" checked={selected.has(a.id)} onChange={() => toggleSel(a.id)}/>
            </div>
            <div className="c" style={{display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0}}>
              <span style={{fontSize: 13, color: 'var(--text)'}}>{a.name}</span>
            </div>
            <div className="c mono dim" style={{fontSize: 11}}>{a.trigger}</div>
            <div className="c"><span className="mono" style={{fontSize: 10.5, background: 'var(--iridescent)', WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent', fontWeight: 600, letterSpacing: '0.08em'}}>{a.agent.toUpperCase()}</span></div>
            <div className="c mono tnum" style={{fontSize: 12}}>{a.runs.toLocaleString()}</div>
            <div className="c mono" style={{fontSize: 12, color: a.success >= 90 ? 'var(--good)' : a.success >= 75 ? 'var(--cyan)' : 'var(--warn)'}}>{a.success}%</div>
            <div className="c mono" style={{fontSize: 12, color: a.errors > 0 ? 'var(--danger)' : 'var(--text-faint)'}}>{a.errors}</div>
            <div className="c">
              <button className={`ccc-toggle ${states[a.id] ? 'on' : ''}`} onClick={() => toggleOne(a.id)}>
                <span className="ccc-toggle-knob"/>
              </button>
            </div>
            <div className="c actions">
              <button className="ccc-iconbtn" title="Edit"  onClick={() => onPushToast(`Editor opened · ${a.name}`)}><Icon.Code style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="Clone" onClick={() => onPushToast(`Cloned · ${a.name}`)}><Icon.Plus style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="Logs"  onClick={() => onPushToast(`Logs · ${a.name}`)}><Icon.Book style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="Assign agent" onClick={() => onPushToast(`Agent picker · ${a.name}`)}><Icon.Agent style={{width: 12, height: 12}}/></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Expose the first three tabs + buildStages — control center + remaining tabs live in funnel-detail-2.jsx
window.buildStages = buildStages;
window.FunnelOverviewTab = FunnelOverviewTab;
window.FunnelStagesTab = FunnelStagesTab;
window.FunnelAutomationsTab = FunnelAutomationsTab;
