/* =====================================================================
   app.jsx — Cotizador Sell-U integrado dentro del layout público.
   Sin barra top propia · sin altura 100vh · navegación inline tipo doc.
   ===================================================================== */
(function () {
  const Cz = window.Cotizador;
  const QUOTES_KEY = "sellu_quotes_v1";

  function loadQuotes() {
    try { return JSON.parse(localStorage.getItem(QUOTES_KEY) || "{}"); } catch (e) { return {}; }
  }
  function saveQuote(id, state) {
    const all = loadQuotes();
    all[id] = { state: JSON.parse(JSON.stringify(state)), createdAt: Date.now() };
    try { localStorage.setItem(QUOTES_KEY, JSON.stringify(all)); } catch (e) {}
  }

  const STEP_TITLES = ["Tipo", "Escala", "Plataforma", "Estado actual", "Contenido", "Integraciones", "Soporte"];

  /* ---- Barra de progreso compacta (chips) ---- */
  function Progress({ step, canGoTo, onJump }) {
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 4, flexWrap: "nowrap", overflowX: "auto", padding: "2px 0" }}>
        {STEP_TITLES.map((t, i) => {
          const n = i + 1;
          const isDone = n < step;
          const isCurrent = n === step;
          const reachable = canGoTo(n);
          return (
            <React.Fragment key={n}>
              <button
                type="button"
                disabled={!reachable}
                onClick={() => reachable && onJump(n)}
                title={t}
                style={{
                  display: "flex", alignItems: "center", gap: 7, background: "transparent", border: "none",
                  cursor: reachable ? "pointer" : "default", padding: 0, flex: "none",
                }}
              >
                <span style={{
                  width: 28, height: 28, borderRadius: 999, flex: "none", display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12.5, fontWeight: 600, fontFamily: "var(--font-display)",
                  background: isDone ? "var(--navy-700)" : "var(--white)",
                  color: isDone ? "var(--paper)" : isCurrent ? "var(--navy-900)" : "var(--fg-muted)",
                  border: isCurrent ? "1.5px solid var(--navy-700)" : isDone ? "1.5px solid var(--navy-700)" : "1.5px solid var(--border-default)",
                  boxShadow: isCurrent ? "var(--shadow-ring-focus)" : "none",
                  transition: "all 200ms var(--ease-out)",
                }}>
                  {isDone ? <Icon name="check" size={13} strokeWidth={3} /> : n}
                </span>
                <span className="cotz-step-label" style={{ fontSize: 12.5, fontWeight: isCurrent ? 600 : 500, color: isCurrent ? "var(--navy-900)" : "var(--fg-tertiary)", whiteSpace: "nowrap" }}>{t}</span>
              </button>
              {n < 7 && <span style={{ flex: "1 1 14px", minWidth: 12, height: 1.5, background: n < step ? "var(--navy-700)" : "var(--border-default)", margin: "0 4px", transition: "background 200ms var(--ease-out)" }} />}
            </React.Fragment>
          );
        })}
      </div>
    );
  }

  /* ---- App principal ---- */
  function App() {
    const store = window.useQuoteStore();
    const { state, setField, setNested, toggleInArray, goTo, reset } = store;
    const density = "regular";
    const [error, setError] = React.useState(null);
    const [showContact, setShowContact] = React.useState(false);
    const [showGuestModal, setShowGuestModal] = React.useState(false);
    const [submitting, setSubmitting] = React.useState(false);
    const [guestForm, setGuestForm] = React.useState({ nombre: "", email: "", whatsapp: "" });
    const stepHeaderRef = React.useRef(null);
    const isAuth = !!window.SELLU?.isAuth;

    React.useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

    React.useEffect(() => {
      setError(null);
      // Scroll suave al inicio del wizard cuando cambia el paso
      if (stepHeaderRef.current) {
        const offset = stepHeaderRef.current.getBoundingClientRect().top + window.scrollY - 90;
        window.scrollTo({ top: offset, behavior: "smooth" });
      }
    }, [state.step, state.submittedId]);

    function canGoTo(target) {
      if (target <= state.step) return true;
      for (let s = state.step; s < target; s++) {
        if (!window.validateStep(s, state).ok) return false;
      }
      return true;
    }

    async function submitToBackend(state, quoteId, guestContact) {
      const csrf = document.querySelector('meta[name="csrf-token"]')?.content;
      const url  = window.SELLU?.cotizarUrl || "/cotizador/enviar";

      const quote = Cz.calculateQuote(state);
      const time  = Cz.calculateTime(state);
      const platform = Cz.PLATFORMS[state.platform];

      const payload = {
        _token:            csrf,
        tipo_proyecto:     state.projectType,
        plataforma:        platform ? platform.label : state.platform,
        paginas:           Cz.pagesCount(state),
        addons:            (state.integrations || []),
        mantenimiento:     state.support || 'ninguno',
        precio_estimado:   quote ? quote.mid : 0,
        urgencia:          'cotizando',
        whatsapp:          (guestContact && guestContact.whatsapp) || state.whatsapp || '—',
        notas:             JSON.stringify({
          folio:           quoteId,
          tipo:            state.projectType,
          escala:          state.scale,
          plataforma:      state.platform,
          recomendada:     Cz.recommendPlatform(state.projectType, state.scale)?.platform,
          hosting:         state.hostingOwnership,
          estado_actual:   state.currentStatus,
          contenido:       state.content,
          integraciones:   state.integrations,
          soporte:         state.support,
          rango:           quote ? { min: quote.min, mid: quote.mid, max: quote.max } : null,
          tiempo_dias:     time,
        }),
      };

      if (!isAuth && guestContact) {
        payload.guest_nombre = guestContact.nombre;
        payload.guest_email  = guestContact.email;
      }

      const form = new FormData();
      Object.entries(payload).forEach(([k, v]) => {
        if (Array.isArray(v)) v.forEach(x => form.append(k + '[]', x));
        else form.append(k, v);
      });

      try {
        await fetch(url, { method: 'POST', body: form, credentials: 'same-origin' });
      } catch (e) {
        console.warn('Cotización guardada local pero no se pudo enviar al servidor', e);
      }
    }

    async function finalizar(guestContact) {
      setSubmitting(true);
      const id = Cz.makeQuoteId();
      saveQuote(id, state);
      await submitToBackend(state, id, guestContact);
      setField({ submittedId: id });
      setSubmitting(false);
      setShowGuestModal(false);
    }

    async function next() {
      const v = window.validateStep(state.step, state);
      if (!v.ok) { setError(v.error); return; }
      setError(null);
      if (state.step < 7) {
        goTo(state.step + 1);
      } else {
        if (!isAuth) {
          setShowGuestModal(true);
          return;
        }
        await finalizar(null);
      }
    }

    function back() {
      if (state.submittedId) { setField({ submittedId: null }); return; }
      if (state.step > 1) goTo(state.step - 1);
    }
    function editStep(s) { setField({ submittedId: null }); goTo(s); }
    function restart() { reset(); }

    function submitGuest(e) {
      e.preventDefault();
      if (!guestForm.nombre || !guestForm.email || !guestForm.whatsapp) {
        setError("Completa nombre, email y WhatsApp para enviar tu cotización.");
        return;
      }
      finalizar(guestForm);
    }

    // ── Resultado ──
    if (state.submittedId) {
      return (
        <div className="cot-container" style={{ paddingTop: 32 }}>
          <window.QuoteResult state={state} quoteId={state.submittedId} onEditStep={editStep} onRestart={restart} />
        </div>
      );
    }

    // ── Estimado dinámico (preview en el footer) ──
    let estimate = null, estimatePrelim = false;
    if (state.step >= 2 && state.projectType && state.scale) {
      const q = Cz.calculateQuote(state, state.platform || "wordpress-elementor");
      if (q) { estimate = q; estimatePrelim = !state.platform; }
    }

    const StepComp = [Step1, Step2, Step3, Step4, Step5, Step6, Step7][state.step - 1];
    const stepProps = { state, setField, setNested, toggleInArray, density, openContact: () => setShowContact(true) };

    return (
      <React.Fragment>
        <div className="cot-container" style={{ paddingTop: 24 }} ref={stepHeaderRef}>
          {/* Barra de progreso */}
          <div style={{ padding: "0 0 24px", borderBottom: "1px solid var(--border-default)", marginBottom: 32 }}>
            <Progress step={state.step} canGoTo={canGoTo} onJump={goTo} />
          </div>

          {/* Step actual */}
          <StepComp {...stepProps} />
        </div>

        {/* Footer fijo con CTA */}
        <div className="cot-nav-footer">
          {error && (
            <div className="cotz-error" style={{ maxWidth: 720, margin: "0 auto 10px", display: "flex", alignItems: "center", gap: 8, color: "var(--danger-700)", fontSize: 13.5, fontWeight: 500 }}>
              <Icon name="alert-circle" size={15} /> {error}
            </div>
          )}
          <div className="cot-nav-inner">
            <button type="button" className="cotz-btn cotz-btn-ghost" onClick={back} disabled={state.step === 1 || submitting}>
              <Icon name="arrow-left" size={16} /> Atrás
            </button>

            {estimate ? (
              <div style={{ flex: 1, textAlign: "center", lineHeight: 1.2, minWidth: 0 }}>
                <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-muted)" }}>
                  {estimatePrelim ? "Estimado preliminar" : "Estimado"}
                </div>
                <div style={{ fontSize: 14.5, fontWeight: 600, color: "var(--navy-900)", fontVariantNumeric: "tabular-nums" }}>
                  {Cz.fmtUSD(estimate.min)} – {Cz.fmtUSD(estimate.max)}
                </div>
              </div>
            ) : <div style={{ flex: 1 }} />}

            <button type="button" className="cotz-btn cotz-btn-primary" onClick={next} disabled={submitting}>
              {submitting ? "Enviando..." : (state.step === 7 ? "Ver mi cotización" : "Siguiente")}
              {!submitting && <Icon name="arrow-right" size={16} color="var(--paper)" />}
            </button>
          </div>
        </div>

        <ContactModal open={showContact} onClose={() => setShowContact(false)} />

        {/* Modal contacto guest */}
        {showGuestModal && (
          <div role="dialog" aria-modal="true" onMouseDown={(e) => { if (e.target === e.currentTarget && !submitting) setShowGuestModal(false); }} style={{
            position: "fixed", inset: 0, zIndex: 300, background: "rgba(20,24,42,.4)",
            display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
          }}>
            <form onSubmit={submitGuest} style={{
              background: "var(--white)", borderRadius: "var(--radius-xl)", boxShadow: "var(--shadow-xl)",
              maxWidth: 460, width: "100%", padding: 28,
            }}>
              <span style={{ width: 44, height: 44, borderRadius: "var(--radius-md)", background: "var(--accent-500)", color: "var(--navy-900)", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
                <Icon name="mail" size={22} />
              </span>
              <h3 style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600, color: "var(--navy-900)", letterSpacing: "-0.01em", margin: 0 }}>Recibe tu cotización</h3>
              <p style={{ marginTop: 8, fontSize: 14.5, lineHeight: "22px", color: "var(--fg-secondary)" }}>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" placeholder="Nombre completo" className="cotz-input"
                  value={guestForm.nombre} onChange={(e) => setGuestForm(f => ({...f, nombre: e.target.value}))} required />
                <input type="email" placeholder="tu@correo.com" className="cotz-input"
                  value={guestForm.email} onChange={(e) => setGuestForm(f => ({...f, email: e.target.value}))} required />
                <input type="tel" placeholder="+57 300 1234567" className="cotz-input"
                  value={guestForm.whatsapp} onChange={(e) => setGuestForm(f => ({...f, whatsapp: e.target.value}))} required />
              </div>

              {error && <div style={{ marginTop: 10, fontSize: 13, color: "var(--danger-700)" }}>{error}</div>}

              <button type="submit" disabled={submitting} className="cotz-btn cotz-btn-primary" style={{ width: "100%", marginTop: 16, justifyContent: "center" }}>
                {submitting ? "Enviando..." : "Enviar mi cotización →"}
              </button>
              <button type="button" disabled={submitting} className="cotz-btn cotz-btn-ghost" style={{ width: "100%", marginTop: 6, justifyContent: "center" }} onClick={() => setShowGuestModal(false)}>
                Volver
              </button>
              <p style={{ marginTop: 12, fontSize: 11.5, color: "var(--fg-tertiary)", textAlign: "center" }}>
                ¿Ya tienes cuenta? <a href={(window.SELLU?.loginUrl || '/login')} style={{ color: "var(--navy-700)", fontWeight: 600 }}>Inicia sesión</a> para guardar todas tus cotizaciones.
              </p>
            </form>
          </div>
        )}
      </React.Fragment>
    );
  }

  window.CotizadorApp = App;
})();
