// ============================================================
// FUNNELS — Grid view + state-driven Control Center handoff
// ============================================================

const FUNNEL_TYPES = {
  lead_gen:     { label: 'Lead Generation',  hue: '#4be8ff' },
  appointment:  { label: 'Appointment',      hue: '#8b6bff' },
  webinar:      { label: 'Webinar',          hue: '#ff7ad9' },
  product:      { label: 'Product',          hue: '#5dffb0' },
  high_ticket:  { label: 'High Ticket',      hue: '#e8c98a' },
  vsl:          { label: 'VSL',              hue: '#ffb14b' },
  membership:   { label: 'Membership',       hue: '#4be8ff' },
  ecommerce:    { label: 'E-commerce',       hue: '#ff7ad9' },
  local:        { label: 'Local Business',   hue: '#8b6bff' },
  retargeting:  { label: 'Retargeting',      hue: '#5dffb0' }
};

const FUNNEL_STATUS = {
  live:        { label: 'LIVE',        color: 'var(--cyan)',     bg: 'rgba(75,232,255,0.08)',  border: 'rgba(75,232,255,0.3)' },
  optimizing:  { label: 'OPTIMIZING',  color: 'var(--violet)',   bg: 'rgba(139,107,255,0.08)', border: 'rgba(139,107,255,0.3)' },
  testing:     { label: 'TESTING',     color: 'var(--magenta)',  bg: 'rgba(255,122,217,0.08)', border: 'rgba(255,122,217,0.3)' },
  warning:     { label: 'WARNING',     color: 'var(--warn)',     bg: 'rgba(255,177,75,0.08)',  border: 'rgba(255,177,75,0.3)' },
  offline:     { label: 'OFFLINE',     color: 'var(--text-dim)', bg: 'rgba(255,255,255,0.04)', border: 'rgba(255,255,255,0.1)' }
};

const SOURCE_COLORS = {
  google: '#4285f4', meta: '#0866ff', tiktok: '#000000', linkedin: '#0a66c2',
  organic: '#5dffb0', email: '#4be8ff', sms: '#ff7ad9', affiliate: '#8b6bff',
  referral: '#ffb14b', gmb: '#e8c98a', direct: '#eaecf5', youtube: '#ff5d6e'
};

const FUNNELS = [
  { id: 'fn-belmont-app',    name: 'Belmont Dental · new patient',   type: 'appointment',  status: 'live',       cvr: 18.4, leads: 1284, booked: 236, revenue: 184200, dropoff: 22.4, sources: {google:42, meta:28, tiktok:12, organic:18}, ai: 'active',  updated: '6m'  },
  { id: 'fn-prop-leadgen',   name: 'Acme Property · seller leads',   type: 'lead_gen',     status: 'live',       cvr: 24.1, leads: 814,  booked: 142, revenue: 412000, dropoff: 18.2, sources: {google:38, meta:24, organic:22, sms:16}, ai: 'active',  updated: '14m' },
  { id: 'fn-iyer-webinar',   name: 'Iyer Studio · founders masterclass', type: 'webinar',  status: 'optimizing', cvr: 11.2, leads: 2104, booked: 412, revenue: 84200,  dropoff: 36.4, sources: {meta:48, tiktok:22, organic:18, email:12}, ai: 'tuning',  updated: '2m'  },
  { id: 'fn-demiurge-vsl',   name: 'Demiurge · operator VSL',        type: 'vsl',          status: 'testing',    cvr: 6.4,  leads: 412,  booked: 84,  revenue: 248000, dropoff: 41.8, sources: {meta:62, organic:24, affiliate:14}, ai: 'auditing', updated: 'now' },
  { id: 'fn-demiurge-ht',    name: 'Demiurge · principals tier',     type: 'high_ticket',  status: 'live',       cvr: 3.2,  leads: 184,  booked: 28,  revenue: 412000, dropoff: 28.2, sources: {linkedin:48, organic:32, referral:20}, ai: 'active', updated: '38m' },
  { id: 'fn-ecom-bag',       name: 'Studio Atelier · launch bag',    type: 'ecommerce',    status: 'live',       cvr: 4.8,  leads: 8412, booked: 0,   revenue: 184000, dropoff: 62.4, sources: {meta:48, tiktok:32, google:14, email:6}, ai: 'active', updated: '4m'  },
  { id: 'fn-belmont-recall', name: 'Belmont · 6-month recall',       type: 'retargeting',  status: 'live',       cvr: 32.4, leads: 1804, booked: 584, revenue: 124000, dropoff: 8.2,  sources: {sms:48, email:38, direct:14}, ai: 'active', updated: '12m' },
  { id: 'fn-club-membership',name: 'Atelier · founders membership',  type: 'membership',   status: 'warning',    cvr: 8.4,  leads: 412,  booked: 32,  revenue: 184000, dropoff: 24.2, sources: {organic:62, email:28, referral:10}, ai: 'paused', updated: '4h'  },
  { id: 'fn-local-trades',   name: 'GreenHVAC · Boston · service',   type: 'local',        status: 'optimizing', cvr: 14.2, leads: 612,  booked: 184, revenue: 92000,  dropoff: 18.4, sources: {google:54, organic:24, gmb:22}, ai: 'tuning', updated: '24m' },
  { id: 'fn-wellness-prod',  name: 'Mindset+ · 28-day program',      type: 'product',      status: 'offline',    cvr: 0,    leads: 0,    booked: 0,   revenue: 0,      dropoff: 0,    sources: {}, ai: 'paused', updated: '2d' }
];

// Mini source-mix bar — stacked horizontal
function SourceMix({ sources }) {
  const total = Object.values(sources).reduce((s, v) => s + v, 0);
  if (total === 0) return <div style={{height: 6, background: 'rgba(255,255,255,0.04)', borderRadius: 3}}/>;
  return (
    <div style={{display: 'flex', gap: 2, height: 6, borderRadius: 3, overflow: 'hidden'}}>
      {Object.entries(sources).map(([k, v]) => (
        <div key={k} title={`${k} · ${v}%`} style={{
          width: `${(v / total) * 100}%`,
          background: SOURCE_COLORS[k] || '#8388a8',
          minWidth: 2
        }}/>
      ))}
    </div>
  );
}

function FunnelTinyChart({ funnel }) {
  // Tiny mini-funnel viz showing 5-stage drop
  const stages = [100, 64, 38, 22, funnel.cvr];
  return (
    <svg viewBox="0 0 120 36" preserveAspectRatio="none" style={{width: '100%', height: 36, opacity: 0.85}}>
      <defs>
        <linearGradient id={`fn-grad-${funnel.id}`} x1="0%" x2="100%">
          <stop offset="0%" stopColor={FUNNEL_TYPES[funnel.type].hue} stopOpacity="0.5"/>
          <stop offset="100%" stopColor={FUNNEL_TYPES[funnel.type].hue} stopOpacity="0.1"/>
        </linearGradient>
      </defs>
      {stages.map((v, i) => {
        const x = (i / (stages.length - 1)) * 120;
        const h = (v / 100) * 28 + 2;
        const y = 32 - h;
        return <rect key={i} x={x - 6} y={y} width="12" height={h} rx="1" fill={`url(#fn-grad-${funnel.id})`} stroke={FUNNEL_TYPES[funnel.type].hue} strokeWidth="0.5" strokeOpacity="0.6"/>;
      })}
      {/* Connecting line through tops */}
      <polyline
        points={stages.map((v, i) => `${(i / (stages.length - 1)) * 120},${32 - ((v / 100) * 28 + 2)}`).join(' ')}
        fill="none"
        stroke={FUNNEL_TYPES[funnel.type].hue}
        strokeWidth="1"
        opacity="0.6"
      />
    </svg>
  );
}

function FunnelCard({ funnel, onOpen }) {
  const type = FUNNEL_TYPES[funnel.type];
  const st = FUNNEL_STATUS[funnel.status];
  const aiMap = {
    active:   { label: 'AI · active',   color: 'var(--cyan)' },
    tuning:   { label: 'AI · tuning',   color: 'var(--warn)' },
    auditing: { label: 'AI · auditing', color: 'var(--magenta)' },
    paused:   { label: 'AI · paused',   color: 'var(--text-faint)' }
  };
  const ai = aiMap[funnel.ai] || aiMap.paused;

  return (
    <div
      className="fn-card"
      role="button"
      tabIndex={0}
      onClick={() => onOpen(funnel)}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(funnel); }}}
    >
      <span className="fn-card-sash" style={{background: type.hue}}/>
      <span className="br-bl"></span>
      <span className="br-br"></span>

      <div className="fn-card-hd">
        <div className="fn-card-type" style={{color: type.hue, borderColor: `${type.hue}30`, background: `${type.hue}08`}}>
          {type.label}
        </div>
        <div className="fn-card-status" style={{color: st.color, background: st.bg, borderColor: st.border}}>
          <span className="pip" style={{background: st.color, boxShadow: funnel.status === 'offline' ? 'none' : `0 0 6px ${st.color}`}}/>
          {st.label}
        </div>
      </div>

      <div className="fn-card-name">{funnel.name}</div>

      <div className="fn-card-stats">
        <div className="fn-stat">
          <div className="lbl">CVR</div>
          <div className="val" style={{color: funnel.cvr > 10 ? 'var(--cyan)' : 'var(--text)'}}>{funnel.cvr}<span className="u">%</span></div>
        </div>
        <div className="fn-stat">
          <div className="lbl">Leads</div>
          <div className="val">{funnel.leads.toLocaleString()}</div>
        </div>
        <div className="fn-stat">
          <div className="lbl">Booked</div>
          <div className="val" style={{color: 'var(--violet)'}}>{funnel.booked}</div>
        </div>
        <div className="fn-stat">
          <div className="lbl">Revenue</div>
          <div className="val" style={{color: 'var(--good)'}}>£{(funnel.revenue / 1000).toFixed(0)}<span className="u">k</span></div>
        </div>
      </div>

      <div className="fn-card-chart">
        <FunnelTinyChart funnel={funnel}/>
      </div>

      <div className="fn-card-sources">
        <SourceMix sources={funnel.sources}/>
        <div className="fn-card-source-labels">
          {Object.entries(funnel.sources).slice(0, 3).map(([k, v]) => (
            <span key={k} className="fn-src-chip">
              <span className="dot" style={{background: SOURCE_COLORS[k] || '#8388a8'}}/>
              {k} {v}%
            </span>
          ))}
          {Object.keys(funnel.sources).length > 3 && (
            <span className="fn-src-chip more">+{Object.keys(funnel.sources).length - 3}</span>
          )}
        </div>
      </div>

      <div className="fn-card-foot">
        <div style={{display: 'flex', alignItems: 'center', gap: 14}}>
          <span style={{display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.1em', textTransform: 'uppercase', color: ai.color}}>
            <span style={{width: 5, height: 5, borderRadius: '50%', background: ai.color, boxShadow: funnel.ai === 'paused' ? 'none' : `0 0 6px ${ai.color}`, animation: funnel.ai === 'paused' ? 'none' : 'pulse 1.6s infinite'}}/>
            {ai.label}
          </span>
          <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.1em'}}>
            drop-off <span style={{color: funnel.dropoff > 30 ? 'var(--danger)' : funnel.dropoff > 20 ? 'var(--warn)' : 'var(--text-dim)'}}>{funnel.dropoff}%</span>
          </span>
        </div>
        <span className="fn-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="fn-card-hover-glow"></div>
    </div>
  );
}

function Funnels() {
  const [filter, setFilter] = React.useState('all');
  const [selected, setSelected] = React.useState(null);

  React.useEffect(() => {
    if (!selected) return;
    const onKey = (e) => { if (e.key === 'Escape') setSelected(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [selected]);

  if (selected) {
    return (
      <div className="ch-fade-in">
        <FunnelControlCenter funnel={selected} onBack={() => setSelected(null)}/>
      </div>
    );
  }

  const filtered = filter === 'all' ? FUNNELS : FUNNELS.filter(f => f.status === filter || f.type === filter);
  const total = FUNNELS.length;
  const live = FUNNELS.filter(f => f.status === 'live').length;
  const totalRevenue = FUNNELS.reduce((s, f) => s + f.revenue, 0);
  const totalLeads = FUNNELS.reduce((s, f) => s + f.leads, 0);
  const totalBooked = FUNNELS.reduce((s, f) => s + f.booked, 0);

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Customer acquisition · {live} live · {total} total</div>
          <h1 className="page-title"><em>Funnels</em> <strong>· growth engine</strong></h1>
          <div className="page-sub">Every funnel instrumented end-to-end. Click any to open its control center — stages, automations, traffic, content, analytics, and a full audit trail.</div>
        </div>
        <div className="page-hd-r">
          <div className="segmented">
            {[['all','All'],['live','Live'],['optimizing','Optimizing'],['testing','Testing'],['warning','Warning'],['offline','Offline']].map(([k,l]) => (
              <button key={k} className={filter === k ? 'active' : ''} onClick={() => setFilter(k)}>{l}</button>
            ))}
          </div>
          <button className="btn"><Icon.Filter className="icon"/>Segment</button>
          <button className="btn primary"><Icon.Plus className="icon"/>New funnel</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">Total leads · 30d</div>
          <div className="kpi-val tnum">{totalLeads.toLocaleString()}</div>
          <div className="kpi-meta"><span className="delta up">+18%</span><span className="dim">vs prev period</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Appointments booked</div>
          <div className="kpi-val tnum">{totalBooked.toLocaleString()}</div>
          <div className="kpi-meta"><span className="delta up">+24%</span><span className="dim">recovered by agents · 142</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Pipeline · 30d</div>
          <div className="kpi-val tnum">£{(totalRevenue / 1000).toFixed(0)}<span className="unit">k</span></div>
          <div className="kpi-meta"><span className="delta up">+£412k</span><span className="dim">vs prev</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Funnels needing attention</div>
          <div className="kpi-val tnum" style={{color: 'var(--warn)'}}>{FUNNELS.filter(f => f.status === 'warning' || f.status === 'offline').length}</div>
          <div className="kpi-meta"><span className="dim">1 warning · 1 offline</span></div>
        </div>
      </div>

      <div style={{padding: '0 32px 36px'}}>
        <div className="fn-grid">
          {filtered.map(f => <FunnelCard key={f.id} funnel={f} onOpen={setSelected}/>)}
        </div>
        {filtered.length === 0 && (
          <div className="empty" style={{padding: 80}}>
            <span className="mono faint" style={{letterSpacing: '0.16em', textTransform: 'uppercase'}}>No funnels match this filter</span>
          </div>
        )}
      </div>
    </div>
  );
}

window.Funnels = Funnels;
window.FUNNELS = FUNNELS;
window.FUNNEL_TYPES = FUNNEL_TYPES;
window.FUNNEL_STATUS = FUNNEL_STATUS;
window.SOURCE_COLORS = SOURCE_COLORS;
