/* global React */
// Terminal LatAm — Onboarding bootstrap (Welcome → OAuth → Tracking → CRM → First audit)

const TO_T = window.T_THEME;
const TO_FM = window.T_FM;
const TO_FS = window.T_FS;
const TO_B = window.TerminalBtn;

const PLATFORMS_OB = [
  { id: "meta", name: "Meta Ads", icon: "M", color: "#4267B2", scopes: ["ads_management", "business_management", "pages_read"] },
  { id: "google", name: "Google Ads", icon: "G", color: "#4285F4", scopes: ["adwords", "userinfo.email"] },
  { id: "tiktok", name: "TikTok Ads", icon: "T", color: "#FE2C55", scopes: ["ads.read", "ads.write"] },
  { id: "linkedin", name: "LinkedIn Ads", icon: "L", color: "#0A66C2", scopes: ["r_ads", "r_ads_reporting"] },
];

const ProgressDots = ({ step, total }) => (
  <div style={{ display: "flex", gap: 8, justifyContent: "center", marginTop: 24 }}>
    {Array.from({ length: total }).map((_, i) => (
      <span key={i} style={{
        width: i === step ? 24 : 8, height: 8, borderRadius: 99,
        background: i < step ? TO_T.green : i === step ? TO_T.amber : TO_T.line,
        transition: "all 0.3s",
      }} />
    ))}
  </div>
);

const StepHeader = ({ tag, title, sub }) => (
  <>
    <div style={{ fontFamily: TO_FM, fontSize: 11, color: TO_T.amber, letterSpacing: "0.18em", marginBottom: 12 }}>{tag}</div>
    <div style={{ fontFamily: TO_FS, fontSize: 28, fontWeight: 600, color: TO_T.ink, marginBottom: 8, lineHeight: 1.2 }}>{title}</div>
    {sub && <div style={{ fontSize: 13, color: TO_T.mute, lineHeight: 1.6, marginBottom: 24 }}>{sub}</div>}
  </>
);

const Welcome = ({ onNext }) => (
  <div style={{ textAlign: "center" }}>
    <div style={{ fontFamily: TO_FM, fontSize: 11, color: TO_T.amber, letterSpacing: "0.2em", marginBottom: 24 }}>// SETUP · MediaAgent v0.4 · LATAM</div>
    <div style={{ fontFamily: TO_FS, fontSize: 38, fontWeight: 600, color: TO_T.ink, marginBottom: 16, lineHeight: 1.15 }}>
      Bienvenido. Vamos a conectar tu primera cuenta.
    </div>
    <div style={{ fontSize: 14, color: TO_T.mute, lineHeight: 1.7, maxWidth: 540, margin: "0 auto 32px" }}>
      4 pasos · ~15 min. El agente necesita ver tus <span style={{ color: TO_T.cyan }}>plataformas</span>, tu <span style={{ color: TO_T.cyan }}>tracking</span> y opcionalmente tu <span style={{ color: TO_T.cyan }}>CRM</span> antes de auditar.
    </div>
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, maxWidth: 600, margin: "0 auto 32px", fontSize: 11 }}>
      {[["1","platforms"],["2","tracking"],["3","CRM · opt"],["4","first audit"]].map(([n,l]) => (
        <div key={n} style={{ padding: "14px 8px", border: `1px solid ${TO_T.line}`, background: TO_T.surface }}>
          <div style={{ fontFamily: TO_FM, color: TO_T.amber, fontSize: 18 }}>{n}</div>
          <div style={{ color: TO_T.muteDim, marginTop: 4, letterSpacing: "0.08em" }}>{l}</div>
        </div>
      ))}
    </div>
    <button onClick={onNext} style={{
      padding: "16px 32px", background: TO_T.amber, color: TO_T.bg, border: "none",
      fontFamily: TO_FM, fontSize: 13, letterSpacing: "0.18em", fontWeight: 700, cursor: "pointer",
    }}>▶ EMPEZAR · paso 1/4</button>
    <ProgressDots step={0} total={5} />
  </div>
);

const Step1Platforms = ({ onNext, onBack }) => {
  const [states, setStates] = React.useState({});
  const connected = Object.values(states).filter(s => s === "connected").length;

  const connect = (id) => {
    setStates(s => ({ ...s, [id]: "connecting" }));
    setTimeout(() => setStates(s => ({ ...s, [id]: "connected" })), 1400 + Math.random() * 800);
  };

  return (
    <div>
      <StepHeader tag="STEP 1/4 · OAUTH" title="Conecta tus plataformas publicitarias" sub="Selecciona al menos 1. Cada conexión usa scopes mínimos · revocable desde ⚙ Connect en cualquier momento." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        {PLATFORMS_OB.map(p => {
          const st = states[p.id] || "pending";
          const stCol = st === "connected" ? TO_T.green : st === "connecting" ? TO_T.amber : st === "error" ? TO_T.red : TO_T.line;
          return (
            <div key={p.id} style={{ border: `1px solid ${stCol}`, borderLeft: `3px solid ${stCol}`, padding: "16px 18px", background: TO_T.surface, opacity: st === "connected" ? 1 : 0.95 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
                <div style={{ width: 36, height: 36, background: p.color, color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: TO_FS, fontWeight: 700, fontSize: 18 }}>{p.icon}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: TO_FS, fontSize: 14, fontWeight: 600, color: TO_T.ink }}>{p.name}</div>
                  <div style={{ fontSize: 9, color: TO_T.muteDim, fontFamily: TO_FM, marginTop: 2 }}>scopes · {p.scopes.join(" · ")}</div>
                </div>
                {st === "connected" && <span style={{ fontSize: 16, color: TO_T.green }}>✓</span>}
                {st === "connecting" && <span style={{ width: 10, height: 10, background: TO_T.amber, borderRadius: 99, animation: "blink 1s infinite" }} />}
              </div>
              {st === "pending" && <TO_B kind="amber" onClick={() => connect(p.id)}>▶ AUTORIZAR EN {p.name.toUpperCase()}</TO_B>}
              {st === "connecting" && <div style={{ fontSize: 11, color: TO_T.amber, fontFamily: TO_FM }}>redirigiendo a {p.name}...</div>}
              {st === "connected" && <div style={{ fontSize: 10, color: TO_T.green, fontFamily: TO_FM }}>● conectado · 2 cuentas detectadas</div>}
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <TO_B onClick={onBack}>← VOLVER</TO_B>
        <span style={{ fontSize: 11, color: TO_T.mute }}>{connected} conectada{connected !== 1 ? "s" : ""} · necesitas mín 1</span>
        <button onClick={onNext} disabled={connected === 0} style={{
          padding: "12px 22px", background: connected ? TO_T.amber : "transparent", color: connected ? TO_T.bg : TO_T.muteDim,
          border: `1px solid ${connected ? TO_T.amber : TO_T.line}`, fontFamily: TO_FM, fontSize: 12, letterSpacing: "0.14em",
          fontWeight: 700, cursor: connected ? "pointer" : "not-allowed",
        }}>CONTINUAR · 2/4 →</button>
      </div>
      <ProgressDots step={1} total={5} />
    </div>
  );
};

const Step2Tracking = ({ onNext, onBack }) => {
  const checks = [
    { k: "Meta CAPI · server-side", finalSt: "ok", finalDetail: "EMQ inicial · 7.8 · dedupe 96.4%" },
    { k: "Pixel verification · fbp/fbc", finalSt: "ok", finalDetail: "cookies activas en /admision" },
    { k: "Enhanced Conversions for Leads", finalSt: "warn", finalDetail: "lifecycle no mapeado · arregla en step 3" },
    { k: "GTM container detection", finalSt: "ok", finalDetail: "GTM-PB42WX · 2 containers activos" },
    { k: "Consent Mode v2 · CMP", finalSt: "ok", finalDetail: "OneTrust detectado · granted 88%" },
  ];
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    if (progress >= checks.length) return;
    const t = setTimeout(() => setProgress(p => p + 1), 900);
    return () => clearTimeout(t);
  }, [progress]);

  const allDone = progress >= checks.length;

  return (
    <div>
      <StepHeader tag="STEP 2/4 · TRACKING · server-side mandatory" title="Verificando tu tracking en vivo" sub="MediaAgent corre estos chequeos automáticamente · si EMQ < 7.0 te avisará pero podrás continuar." />
      <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface }}>
        {checks.map((c, i) => {
          const done = i < progress;
          const running = i === progress;
          const st = done ? c.finalSt : running ? "running" : "queued";
          const col = st === "ok" ? TO_T.green : st === "warn" ? TO_T.amber : st === "running" ? TO_T.cyan : TO_T.muteDim;
          return (
            <div key={i} style={{ padding: "12px 16px", borderBottom: i < checks.length - 1 ? `1px solid ${TO_T.line}` : "none", display: "grid", gridTemplateColumns: "20px 1fr 220px", gap: 12, alignItems: "center", opacity: running || done ? 1 : 0.5 }}>
              <span style={{ color: col, fontFamily: TO_FM, fontSize: 14 }}>
                {st === "ok" ? "✓" : st === "warn" ? "!" : st === "running" ? "●" : "○"}
              </span>
              <span style={{ fontSize: 12, color: TO_T.ink }}>{c.k}</span>
              <span style={{ fontSize: 10, color: col, fontFamily: TO_FM, textAlign: "right" }}>
                {st === "running" ? "verificando..." : st === "queued" ? "queued" : c.finalDetail}
              </span>
            </div>
          );
        })}
      </div>
      <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <TO_B onClick={onBack}>← VOLVER</TO_B>
        <button onClick={onNext} disabled={!allDone} style={{
          padding: "12px 22px", background: allDone ? TO_T.amber : "transparent", color: allDone ? TO_T.bg : TO_T.muteDim,
          border: `1px solid ${allDone ? TO_T.amber : TO_T.line}`, fontFamily: TO_FM, fontSize: 12, letterSpacing: "0.14em",
          fontWeight: 700, cursor: allDone ? "pointer" : "not-allowed",
        }}>CONTINUAR · 3/4 →</button>
      </div>
      <ProgressDots step={2} total={5} />
    </div>
  );
};

const Step3CRM = ({ onNext, onBack }) => {
  const [pick, setPick] = React.useState(null);
  const opts = [
    { id: "hubspot", name: "HubSpot", color: "#FF7A59" },
    { id: "salesforce", name: "Salesforce", color: "#00A1E0" },
    { id: "other", name: "Otro · CSV/Webhook" },
    { id: "skip", name: "Skip por ahora" },
  ];
  return (
    <div>
      <StepHeader tag="STEP 3/4 · CRM · skippable" title="¿Conectamos tu CRM?" sub="Sin CRM, MediaAgent optimiza por leads superficiales · con CRM optimiza por leads calificados, pipeline y revenue. Recomendado." />
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
        {opts.map(o => (
          <button key={o.id} onClick={() => setPick(o.id)} style={{
            padding: "16px 18px", background: pick === o.id ? TO_T.surface : TO_T.bg, textAlign: "left",
            border: `1px solid ${pick === o.id ? TO_T.amber : TO_T.line}`,
            borderLeft: pick === o.id ? `3px solid ${TO_T.amber}` : `1px solid ${TO_T.line}`, cursor: "pointer",
          }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              {o.color && <div style={{ width: 28, height: 28, background: o.color, color: "#fff", fontFamily: TO_FS, fontSize: 14, fontWeight: 700, display: "flex", alignItems: "center", justifyContent: "center" }}>{o.name[0]}</div>}
              <div style={{ fontFamily: TO_FS, fontSize: 14, color: pick === o.id ? TO_T.amber : TO_T.ink, fontWeight: 500 }}>{o.name}</div>
            </div>
          </button>
        ))}
      </div>
      {pick === "skip" && (
        <div style={{ marginTop: 16, padding: "12px 14px", background: TO_T.surface, border: `1px solid ${TO_T.amber}`, borderLeftWidth: 3, fontSize: 11, color: TO_T.ink, lineHeight: 1.6 }}>
          <span style={{ color: TO_T.amber, letterSpacing: "0.14em", fontFamily: TO_FM }}>// HEADS UP </span>
          Sin CRM, MediaAgent optimizará por leads superficiales (form fills). Para optimizar por leads calificados / pipeline / revenue, agrega después en ⚙ Connect.
        </div>
      )}
      {(pick === "hubspot" || pick === "salesforce") && (
        <div style={{ marginTop: 16, padding: "14px 16px", background: TO_T.surface, border: `1px solid ${TO_T.cyan}`, borderLeftWidth: 3 }}>
          <div style={{ fontFamily: TO_FM, fontSize: 10, color: TO_T.cyan, letterSpacing: "0.14em", marginBottom: 8 }}>// MAPEO LIFECYCLE STAGES</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, fontSize: 11 }}>
            {["Lead","MQL","SAL","SQL","Customer","Won"].map(s => (
              <div key={s} style={{ display: "flex", justifyContent: "space-between", padding: "6px 10px", background: TO_T.bg }}>
                <span style={{ color: TO_T.muteDim }}>{s}</span>
                <span style={{ color: TO_T.green, fontFamily: TO_FM }}>auto-mapped ✓</span>
              </div>
            ))}
          </div>
        </div>
      )}
      <div style={{ marginTop: 24, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <TO_B onClick={onBack}>← VOLVER</TO_B>
        <button onClick={onNext} disabled={!pick} style={{
          padding: "12px 22px", background: pick ? TO_T.amber : "transparent", color: pick ? TO_T.bg : TO_T.muteDim,
          border: `1px solid ${pick ? TO_T.amber : TO_T.line}`, fontFamily: TO_FM, fontSize: 12, letterSpacing: "0.14em",
          fontWeight: 700, cursor: pick ? "pointer" : "not-allowed",
        }}>{pick === "skip" ? "SKIP CRM · CONTINUAR · 4/4 →" : "CONTINUAR · 4/4 →"}</button>
      </div>
      <ProgressDots step={3} total={5} />
    </div>
  );
};

const Step4Audit = ({ onComplete }) => {
  const TIER1 = [
    "verificando CAPI dedupe...",
    "scoring EMQ across pixels...",
    "scanning ad sets · 47 detected en SF · alarm fragmentación...",
    "comparando platform attribution vs MMM prior...",
    "calculando creative fatigue ratios...",
    "construyendo response curves preliminares...",
    "diagnose tree compiled · 6 ramas · 13 hipótesis...",
    "audit score computed · finalizando reporte...",
  ];
  const [tick, setTick] = React.useState(0);
  const total = TIER1.length;
  const pct = Math.min(100, (tick / total) * 100);
  const done = tick >= total;

  React.useEffect(() => {
    if (done) return;
    const t = setTimeout(() => setTick(x => x + 1), 800);
    return () => clearTimeout(t);
  }, [tick, done]);

  return (
    <div>
      <StepHeader tag="STEP 4/4 · FIRST AUDIT · the magic moment" title={done ? "Audit completado · score 86" : "Agente auditando tu setup..."} sub={done ? "5 hallazgos · 2 ya resueltos auto · 3 esperan tu aprobación en F1 Today" : "30-60s · el agente ejecuta Tier 1 (tracking) + Tier 2 (estructura) + Tier 3 (señal)."} />
      {/* Progress bar */}
      <div style={{ height: 4, background: TO_T.line, marginBottom: 18, position: "relative" }}>
        <div style={{ position: "absolute", left: 0, top: 0, height: "100%", width: `${pct}%`, background: done ? TO_T.green : TO_T.amber, transition: "width 0.6s ease, background 0.3s" }} />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface, padding: "14px 16px" }}>
          <div style={{ fontFamily: TO_FM, fontSize: 10, color: TO_T.amber, letterSpacing: "0.14em", marginBottom: 12 }}>// AGENT.LOG · live</div>
          <div style={{ minHeight: 220, fontFamily: TO_FM, fontSize: 11, lineHeight: 1.7 }}>
            {TIER1.slice(0, tick).map((line, i) => (
              <div key={i} style={{ color: TO_T.green, opacity: 0.5 + (0.5 * (i / Math.max(tick - 1, 1))) }}>
                <span style={{ color: TO_T.muteDim }}>11:{(42 + i).toString().padStart(2,"0")}</span> ✓ {line}
              </div>
            ))}
            {!done && tick > 0 && (
              <div style={{ color: TO_T.amber }}>
                <span style={{ color: TO_T.muteDim }}>11:{(42 + tick).toString().padStart(2,"0")}</span> ● <span style={{ animation: "blink 1s infinite" }}>{TIER1[tick] || "procesando..."}</span>
              </div>
            )}
          </div>
        </div>
        <div style={{ border: `1px solid ${TO_T.line}`, background: TO_T.surface, padding: "14px 16px" }}>
          <div style={{ fontFamily: TO_FM, fontSize: 10, color: TO_T.amber, letterSpacing: "0.14em", marginBottom: 12 }}>// HALLAZGOS</div>
          {done ? (
            <div>
              <div style={{ fontFamily: TO_FS, fontSize: 64, fontWeight: 700, color: TO_T.green, lineHeight: 1, marginBottom: 6 }}>86</div>
              <div style={{ fontSize: 11, color: TO_T.muteDim, letterSpacing: "0.12em", marginBottom: 16 }}>AUDIT SCORE / 100</div>
              {[
                { sev: "P0", t: "Fragmentación SF · 47 ad sets activos", c: TO_T.red },
                { sev: "P1", t: "Lifecycle CRM no mapeado · pipeline blindspot", c: TO_T.amber },
                { sev: "P1", t: "Anti-pattern: 12 creatives en zona fatigada", c: TO_T.amber },
                { sev: "P2", t: "Consent Mode v2 granted 88% · puede subir", c: TO_T.cyan },
                { sev: "✓", t: "Dedupe CAPI · 96.4% · saludable", c: TO_T.green },
              ].map((f, i) => (
                <div key={i} style={{ padding: "8px 10px", background: TO_T.bg, borderLeft: `3px solid ${f.c}`, marginBottom: 6, fontSize: 11 }}>
                  <span style={{ color: f.c, fontFamily: TO_FM, marginRight: 8 }}>{f.sev}</span>
                  <span style={{ color: TO_T.ink }}>{f.t}</span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ minHeight: 220, display: "flex", alignItems: "center", justifyContent: "center", color: TO_T.muteDim, fontSize: 11 }}>
              hallazgos aparecerán al completar audit · {Math.round(pct)}%
            </div>
          )}
        </div>
      </div>

      <div style={{ marginTop: 24, textAlign: "center" }}>
        {done ? (
          <button onClick={onComplete} style={{
            padding: "16px 32px", background: TO_T.green, color: TO_T.bg, border: "none",
            fontFamily: TO_FM, fontSize: 13, letterSpacing: "0.18em", fontWeight: 700, cursor: "pointer",
          }}>▶ ENTRAR AL COCKPIT</button>
        ) : (
          <span style={{ fontSize: 11, color: TO_T.muteDim }}>completando audit · {Math.round(pct)}% · espera...</span>
        )}
      </div>
      <ProgressDots step={done ? 4 : 3} total={5} />
    </div>
  );
};

const OnboardingFlow = ({ onComplete }) => {
  const [step, setStep] = React.useState(0); // 0 welcome, 1-4 steps
  const Cards = [
    <Welcome onNext={() => setStep(1)} />,
    <Step1Platforms onNext={() => setStep(2)} onBack={() => setStep(0)} />,
    <Step2Tracking onNext={() => setStep(3)} onBack={() => setStep(1)} />,
    <Step3CRM onNext={() => setStep(4)} onBack={() => setStep(2)} />,
    <Step4Audit onComplete={onComplete} />,
  ];
  return (
    <div style={{ position: "fixed", inset: 0, background: TO_T.bg, zIndex: 5000, display: "flex", alignItems: "center", justifyContent: "center", overflowY: "auto", padding: "40px 20px" }}>
      {/* grid bg */}
      <div style={{ position: "absolute", inset: 0, backgroundImage: `radial-gradient(${TO_T.line} 1px, transparent 1px)`, backgroundSize: "20px 20px", opacity: 0.4, pointerEvents: "none" }} />
      <div style={{ position: "relative", width: "100%", maxWidth: 760, background: TO_T.bg, border: `1px solid ${TO_T.amber}`, borderTopWidth: 3, padding: "36px 40px", fontFamily: TO_FS }}>
        {Cards[step]}
      </div>
    </div>
  );
};

window.OnboardingFlow = OnboardingFlow;
