/* =====================================================================
   ed-quoter.jsx — motor genérico de cotizador (5 pasos: 4 preguntas + resultado).
   Config-driven desde ED.quoters[key]. Cálculo puro y reproducible.
   ===================================================================== */
const EDP = window.ED.platforms;

/* ---- Cálculo puro ---- */
function edPlatformRange(cfg, platformKey) {
  return (cfg.platforms || []).find(p => p.key === platformKey) || null;
}
function edScaleFactor(cfg, answers) {
  // busca el primer paso single con 'factor' en sus opciones
  for (const st of cfg.steps) {
    if (st.kind === "single" && st.options.some(o => o.factor != null)) {
      const v = answers[st.id];
      const opt = st.options.find(o => o.value === v);
      if (opt && opt.factor != null) return opt.factor;
    }
  }
  return 0;
}
function edAddonsTotal(cfg, answers) {
  let sum = 0; const picked = [];
  for (const st of cfg.steps) {
    if (st.kind === "multi") {
      const arr = answers[st.id] || [];
      arr.forEach(v => {
        const opt = st.options.find(o => o.value === v);
        if (opt) { sum += (opt.price || 0); if ((opt.price || 0) > 0) picked.push(opt); }
      });
    }
  }
  return { sum, picked };
}
function edCalc(cfg, answers) {
  const pr = edPlatformRange(cfg, answers.plataforma);
  if (!pr) return null;
  const factor = edScaleFactor(cfg, answers);
  // base = punto dentro (o más allá) del rango según el factor de escala
  const base = Math.round(pr.min + Math.min(factor, 1) * (pr.max - pr.min) + Math.max(factor - 1, 0) * (pr.max - pr.min) * 0.6);
  const { sum, picked } = edAddonsTotal(cfg, answers);
  const total = base + sum;
  const [tMin, tMax] = cfg.timeBase;
  const days = [Math.round(tMin + factor * tMin * 0.6), Math.round(tMax + factor * tMax * 0.7)];
  return {
    base, addonsSum: sum, addonsPicked: picked, total,
    min: Math.round(total * 0.95), max: Math.round(total * 1.12),
    days, platform: pr, platformKey: answers.plataforma,
  };
}

/* ---- Tarjeta de opción ---- */
function QOption({ selected, onClick, title, desc, multi, right }) {
  const [hover, setHover] = useS(false);
  return (
    <button type="button" role={multi ? "checkbox" : "radio"} aria-checked={selected} onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        textAlign: "left", width: "100%", cursor: "pointer", fontFamily: "var(--font-sans)",
        background: selected ? "var(--surface)" : (hover ? "var(--surface)" : "var(--surface)"),
        border: "1.5px solid " + (selected ? "var(--navy-700)" : (hover ? "var(--border-strong)" : "var(--border)")),
        borderRadius: "var(--r-lg)", padding: "16px 18px", display: "flex", gap: 13, alignItems: "center",
        boxShadow: selected ? "var(--shadow-md)" : (hover ? "var(--shadow-sm)" : "var(--shadow-xs)"),
        transition: "all 180ms var(--ease-out)",
      }}>
      <span style={{
        flex: "none", width: 22, height: 22, borderRadius: multi ? "var(--r-xs)" : 999, marginTop: 1,
        border: selected ? "none" : "1.5px solid var(--border-strong)",
        background: selected ? "var(--navy-900)" : "transparent",
        display: "flex", alignItems: "center", justifyContent: "center", color: "var(--white)",
        transition: "all 160ms var(--ease-out)", alignSelf: "flex-start",
      }}>{selected && <Icon name="check" size={14} color="var(--white)" strokeWidth={3} />}</span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: "block", fontSize: 15.5, fontWeight: 600, color: "var(--navy-900)" }}>{title}</span>
        {desc && <span style={{ display: "block", marginTop: 3, fontSize: 13, lineHeight: "18px", color: "var(--fg-tertiary)" }}>{desc}</span>}
      </span>
      {right && <span style={{ flex: "none", fontFamily: "var(--font-mono)", fontSize: 13.5, fontWeight: 500, color: "var(--navy-900)" }}>{right}</span>}
    </button>
  );
}

/* ---- Paso de plataforma (con rango de precio) ---- */
function QPlatformStep({ cfg, value, onPick }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
      {cfg.platforms.map(p => {
        const meta = EDP[p.key]; const sel = value === p.key;
        return (
          <button key={p.key} type="button" role="radio" aria-checked={sel} onClick={() => onPick(p.key)}
            style={{ textAlign: "left", cursor: "pointer", fontFamily: "var(--font-sans)", background: "var(--surface)",
              border: "1.5px solid " + (sel ? "var(--navy-700)" : "var(--border)"), borderRadius: "var(--r-lg)", padding: "18px 18px",
              boxShadow: sel ? "var(--shadow-md)" : "var(--shadow-xs)", transition: "all 180ms var(--ease-out)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 20, height: 20, borderRadius: 999, border: sel ? "none" : "1.5px solid var(--border-strong)", background: sel ? "var(--navy-900)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center" }}>{sel && <Icon name="check" size={12} color="var(--white)" strokeWidth={3} />}</span>
              <span style={{ fontFamily: "var(--font-display)", fontSize: 16, fontWeight: 600, color: "var(--navy-900)" }}>{meta ? meta.label : p.key}</span>
            </div>
            <div className="ed-tnum" style={{ fontFamily: "var(--font-mono)", fontSize: 13.5, color: "var(--gold-700)", fontWeight: 500, marginTop: 12 }}>${p.min}–${p.max} USD</div>
            {meta && <div style={{ fontSize: 12.5, color: "var(--fg-tertiary)", marginTop: 6, lineHeight: "17px" }}>{meta.accent}</div>}
            {meta && <a href={"#/plataforma/" + p.key} onClick={(e) => e.stopPropagation()} style={{ display: "inline-flex", alignItems: "center", gap: 4, marginTop: 10, fontSize: 12.5, fontWeight: 600, color: "var(--navy-700)" }}>Ver detalle <Icon name="arrow-up-right" size={13} color="var(--navy-700)" /></a>}
          </button>
        );
      })}
    </div>
  );
}

/* ---- Resultado del cotizador ---- */
function QResult({ cfg, answers, calc, onEdit, onCalendly, onSubmit }) {
  const meta = EDP[calc.platformKey];
  return (
    <div className="ed-view">
      <div style={{ textAlign: "center", marginBottom: 24 }}>
        <Eyebrow style={{ marginBottom: 10 }}>Tu estimado está listo</Eyebrow>
        <h2 style={{ fontSize: 30, lineHeight: "36px", fontWeight: 600 }}>{cfg.title.replace("Cotizador de ", "")} en {meta ? meta.label : ""}</h2>
      </div>
      <div style={{ background: "var(--navy-900)", borderRadius: "var(--r-xl)", padding: "30px 32px", boxShadow: "var(--shadow-lg)", display: "flex", gap: 32, flexWrap: "wrap" }}>
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--gold)" }}>Inversión estimada</div>
          <div className="ed-tnum" style={{ fontFamily: "var(--font-display)", fontSize: 38, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--white)", marginTop: 10 }}>${calc.min.toLocaleString("en-US")} – ${calc.max.toLocaleString("en-US")}</div>
          <div style={{ fontSize: 13, color: "rgba(238,241,246,0.7)", marginTop: 6 }}>USD · según alcance final</div>
        </div>
        <div style={{ width: 1, background: "rgba(238,241,246,0.16)" }} />
        <div style={{ flex: 1, minWidth: 200 }}>
          <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--gold)" }}>Tiempo de entrega</div>
          <div className="ed-tnum" style={{ fontFamily: "var(--font-display)", fontSize: 38, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--white)", marginTop: 10 }}>{calc.days[0]}–{calc.days[1]} días</div>
          <div style={{ fontSize: 13, color: "rgba(238,241,246,0.7)", marginTop: 6 }}>hábiles</div>
        </div>
      </div>

      {/* Desglose */}
      <div style={{ marginTop: 16, background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: "20px 22px", boxShadow: "var(--shadow-sm)" }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: "var(--navy-900)", marginBottom: 6 }}>¿Qué incluye este estimado?</div>
        <div style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderTop: "1px solid var(--border-subtle)", fontSize: 14 }}>
          <span style={{ color: "var(--navy-900)" }}>Construcción en {meta ? meta.label : ""}</span>
          <span className="ed-tnum" style={{ fontFamily: "var(--font-mono)", fontSize: 13.5 }}>${calc.base.toLocaleString("en-US")}</span>
        </div>
        {calc.addonsPicked.map((a, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderTop: "1px solid var(--border-subtle)", fontSize: 14 }}>
            <span style={{ color: "var(--navy-900)" }}>{a.label}</span>
            <span className="ed-tnum" style={{ fontFamily: "var(--font-mono)", fontSize: 13.5 }}>+${a.price}</span>
          </div>
        ))}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 0", borderTop: "1px solid var(--border-subtle)", fontSize: 13.5, color: "var(--fg-tertiary)" }}>
          <Icon name="shield-check" size={15} color="var(--success)" /> Compliance legal · Términos, Privacidad y Cookies — incluido
        </div>
      </div>

      <div style={{ marginTop: 24, display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
        <Btn kind="ghost" icon="pencil" onClick={onEdit}>Ajustar respuestas</Btn>
        <Btn kind="navy" icon="calendar" onClick={onCalendly}>Agendar llamada</Btn>
        <Btn kind="gold" icon="send" onClick={onSubmit}>Solicitar cotización formal</Btn>
      </div>
    </div>
  );
}

/* ---- Cotizador (orquestador) ---- */
function Quoter({ cfgKey }) {
  const cfg = window.ED.quoters[cfgKey];
  const storeKey = "ed_quoter_" + cfgKey;
  const [answers, setAnswers] = useS(() => {
    try { return JSON.parse(localStorage.getItem(storeKey)) || {}; } catch (e) { return {}; }
  });
  const [step, setStep] = useS(0);          // 0..3 preguntas, 4 = resultado
  const [error, setError] = useS(null);
  const [showCal, setShowCal] = useS(false);
  const total = cfg.steps.length;           // 4 pasos de pregunta

  useE(() => { try { localStorage.setItem(storeKey, JSON.stringify(answers)); } catch (e) {} }, [answers]);
  useE(() => { setError(null); if (window.lucide) window.lucide.createIcons(); }, [step]);

  function setSingle(stepId, value) { setAnswers(a => Object.assign({}, a, { [stepId]: value })); }
  function toggleMulti(stepId, value) {
    setAnswers(a => { const arr = a[stepId] || []; return Object.assign({}, a, { [stepId]: arr.includes(value) ? arr.filter(v => v !== value) : arr.concat(value) }); });
  }
  function validate(i) {
    const st = cfg.steps[i];
    if (st.kind === "multi") return { ok: true };
    if (!answers[st.id]) return { ok: false, error: "Selecciona una opción para continuar." };
    return { ok: true };
  }
  function next() {
    if (step < total) { const v = validate(step); if (!v.ok) { setError(v.error); return; } }
    setStep(s => Math.min(s + 1, total));
  }
  function back() { setStep(s => Math.max(s - 1, 0)); }

  const calc = edCalc(cfg, answers);
  const isResult = step >= total;
  const st = !isResult ? cfg.steps[step] : null;

  // ── Submit al backend Laravel ──
  const [showContact, setShowContact] = useS(false);
  const [contact, setContact] = useS({ nombre: "", email: "", whatsapp: "" });
  const [sending, setSending] = useS(false);
  const [sent, setSent] = useS(false);

  async function submitToBackend(e) {
    e?.preventDefault?.();
    if (!contact.nombre || !contact.email || !contact.whatsapp) return;
    setSending(true);

    const csrf = document.querySelector('meta[name="csrf-token"]')?.content;
    const url  = (window.SELLU && window.SELLU.cotizarUrl) || "/cotizador/enviar";
    const platformKey = answers.plataforma || (calc && calc.platformKey);
    const platformLabel = platformKey && window.ED.platforms[platformKey]
      ? window.ED.platforms[platformKey].label
      : platformKey || "—";

    const fd = new FormData();
    fd.append("_token", csrf || "");
    fd.append("tipo_proyecto",   cfgKey);
    fd.append("plataforma",      platformLabel);
    fd.append("paginas",         "1");
    fd.append("mantenimiento",   "ninguno");
    fd.append("precio_estimado", String(calc ? calc.mid : 0));
    fd.append("urgencia",        "cotizando");
    fd.append("whatsapp",        contact.whatsapp);
    if (!window.SELLU?.isAuth) {
      fd.append("guest_nombre", contact.nombre);
      fd.append("guest_email",  contact.email);
    }
    fd.append("notas", JSON.stringify({
      folio:        "ED-" + Date.now().toString(36).toUpperCase(),
      tipo:         cfgKey,
      respuestas:   answers,
      plataforma:   platformKey,
      addons:       calc?.addonsPicked || [],
      rango:        calc ? { min: calc.min, mid: calc.mid, max: calc.max } : null,
      dias:         calc ? calc.days : null,
      contacto:     contact,
    }));

    try {
      await fetch(url, { method: "POST", body: fd, credentials: "same-origin" });
      setSent(true);
      setTimeout(() => setShowContact(false), 2200);
    } catch (e) {
      console.warn("No se pudo enviar al backend", e);
      setSent(true); // mostramos confirmación igual; el localStorage guarda el folio
    } finally {
      setSending(false);
    }
  }

  return (
    <div>
      {/* Progreso */}
      <div style={{ maxWidth: 680, margin: "0 auto 28px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
          <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-tertiary)" }}>{isResult ? "Resultado" : "Paso " + (step + 1) + " de " + total}</span>
          <span style={{ fontSize: 13, fontWeight: 600, color: "var(--navy-900)" }}>{cfg.title.replace("Cotizador de ", "")}</span>
        </div>
        <div style={{ height: 6, borderRadius: 999, background: "var(--navy-100)", overflow: "hidden" }}>
          <div style={{ height: "100%", width: ((isResult ? total : step) / total * 100) + "%", background: "var(--navy-900)", borderRadius: 999, transition: "width 320ms var(--ease-out)" }} />
        </div>
      </div>

      <div style={{ maxWidth: 680, margin: "0 auto" }}>
        {isResult ? (
          <QResult cfg={cfg} answers={answers} calc={calc} onEdit={() => setStep(total - 1)} onCalendly={() => setShowCal(true)} onSubmit={() => setShowContact(true)} />
        ) : (
          <div className="ed-view" key={step}>
            <h2 style={{ fontSize: 26, lineHeight: "32px", fontWeight: 600 }}>{st.title}</h2>
            {st.subtitle && <p style={{ marginTop: 8, fontSize: 15.5, color: "var(--fg-tertiary)" }}>{st.subtitle}</p>}
            <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 12 }} role={st.kind === "multi" ? "group" : "radiogroup"}>
              {st.kind === "platform"
                ? <QPlatformStep cfg={cfg} value={answers.plataforma} onPick={(k) => setSingle("plataforma", k)} />
                : st.options.map(opt => (
                  <QOption key={opt.value} multi={st.kind === "multi"}
                    selected={st.kind === "multi" ? (answers[st.id] || []).includes(opt.value) : answers[st.id] === opt.value}
                    onClick={() => st.kind === "multi" ? toggleMulti(st.id, opt.value) : setSingle(st.id, opt.value)}
                    title={opt.label} desc={opt.desc}
                    right={opt.price != null ? (opt.price === 0 ? "Incluido" : "+$" + opt.price) : null} />
                ))}
            </div>
          </div>
        )}
      </div>

      {/* Footer con estimado en vivo */}
      {!isResult && (
        <div style={{ position: "sticky", bottom: 0, marginTop: 36, borderTop: "1px solid var(--border)", background: "rgba(248,249,250,0.94)", backdropFilter: "blur(12px)", WebkitBackdropFilter: "blur(12px)" }}>
          {error && <div style={{ maxWidth: 680, margin: "0 auto", padding: "10px 0 0", display: "flex", alignItems: "center", gap: 8, color: "var(--danger)", fontSize: 13.5, fontWeight: 500 }}><Icon name="alert-circle" size={15} color="var(--danger)" /> {error}</div>}
          <div style={{ maxWidth: 680, margin: "0 auto", padding: "14px 0", display: "flex", alignItems: "center", gap: 16 }}>
            <Btn kind="quiet" icon="arrow-left" onClick={back} disabled={step === 0} style={{ opacity: step === 0 ? 0.4 : 1 }}>Atrás</Btn>
            <div style={{ flex: 1, textAlign: "center", lineHeight: 1.2 }}>
              {calc ? (
                <React.Fragment>
                  <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-muted)" }}>Estimado</div>
                  <div className="ed-tnum" style={{ fontSize: 15, fontWeight: 600, color: "var(--navy-900)" }}>${calc.min.toLocaleString("en-US")} – ${calc.max.toLocaleString("en-US")}</div>
                </React.Fragment>
              ) : <div style={{ fontSize: 12.5, color: "var(--fg-muted)" }}>Elige una plataforma para ver tu estimado</div>}
            </div>
            <Btn kind="gold" iconRight="arrow-right" onClick={next}>{step === total - 1 ? "Ver estimado" : "Siguiente"}</Btn>
          </div>
        </div>
      )}

      <CalendlyModal open={showCal} onClose={() => setShowCal(false)} context={cfg.title.replace("Cotizador de ", "")} />

      {/* Modal de contacto: cliente solicita cotización formal */}
      {showContact && (
        <div role="dialog" aria-modal="true" onMouseDown={(e) => { if (e.target === e.currentTarget && !sending) setShowContact(false); }}
             style={{ position: "fixed", inset: 0, zIndex: 300, background: "rgba(20,24,42,.45)", display: "flex", alignItems: "center", justifyContent: "center", padding: 20 }}>
          <form onSubmit={submitToBackend} style={{ background: "var(--surface)", borderRadius: "var(--r-xl)", boxShadow: "var(--shadow-xl)", maxWidth: 460, width: "100%", padding: 28 }}>
            {!sent ? (
              <React.Fragment>
                <span style={{ width: 44, height: 44, borderRadius: "var(--r-md)", background: "var(--gold)", color: "var(--navy-900)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
                  <Icon name="mail" size={22} color="var(--navy-900)" />
                </span>
                <h3 style={{ fontSize: 22, fontWeight: 600, letterSpacing: "-0.01em" }}>Recibe tu cotización formal</h3>
                <p style={{ marginTop: 8, fontSize: 14.5, color: "var(--fg-secondary)", lineHeight: 1.5 }}>Te enviamos el detalle de tu proyecto y un especialista te contacta en menos de 24 horas.</p>

                <div style={{ marginTop: 16, display: "flex", flexDirection: "column", gap: 10 }}>
                  <input type="text" required placeholder="Nombre completo" className="ed-input"
                         value={contact.nombre} onChange={(e) => setContact(c => ({...c, nombre: e.target.value}))} />
                  <input type="email" required placeholder="tu@correo.com" className="ed-input"
                         value={contact.email} onChange={(e) => setContact(c => ({...c, email: e.target.value}))} />
                  <input type="tel" required placeholder="+57 300 1234567" className="ed-input"
                         value={contact.whatsapp} onChange={(e) => setContact(c => ({...c, whatsapp: e.target.value}))} />
                </div>

                <button type="submit" disabled={sending} className="ed-btn ed-btn-gold" style={{ width: "100%", marginTop: 16, justifyContent: "center" }}>
                  {sending ? "Enviando..." : "Enviar mi cotización →"}
                </button>
                <button type="button" disabled={sending} className="ed-btn ed-btn-quiet" style={{ width: "100%", marginTop: 6, justifyContent: "center" }} onClick={() => setShowContact(false)}>Cancelar</button>
              </React.Fragment>
            ) : (
              <div style={{ textAlign: "center", padding: "8px 0" }}>
                <span style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-bg)", color: "var(--success-fg)", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
                  <Icon name="check" size={28} color="var(--success-fg)" strokeWidth={2.5} />
                </span>
                <h3 style={{ fontSize: 20, fontWeight: 600 }}>¡Cotización enviada!</h3>
                <p style={{ marginTop: 8, fontSize: 14, color: "var(--fg-secondary)" }}>Te responderemos a {contact.email} en menos de 24 horas hábiles.</p>
              </div>
            )}
          </form>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Quoter, edCalc });
