// Flow components for /automatizaciones page
const { useState: useStateF, useEffect: useEffectF, useRef: useRefF, useContext: useContextF } = React;

// ── Scenario context ──────────────────────────────────────────────────────────
const ScenarioCtx = React.createContext(null);

const SCENARIOS = {
  pasteleria: {
    label: 'Pastelería', emoji: '🎂',
    persona: 'Ana', apellido: 'Robles', negocio: 'La Lola Pasteles',
    email: 'ana@lalolapasteles.mx', origen: 'Instagram',
    servicio: 'pedidos personalizados', monto: '$3,200 MXN', plan: 'Catálogo + WA',
    tagline: 'Ana tiene una pastelería. Recibe pedidos por Instagram pero los pierde entre mensajes.',
  },
  consultora: {
    label: 'Consultora', emoji: '📊',
    persona: 'Roberto', apellido: 'Sáenz', negocio: 'Sáenz Consultoría',
    email: 'rsaenz@saenzconsulting.mx', origen: 'LinkedIn',
    servicio: 'diagnóstico organizacional', monto: '$22,000 MXN', plan: 'Plan Pro',
    tagline: 'Roberto dirige una consultora. Cada lead perdido cuesta más que su sitio web.',
  },
  musico: {
    label: 'Músico', emoji: '🎵',
    persona: 'Valeria', apellido: 'Cruz', negocio: 'Valeria Cruz · Música',
    email: 'val@valeriacruz.mx', origen: 'TikTok',
    servicio: 'presentaciones y clases', monto: '$4,800 MXN', plan: 'Landing Artista',
    tagline: 'Valeria da clases y toca en eventos. Sus fans no saben dónde contratarla.',
  },
  ecommerce: {
    label: 'E-commerce', emoji: '🛍️',
    persona: 'Diego', apellido: 'Montoya', negocio: 'Montoya Artesanías',
    email: 'diego@montoyaart.mx', origen: 'Web',
    servicio: 'catálogo artesanal online', monto: '$8,500 MXN', plan: 'Tienda + Flows',
    tagline: 'Diego vende artesanías. Procesa pedidos a mano en un Excel que ya no aguanta.',
  },
};

function ScenarioPicker({ active, onChange }) {
  return (
    <div className="mb-2">
      <div className="text-[11px] font-mono uppercase tracking-widest text-muted mb-3">
        Elige tu caso de negocio — los datos cambian en todos los flujos
      </div>
      <div className="flex flex-wrap gap-2">
        {Object.entries(SCENARIOS).map(([key, s]) => (
          <button
            key={key}
            onClick={() => onChange(key)}
            className="px-4 py-2 rounded-full text-sm font-medium transition-all duration-200"
            style={{
              background: active === key ? 'var(--accent-soft)' : 'rgba(255,255,255,0.03)',
              border: '0.5px solid ' + (active === key ? 'var(--accent)' : 'var(--border)'),
              color: active === key ? 'var(--accent)' : 'var(--text)',
              transform: active === key ? 'scale(1.03)' : 'scale(1)',
            }}
          >
            {s.emoji} {s.label}
          </button>
        ))}
      </div>
    </div>
  );
}

// ── FlowIcon dict ─────────────────────────────────────────────────────────────
const FlowIcon = {
  form:    (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>,
  webhook: (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M13 2L4 14h7l-1 8 9-12h-7l1-8z"/></svg>,
  filter:  (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 4h18l-7 9v7l-4-2V13L3 4z"/></svg>,
  chat:    (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/><path d="M8 10h8M8 14h5"/></svg>,
  bell:    (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 0 1-3.46 0"/></svg>,
  sheets:  (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18"/></svg>,
  rowAdd:  (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M3 12h18M3 6h18M3 18h10M17 15v6M14 18h6"/></svg>,
  workflow:(p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="3" width="6" height="6" rx="1"/><rect x="15" y="15" width="6" height="6" rx="1"/><path d="M9 6h6a3 3 0 0 1 3 3v6"/></svg>,
  clock:   (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>,
  doc:     (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z"/><path d="M8 13h8M8 17h6"/></svg>,
  send:    (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M22 2L11 13M22 2L15 22l-4-9-9-4 20-7z"/></svg>,
  person:  (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8z"/></svg>,
  star:    (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>,
  mail:    (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" {...p}><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 7l9 7 9-7"/></svg>,
  check:   (p) => <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" {...p}><path d="M5 12l5 5L20 7"/></svg>,
};

// ── Node types ────────────────────────────────────────────────────────────────
const NODE_TYPES = {
  trigger: { color: '#60A5FA', bg: 'rgba(96,165,250,0.12)',  border: 'rgba(96,165,250,0.4)',  label: 'TRIGGER' },
  process: { color: '#A78BFA', bg: 'rgba(167,139,250,0.12)', border: 'rgba(167,139,250,0.4)', label: 'PROCESO' },
  api:     { color: '#34D399', bg: 'rgba(52,211,153,0.12)',  border: 'rgba(52,211,153,0.4)',  label: 'API' },
  output:  { color: '#F59E0B', bg: 'rgba(245,158,11,0.12)',  border: 'rgba(245,158,11,0.4)',  label: 'OUTPUT' },
};

function Node({ label, active, type = 'process', sub, icon: IconComp }) {
  const t = NODE_TYPES[type];
  return (
    <div
      className="relative shrink-0 px-3 py-3 rounded-xl text-center transition-all duration-300"
      style={{
        background: active ? t.bg : 'var(--bg-surface)',
        border: '0.5px solid ' + (active ? t.border : 'var(--border)'),
        minWidth: 112,
        transform: active ? 'translateY(-2px)' : 'none',
        boxShadow: active ? `0 8px 20px ${t.bg}` : 'none',
      }}
    >
      {IconComp && (
        <div className="flex justify-center mb-1.5" style={{ color: active ? t.color : 'var(--text-muted)' }}>
          <IconComp width="16" height="16"/>
        </div>
      )}
      <div className="text-[9px] font-mono uppercase tracking-widest mb-0.5" style={{ color: active ? t.color : 'var(--text-muted)' }}>
        {t.label}
      </div>
      <div className="text-[12px] font-semibold leading-tight" style={{ color: active ? t.color : 'var(--text)' }}>
        {label}
      </div>
      {sub && (
        <div className="text-[10px] font-mono mt-0.5" style={{ color: active ? t.color : 'var(--text-muted)', opacity: 0.8 }}>
          {sub}
        </div>
      )}
      {active && (
        <div className="absolute inset-0 rounded-xl node-land pointer-events-none" style={{ border: '0.5px solid ' + t.border }}/>
      )}
    </div>
  );
}

function Connector({ active }) {
  return (
    <div className="relative h-px flex-1 min-w-[16px] mx-1" style={{ background: 'var(--border)' }}>
      <div
        className="absolute inset-y-0 left-0 transition-all duration-500"
        style={{
          width: active ? '100%' : '0%',
          background: 'linear-gradient(90deg, transparent, var(--accent))',
          boxShadow: active ? '0 0 10px rgba(167,139,250,0.5)' : 'none',
          height: 1,
        }}
      />
      {active && (
        <div className="absolute -top-[3px] w-1.5 h-1.5 rounded-full" style={{ background: 'var(--accent)', right: 0, boxShadow: '0 0 6px var(--accent)' }}/>
      )}
    </div>
  );
}

// ── Hooks ─────────────────────────────────────────────────────────────────────
function useFlowRunner(stepCount) {
  const [step, setStep] = useStateF(-1);
  const timers = useRefF([]);
  const run = () => {
    timers.current.forEach(clearTimeout);
    timers.current = [];
    setStep(0);
    for (let i = 1; i <= stepCount; i++) {
      timers.current.push(setTimeout(() => setStep(i), i * 700));
    }
  };
  const reset = () => { timers.current.forEach(clearTimeout); setStep(-1); };
  useEffectF(() => () => timers.current.forEach(clearTimeout), []);
  return { step, run, reset, running: step >= 0 && step <= stepCount, done: step > stepCount };
}

function useResultPhases(done, count, interval) {
  var ms = interval || 220;
  const [phase, setPhase] = useStateF(0);
  useEffectF(() => {
    if (!done) { setPhase(0); return; }
    var ids = [];
    for (var n = 1; n <= count; n++) {
      (function(nn) {
        ids.push(setTimeout(() => setPhase(nn), nn * ms));
      })(n);
    }
    return () => ids.forEach(clearTimeout);
  }, [done]);
  return phase;
}

// ── FlowShell ─────────────────────────────────────────────────────────────────
function FlowShell({ title, tag, nodes, result, onRun, step, done, onReset, narrative }) {
  const total = nodes.length;
  const progress = step < 0 ? 0 : Math.min(((step + 1) / total) * 100, 100);
  const activeLabel = step >= 0 && step < total ? nodes[step].label : null;

  return (
    <div className="card !p-0 overflow-hidden">
      {/* Header */}
      <div className="p-5 md:p-6 flex items-center justify-between gap-4 flex-wrap">
        <div>
          <div className="badge mb-2">{tag}</div>
          <h3 className="text-xl md:text-2xl font-bold tracking-tight">{title}</h3>
        </div>
        <div className="flex gap-2">
          {done && <button onClick={onReset} className="btn-secondary !py-2 !px-4 text-sm">Reiniciar</button>}
          <button onClick={onRun} className="btn-primary !py-2.5 !px-5 text-sm">
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
            {done ? 'Volver a simular' : 'Simular flujo'}
          </button>
        </div>
      </div>

      {/* Narrative */}
      {narrative && (
        <div className="mx-5 md:mx-6 mb-4 px-4 py-3 rounded-lg text-[13px] leading-relaxed" style={{ background: 'rgba(167,139,250,0.04)', borderLeft: '2px solid var(--accent)', color: 'var(--text-muted)' }}>
          {narrative}
        </div>
      )}

      {/* Progress bar */}
      <div className="h-px mx-5 md:mx-6 mb-1 relative" style={{ background: 'var(--border)' }}>
        <div
          className="absolute inset-y-0 left-0 transition-all duration-700"
          style={{
            width: progress + '%',
            background: 'linear-gradient(90deg, var(--accent), rgba(167,139,250,0.5))',
            boxShadow: progress > 0 ? '0 0 8px rgba(167,139,250,0.4)' : 'none',
          }}
        />
      </div>

      {/* Nodes */}
      <div className="px-5 md:px-6 pb-1">
        <div className="overflow-x-auto scrollbar-thin pb-2">
          <div className="flex items-center min-w-max py-4">
            {nodes.map((n, i) => (
              <React.Fragment key={i}>
                <Node label={n.label} sub={n.sub} active={step >= i} type={n.type} icon={n.icon}/>
                {i < nodes.length - 1 && <Connector active={step > i}/>}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      {/* Result area */}
      <div className="px-5 md:px-6 pb-5 min-h-[160px]">
        {done && result}
        {!done && step < 0 && (
          <div className="text-[11px] text-muted font-mono uppercase tracking-widest opacity-50 text-center py-10">
            · presiona simular para ver el resultado ·
          </div>
        )}
        {!done && step >= 0 && (
          <div className="flex flex-col items-center gap-3 py-8">
            <div className="flex items-center gap-1.5">
              {[0, 1, 2].map(function(i) {
                return (
                  <div key={i} className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--accent)', animation: 'pulseDot 0.8s ' + (i * 0.2) + 's ease-in-out infinite' }}/>
                );
              })}
            </div>
            {activeLabel && (
              <div className="text-[11px] font-mono uppercase tracking-widest text-muted anim-fadeUp">
                ejecutando · {activeLabel}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Flow 1: WhatsApp Lead ─────────────────────────────────────────────────────
function FlowWhatsApp() {
  const sc = useContextF(ScenarioCtx) || SCENARIOS.pasteleria;
  const nodes = [
    { label: 'Formulario',    type: 'trigger', icon: FlowIcon.form },
    { label: 'Webhook',       sub: 'POST /lead', type: 'process', icon: FlowIcon.webhook },
    { label: 'Filtro',        sub: 'spam check', type: 'process', icon: FlowIcon.filter },
    { label: 'WhatsApp API',  type: 'api',     icon: FlowIcon.chat },
    { label: 'Notificación',  type: 'output',  icon: FlowIcon.bell },
  ];
  const { step, run, done, reset } = useFlowRunner(nodes.length - 1);
  const phase = useResultPhases(done, 3);
  const [timerSec, setTimerSec] = useStateF(0);

  useEffectF(() => {
    if (phase < 3) { setTimerSec(0); return; }
    const id = setInterval(() => setTimerSec(s => s + 1), 1000);
    return () => clearInterval(id);
  }, [phase]);

  const initials = sc.persona.charAt(0) + sc.apellido.charAt(0);

  const result = (
    <div className="anim-fadeUp">
      <div className="text-[10px] text-muted font-mono uppercase tracking-widest mb-3 text-center">Resultado en el teléfono de {sc.persona}</div>
      {/* Phone mockup */}
      <div className="phone-frame">
        {/* Notch */}
        <div className="phone-notch"><div className="phone-notch-pill"/></div>
        {/* Status bar */}
        <div className="phone-status" style={{ color: '#E9EDEF' }}>
          <span>9:41</span>
          <span>▲ ● ▓</span>
        </div>
        {/* WA screen */}
        <div className="phone-screen" style={{ background: '#0D1117' }}>
          {/* WA Chat header */}
          <div className="flex items-center gap-2 px-3 py-2.5" style={{ background: '#075E54' }}>
            <div className="text-white text-[14px] opacity-80">←</div>
            <div className="w-7 h-7 rounded-full grid place-items-center text-[10px] font-bold shrink-0" style={{ background: 'rgba(255,255,255,0.2)', color: '#fff' }}>
              {initials}
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[12px] font-semibold text-white truncate">{sc.negocio}</div>
              {phase >= 1 && (
                <div className="text-[10px] anim-fadeUp" style={{ color: 'rgba(255,255,255,0.7)' }}>en línea</div>
              )}
            </div>
            <div className="flex gap-3 opacity-70">
              <span className="text-white text-[13px]">⊘</span>
              <span className="text-white text-[13px]">⋮</span>
            </div>
          </div>

          {/* WA chat background pattern */}
          <div className="px-3 py-4 space-y-3" style={{ minHeight: 260, background: '#0D1117' }}>
            {/* Date separator */}
            <div className="flex items-center justify-center">
              <div className="text-[9px] px-2 py-0.5 rounded-full" style={{ background: 'rgba(255,255,255,0.08)', color: 'rgba(233,237,239,0.6)' }}>
                HOY
              </div>
            </div>

            {/* Incoming bubble — system bot */}
            {phase >= 1 && (
              <div className="flex justify-start anim-fadeUp">
                <div className="rounded-lg rounded-tl-sm px-3 py-2 max-w-[85%]" style={{ background: '#1F2C34' }}>
                  <div className="text-[11px] font-semibold mb-1" style={{ color: '#25D366' }}>
                    🚀 Nuevo lead
                  </div>
                  {phase >= 2 && (
                    <div className="anim-fadeUp space-y-0.5">
                      <div className="text-[12px] font-semibold shimmer-text" style={{ color: '#E9EDEF' }}>
                        {sc.persona} {sc.apellido}
                      </div>
                      <div className="text-[10px]" style={{ color: 'rgba(233,237,239,0.55)' }}>
                        {sc.origen} · {sc.email}
                      </div>
                    </div>
                  )}
                  {phase >= 3 && (
                    <div className="anim-fadeUp mt-2 pt-2" style={{ borderTop: '0.5px solid rgba(255,255,255,0.08)' }}>
                      <div className="text-[11px] italic" style={{ color: 'rgba(233,237,239,0.75)' }}>
                        "Hola, me interesa {sc.servicio}."
                      </div>
                      <div className="flex items-center justify-between mt-1.5">
                        <span className="text-[9px]" style={{ color: 'rgba(233,237,239,0.35)' }}>hace {timerSec}s</span>
                        <span className="text-[11px]" style={{ color: '#53BDEB' }}>✓✓</span>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* WA input bar */}
          <div className="flex items-center gap-2 px-3 py-2" style={{ background: '#1F2C34', borderTop: '0.5px solid rgba(255,255,255,0.06)' }}>
            <div className="flex-1 rounded-full px-3 py-1.5 text-[10px]" style={{ background: '#2A3942', color: 'rgba(233,237,239,0.4)' }}>
              Mensaje
            </div>
            <div className="w-7 h-7 rounded-full grid place-items-center" style={{ background: '#25D366' }}>
              <span className="text-white text-[11px]">▶</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );

  return (
    <FlowShell
      title="Lead → WhatsApp en tiempo real"
      tag="Flujo 01"
      nodes={nodes}
      step={step} done={done} onRun={run} onReset={reset}
      result={result}
      narrative={sc.tagline + ' Este flujo captura el contacto y le avisa al instante.'}
    />
  );
}

// ── Flow 2: Sheets CRM ────────────────────────────────────────────────────────
function FlowSheets() {
  const sc = useContextF(ScenarioCtx) || SCENARIOS.pasteleria;
  const nodes = [
    { label: 'Formulario',     type: 'trigger', icon: FlowIcon.form },
    { label: 'n8n',            sub: 'workflow',  type: 'process', icon: FlowIcon.workflow },
    { label: 'Google Sheets',  type: 'api',     icon: FlowIcon.sheets },
    { label: 'Fila agregada',  type: 'process', icon: FlowIcon.rowAdd },
    { label: 'Email bienvenida', type: 'output', icon: FlowIcon.mail },
  ];
  const { step, run, done, reset } = useFlowRunner(nodes.length - 1);
  const phase = useResultPhases(done, 4);
  const initials = sc.persona.charAt(0) + sc.apellido.charAt(0);

  const result = (
    <div className="anim-fadeUp">
      <div className="text-[10px] text-muted font-mono uppercase tracking-widest mb-3 text-center">Resultado en Google Sheets · {sc.negocio}</div>
      <div className="laptop-frame">
        <div className="laptop-screen-wrap">
          <div className="laptop-cam-bar"><div className="laptop-cam-dot"/></div>
          {/* Browser bar */}
          {phase >= 1 && (
            <div className="flex items-center gap-2 px-3 py-1.5 anim-fadeUp" style={{ background: '#1e6837', borderBottom: '1px solid rgba(0,0,0,0.2)' }}>
              <div className="flex gap-1 shrink-0">
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#ff5f57' }}/>
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#febc2e' }}/>
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#28c840' }}/>
              </div>
              <div className="flex-1 bg-white/10 rounded px-2 py-0.5 text-[9px] font-mono" style={{ color: 'rgba(255,255,255,0.8)' }}>
                docs.google.com/spreadsheets — Leads · {sc.negocio}
              </div>
            </div>
          )}
          {/* Sheets menu bar */}
          {phase >= 1 && (
            <div className="flex items-center gap-3 px-3 py-1 anim-fadeUp" style={{ background: '#fff', borderBottom: '1px solid #e0e0e0' }}>
              <span className="text-[8px] font-bold" style={{ color: '#0f9d58' }}>■</span>
              {['Archivo','Editar','Ver','Insertar','Formato','Datos'].map(m => (
                <span key={m} className="text-[8px]" style={{ color: '#3c4043' }}>{m}</span>
              ))}
            </div>
          )}
          {/* Spreadsheet */}
          <div style={{ background: '#fff', minHeight: 180 }}>
            {/* Column headers */}
            {phase >= 2 && (
              <div className="grid anim-fadeUp" style={{ gridTemplateColumns: '32px 1fr 1.4fr 60px 80px', background: '#f8f9fa', borderBottom: '1px solid #e0e0e0' }}>
                {['#','Nombre','Email','Origen','Estado'].map((h, i) => (
                  <div key={h} className="px-2 py-1 text-[9px] font-semibold" style={{ color: '#3c4043', borderRight: '1px solid #e0e0e0' }}>{h}</div>
                ))}
              </div>
            )}
            {/* Old rows */}
            {phase >= 2 && [
              ['012','Andrea M.','andrea@studio.mx','IG','✓'],
              ['013','Luis R.','luis@pyme.com','Web','✓'],
            ].map((r, i) => (
              <div key={i} className="grid anim-fadeUp" style={{ gridTemplateColumns: '32px 1fr 1.4fr 60px 80px', borderBottom: '1px solid #e8eaed', animationDelay: (i * 60) + 'ms' }}>
                {r.map((cell, ci) => (
                  <div key={ci} className="px-2 py-1.5 text-[9px]" style={{ color: '#5f6368', borderRight: '1px solid #e8eaed' }}>{cell}</div>
                ))}
              </div>
            ))}
            {/* New row */}
            {phase >= 3 && (
              <div className="grid row-in" style={{ gridTemplateColumns: '32px 1fr 1.4fr 60px 80px', borderBottom: '1px solid #c8e6c9', background: 'rgba(15,157,88,0.08)' }}>
                <div className="px-2 py-1.5 text-[9px] font-mono" style={{ color: '#0f9d58', borderRight: '1px solid #c8e6c9' }}>014</div>
                <div className="px-2 py-1.5 text-[9px] font-semibold" style={{ color: '#202124', borderRight: '1px solid #c8e6c9' }}>{sc.persona} {sc.apellido.charAt(0)}.</div>
                <div className="px-2 py-1.5 text-[9px] font-mono" style={{ color: '#5f6368', borderRight: '1px solid #c8e6c9' }}>{sc.email}</div>
                <div className="px-2 py-1.5 text-[9px]" style={{ color: '#5f6368', borderRight: '1px solid #c8e6c9' }}>{sc.origen}</div>
                <div className="px-2 py-1.5 text-[9px] flex items-center gap-1">
                  {phase >= 4 ? (
                    <span className="flex items-center gap-1 text-[9px] font-semibold" style={{ color: '#0f9d58' }}>
                      <span>✓</span> enviado
                    </span>
                  ) : (
                    <span className="flex items-center gap-1 text-[9px] font-semibold" style={{ color: '#1a73e8' }}>
                      <span className="w-1.5 h-1.5 rounded-full pulse-dot" style={{ background: '#1a73e8', display: 'inline-block' }}/> NUEVO
                    </span>
                  )}
                </div>
              </div>
            )}
          </div>
        </div>
        <div className="laptop-base"/>
        <div className="laptop-foot"/>
      </div>
    </div>
  );

  return (
    <FlowShell
      title="Captura → Sheets → Email automático"
      tag="Flujo 02"
      nodes={nodes}
      step={step} done={done} onRun={run} onReset={reset}
      result={result}
      narrative={'Cada contacto de ' + sc.negocio + ' queda registrado automáticamente en Google Sheets. Y ' + sc.persona + ' recibe un correo de bienvenida sin tocar nada.'}
    />
  );
}

// ── Flow 3: Email ─────────────────────────────────────────────────────────────
function FlowEmail() {
  const sc = useContextF(ScenarioCtx) || SCENARIOS.pasteleria;
  const nodes = [
    { label: 'Formulario', type: 'trigger', icon: FlowIcon.form },
    { label: 'Trigger',    sub: 'on submit', type: 'process', icon: FlowIcon.clock },
    { label: 'Plantilla',  type: 'process', icon: FlowIcon.doc },
    { label: 'Enviado',    type: 'output',  icon: FlowIcon.send },
  ];
  const { step, run, done, reset } = useFlowRunner(nodes.length - 1);
  const phase = useResultPhases(done, 3);

  const result = (
    <div className="anim-fadeUp">
      <div className="text-[10px] text-muted font-mono uppercase tracking-widest mb-3 text-center">Resultado en Gmail · {sc.email}</div>
      <div className="laptop-frame">
        <div className="laptop-screen-wrap">
          <div className="laptop-cam-bar"><div className="laptop-cam-dot"/></div>
          {/* Browser bar */}
          {phase >= 1 && (
            <div className="flex items-center gap-2 px-3 py-1.5 anim-fadeUp" style={{ background: '#c5221f', borderBottom: '1px solid rgba(0,0,0,0.2)' }}>
              <div className="flex gap-1 shrink-0">
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#ff5f57' }}/>
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#febc2e' }}/>
                <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#28c840' }}/>
              </div>
              <div className="flex-1 bg-white/10 rounded px-2 py-0.5 text-[9px] font-mono" style={{ color: 'rgba(255,255,255,0.8)' }}>
                mail.google.com — Bandeja de entrada
              </div>
            </div>
          )}
          {/* Gmail UI */}
          {phase >= 1 && (
            <div className="flex anim-fadeUp" style={{ background: '#fff', minHeight: 200 }}>
              {/* Sidebar */}
              <div className="shrink-0 py-2 px-2" style={{ width: 88, background: '#f6f8fc', borderRight: '1px solid #e0e0e0' }}>
                <div className="text-[8px] font-bold mb-2 px-1" style={{ color: '#ea4335' }}>M Gmail</div>
                <div className="text-[7px] font-semibold px-1 py-1 rounded mb-0.5" style={{ background: '#d3e3fd', color: '#0b57d0' }}>📥 Recibidos</div>
                {['Enviados','Borradores','Más'].map(s => (
                  <div key={s} className="text-[7px] px-1 py-0.5 mb-0.5" style={{ color: '#444746' }}>{s}</div>
                ))}
              </div>
              {/* Main panel */}
              <div className="flex-1 flex flex-col">
                {/* Inbox header */}
                <div className="px-3 py-1.5" style={{ borderBottom: '1px solid #e0e0e0' }}>
                  <div className="text-[9px] font-semibold" style={{ color: '#202124' }}>Recibidos</div>
                </div>
                {/* Email row in inbox */}
                {phase >= 2 && (
                  <div className="flex items-start gap-2 px-3 py-2 anim-fadeUp" style={{ background: '#fff', borderBottom: '1px solid #f1f3f4' }}>
                    <div className="w-1.5 h-1.5 rounded-full shrink-0 mt-1.5" style={{ background: '#1a73e8' }}/>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between">
                        <span className="text-[9px] font-bold" style={{ color: '#202124' }}>Cristian Salazar</span>
                        <span className="text-[8px]" style={{ color: '#5f6368' }}>10:14 am</span>
                      </div>
                      <div className="text-[8px] font-semibold" style={{ color: '#202124' }}>Gracias por tu interés, {sc.persona} 👋</div>
                      <div className="text-[8px] truncate" style={{ color: '#5f6368' }}>Recibimos tu consulta sobre {sc.servicio}...</div>
                    </div>
                  </div>
                )}
                {/* Open email panel */}
                {phase >= 3 && (
                  <div className="px-3 py-2.5 anim-fadeUp flex-1" style={{ background: '#fff' }}>
                    <div className="text-[10px] font-bold mb-1" style={{ color: '#202124' }}>Gracias por tu interés, {sc.persona} 👋</div>
                    <div className="text-[8px] mb-2" style={{ color: '#5f6368' }}>De: hola@cristiansalazar.com.mx &nbsp;·&nbsp; Para: {sc.email}</div>
                    <div className="text-[9px] leading-relaxed mb-3" style={{ color: '#3c4043' }}>
                      Recibimos tu consulta sobre <strong>{sc.servicio}</strong> en {sc.negocio}. En las próximas 24 horas te enviamos una propuesta personalizada.
                    </div>
                    <div className="flex gap-1.5 flex-wrap">
                      {['Ver propuesta','Agendar llamada'].map(btn => (
                        <span key={btn} className="text-[8px] px-2 py-0.5 rounded-full font-medium" style={{ background: '#1a73e8', color: '#fff' }}>{btn}</span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
          {phase < 1 && <div style={{ background: '#fff', minHeight: 200 }}/>}
        </div>
        <div className="laptop-base"/>
        <div className="laptop-foot"/>
      </div>
    </div>
  );

  return (
    <FlowShell
      title="Correo automático personalizado"
      tag="Flujo 03"
      nodes={nodes}
      step={step} done={done} onRun={run} onReset={reset}
      result={result}
      narrative={'Cuando alguien llena el formulario de ' + sc.negocio + ', recibe un correo personalizado en segundos. ' + sc.persona + ' no escribe uno solo a mano.'}
    />
  );
}

// ── Flow 4: CRM Kanban ────────────────────────────────────────────────────────
const GHOST_CARDS = {
  0: [{ name: 'Carlos V.',   tag: 'Web',     amount: '$7k' }],
  1: [{ name: 'Fernanda L.', tag: 'Starter', amount: '$7k' }, { name: 'Jorge M.', tag: 'Web', amount: '$7k' }],
  2: [{ name: 'Sofía R.',    tag: 'Pro',     amount: '$18k' }],
  3: [{ name: 'Rodrigo P.',  tag: 'Elite',   amount: '$35k' }, { name: 'Luz M.', tag: 'Pro', amount: '$18k' }],
  4: [{ name: 'Andrea S.',   tag: 'Starter', amount: '$7k' }],
};
const COL_TIMESTAMPS  = ['ahora mismo', 'hace 1h', 'ayer', 'hace 3 días', 'esta semana'];
const COL_BADGES      = ['Nuevo', 'Calificado', 'Activo', 'En propuesta', '🎉 Ganado'];
const COL_BADGE_BG    = ['rgba(96,165,250,0.15)', 'rgba(167,139,250,0.15)', 'rgba(52,211,153,0.15)', 'rgba(245,158,11,0.15)', 'rgba(52,211,153,0.25)'];
const COL_BADGE_COLOR = ['#60A5FA', '#A78BFA', '#34D399', '#F59E0B', '#34D399'];

function FlowKanban() {
  const sc = useContextF(ScenarioCtx) || SCENARIOS.pasteleria;
  const nodes = [
    { label: 'Lead nuevo',   type: 'trigger', icon: FlowIcon.person },
    { label: 'Calificación', type: 'process', icon: FlowIcon.star },
    { label: 'Seguimiento',  type: 'process', icon: FlowIcon.clock },
    { label: 'Propuesta',    type: 'process', icon: FlowIcon.doc },
    { label: 'Cerrado',      type: 'output',  icon: FlowIcon.check },
  ];
  const { step, run, done, reset } = useFlowRunner(nodes.length - 1);
  const cols = ['Nuevo', 'Calificado', 'Seguimiento', 'Propuesta', 'Cerrado'];
  const pos = done ? 4 : Math.max(0, Math.min(step, 4));
  const initials = sc.persona.charAt(0) + sc.apellido.charAt(0);

  const result = (
    <div className="anim-fadeUp">
      <div className="text-[10px] text-muted font-mono uppercase tracking-widest mb-3 text-center">CRM Pipeline · {sc.negocio}</div>
      <div className="laptop-frame">
        <div className="laptop-screen-wrap">
          <div className="laptop-cam-bar"><div className="laptop-cam-dot"/></div>
          {/* Browser bar */}
          <div className="flex items-center gap-2 px-3 py-1.5" style={{ background: '#1a1a2e', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
            <div className="flex gap-1 shrink-0">
              <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#ff5f57' }}/>
              <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#febc2e' }}/>
              <div className="w-2.5 h-2.5 rounded-full" style={{ background: '#28c840' }}/>
            </div>
            <div className="flex-1 bg-white/5 rounded px-2 py-0.5 text-[9px] font-mono" style={{ color: 'rgba(255,255,255,0.5)' }}>
              CRM Pipeline — {sc.negocio}
            </div>
          </div>
          {/* App header */}
          <div className="flex items-center gap-3 px-3 py-2" style={{ background: '#13111f', borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
            <span className="text-[9px] font-semibold" style={{ color: 'var(--accent)' }}>Pipeline</span>
            <span className="text-[9px]" style={{ color: 'rgba(255,255,255,0.3)' }}>Tabla</span>
            <span className="text-[9px]" style={{ color: 'rgba(255,255,255,0.3)' }}>Calendario</span>
          </div>
          {/* Kanban board */}
          <div className="p-2" style={{ background: '#0f0d1a', minHeight: 180 }}>
            <div className="grid gap-1.5" style={{ gridTemplateColumns: 'repeat(5, 1fr)' }}>
              {cols.map((c, i) => {
                const ghosts = GHOST_CARDS[i] || [];
                const count = ghosts.length + (i === pos ? 1 : 0);
                return (
                  <div
                    key={c}
                    className="rounded-lg p-1.5"
                    style={{
                      background: 'rgba(255,255,255,0.02)',
                      border: '0.5px solid ' + (i === pos ? 'rgba(167,139,250,0.35)' : 'rgba(255,255,255,0.06)'),
                      minHeight: 120,
                    }}
                  >
                    <div className="flex items-center justify-between mb-1.5">
                      <div className="text-[8px] font-mono uppercase tracking-widest truncate" style={{ color: COL_BADGE_COLOR[i] }}>{c}</div>
                      <div className="text-[8px] font-mono px-1 py-0.5 rounded-full shrink-0 ml-1" style={{ background: COL_BADGE_BG[i], color: COL_BADGE_COLOR[i] }}>
                        {count}
                      </div>
                    </div>
                    {i === pos && (
                      <div
                        key={'main-' + pos}
                        className="rounded-md p-1.5 mb-1 card-land"
                        style={{ background: 'var(--bg-surface)', border: '0.5px solid var(--accent)', boxShadow: '0 0 10px rgba(167,139,250,0.15)' }}
                      >
                        <div className="flex items-center gap-1 mb-1">
                          <div className="w-4 h-4 rounded-full grid place-items-center text-[7px] font-bold shrink-0" style={{ background: 'var(--accent-soft)', color: 'var(--accent)' }}>
                            {initials}
                          </div>
                          <div className="text-[9px] font-semibold truncate" style={{ color: 'var(--text)' }}>{sc.persona} {sc.apellido.charAt(0)}.</div>
                        </div>
                        <div className="text-[7px] font-medium px-1.5 py-0.5 rounded-full mb-1 inline-block" style={{ background: COL_BADGE_BG[i], color: COL_BADGE_COLOR[i] }}>
                          {COL_BADGES[i]}
                        </div>
                        <div className="flex items-center justify-between">
                          <div className="text-[8px] font-mono" style={{ color: 'var(--accent)' }}>{sc.monto}</div>
                          <div className="text-[7px] font-mono text-muted">{COL_TIMESTAMPS[i]}</div>
                        </div>
                      </div>
                    )}
                    {ghosts.map((g, gi) => (
                      <div key={gi} className="rounded-md p-1.5 mb-1" style={{ background: 'rgba(255,255,255,0.015)', border: '0.5px solid rgba(255,255,255,0.05)' }}>
                        <div className="text-[9px]" style={{ color: 'rgba(255,255,255,0.3)' }}>{g.name}</div>
                        <div className="flex items-center justify-between mt-0.5">
                          <div className="text-[8px] font-mono" style={{ color: 'rgba(255,255,255,0.2)' }}>{g.tag}</div>
                          <div className="text-[8px] font-mono" style={{ color: 'rgba(255,255,255,0.2)' }}>{g.amount}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        <div className="laptop-base"/>
        <div className="laptop-foot"/>
      </div>
    </div>
  );

  return (
    <FlowShell
      title="CRM Pipeline visual"
      tag="Flujo 04"
      nodes={nodes}
      step={step} done={done} onRun={run} onReset={reset}
      result={result}
      narrative={'El pipeline de ' + sc.persona + ' en ' + sc.negocio + '. Cada lead avanza de etapa y el equipo sabe dónde está cada oportunidad en todo momento.'}
    />
  );
}

Object.assign(window, {
  ScenarioCtx, SCENARIOS, ScenarioPicker,
  FlowWhatsApp, FlowSheets, FlowEmail, FlowKanban,
});
