/* =====================================================================
   QuoteResult.jsx — pantalla de resultado de la cotización.
   ===================================================================== */
const QR = window.Cotizador;

function StatBig({ label, value, sub }) {
  return (
    <div style={{ flex: 1, minWidth: 200 }}>
      <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--accent-500)" }}>{label}</div>
      <div style={{ fontFamily: "var(--font-display)", fontSize: 40, lineHeight: 1.05, fontWeight: 600, letterSpacing: "-0.02em", color: "var(--paper)", marginTop: 10, fontVariantNumeric: "tabular-nums" }}>{value}</div>
      {sub && <div style={{ fontSize: 13.5, color: "rgba(251,250,247,0.7)", marginTop: 8 }}>{sub}</div>}
    </div>
  );
}

function IncludedChip({ icon, label }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 500, color: "var(--navy-900)", background: "var(--white)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-pill)", padding: "7px 14px" }}>
      <Icon name={icon} size={14} color="var(--success-700)" /> {label}
    </span>
  );
}

function QuoteResult({ state, quoteId, shareUrl, onEditStep, onRestart, readOnly }) {
  const quote = QR.calculateQuote(state);
  const time = QR.calculateTime(state);
  const breakdown = QR.buildBreakdown(state);
  const [openBreakdown, setOpenBreakdown] = useStateUI(!readOnly ? false : true);
  const [showCal, setShowCal] = useStateUI(false);
  const [showStripe, setShowStripe] = useStateUI(false);
  const [showEmail, setShowEmail] = useStateUI(false);
  const [copied, setCopied] = useStateUI(false);

  if (!quote || time == null) {
    return <div style={{ padding: 48, textAlign: "center", color: "var(--fg-tertiary)" }}>Cotización incompleta.</div>;
  }

  const platform = QR.PLATFORMS[state.platform];
  const rec = QR.recommendPlatform(state.projectType, state.scale);
  const wasRecommended = state.platform === rec.platform;
  const deposit = Math.round(quote.mid * 0.5);
  const internal = QR.internalEstimate(state, quote.mid);
  const buildSubtotal = breakdown.filter(it => it.kind === "base" || it.kind === "platform").reduce((a, it) => a + it.amount, 0);
  const extrasSubtotal = breakdown.filter(it => !it.kind && it.amount !== 0).reduce((a, it) => a + it.amount, 0);

  // semanas hábiles aprox
  const weeks = Math.max(1, Math.round(time / 5));

  function copyShare() {
    const url = shareUrl || (location.origin + location.pathname + "?cotizacion=" + quoteId);
    const done = () => { setCopied(true); setTimeout(() => setCopied(false), 2000); };
    try {
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(url).then(done, done);
      } else {
        const ta = document.createElement("textarea"); ta.value = url; document.body.appendChild(ta); ta.select();
        try { document.execCommand("copy"); } catch (e) {}
        document.body.removeChild(ta); done();
      }
    } catch (e) { done(); }
  }

  return (
    <div style={{ maxWidth: 860, margin: "0 auto", padding: "0 20px 64px" }}>
      {/* Cabecera */}
      <div style={{ textAlign: "center", paddingTop: readOnly ? 24 : 8, marginBottom: 24 }}>
        <Eyebrow style={{ marginBottom: 10 }}>{readOnly ? "Cotización guardada" : "Tu estimado está listo"}</Eyebrow>
        <h1 style={{ fontFamily: "var(--font-display)", fontSize: 34, lineHeight: "40px", letterSpacing: "-0.02em", fontWeight: 600, color: "var(--navy-900)", margin: 0 }}>
          {QR.PROJECT_TYPES[state.projectType].label} en {platform ? platform.label : "—"}
        </h1>
        <div style={{ marginTop: 10, fontSize: 13, color: "var(--fg-tertiary)", display: "inline-flex", alignItems: "center", gap: 8 }}>
          <span>Folio</span>
          <span style={{ fontFamily: "var(--font-mono)", color: "var(--navy-900)", background: "var(--paper-2)", padding: "2px 8px", borderRadius: "var(--radius-xs)" }}>{quoteId}</span>
        </div>
      </div>

      {/* HERO precio + tiempo (banda navy) */}
      <div style={{ background: "var(--navy-700)", borderRadius: "var(--radius-xl)", padding: "32px 32px", boxShadow: "var(--shadow-lg)", position: "relative", overflow: "hidden" }}>
        <div style={{ display: "flex", gap: 32, flexWrap: "wrap", position: "relative", zIndex: 1 }}>
          <StatBig label="Inversión estimada" value={QR.fmtUSD(quote.min) + " – " + QR.fmtUSD(quote.max)} sub={"USD · rango según alcance final · ~" + QR.fmtUSD(quote.mid) + " promedio"} />
          <div style={{ width: 1, background: "rgba(251,250,247,0.16)", alignSelf: "stretch" }} />
          <StatBig label="Tiempo de entrega" value={time + " días"} sub={"hábiles · aprox. " + weeks + " semana" + (weeks > 1 ? "s" : "") + " de trabajo"} />
        </div>
      </div>

      {/* Split construcción vs. extras — evita leer el total como "precio de la página" */}
      {extrasSubtotal > 0 && (
        <div style={{ marginTop: 12, display: "flex", gap: 10, flexWrap: "wrap" }}>
          <div style={{ flex: 1, minWidth: 200, display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", background: "var(--white)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-xs)" }}>
            <Icon name="layout-template" size={16} color="var(--navy-700)" />
            <span style={{ flex: 1, fontSize: 13.5, color: "var(--fg-secondary)" }}>Construcción del sitio</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 600, color: "var(--navy-900)", fontVariantNumeric: "tabular-nums" }}>{QR.fmtUSD(buildSubtotal)}</span>
          </div>
          <div style={{ flex: 1, minWidth: 200, display: "flex", alignItems: "center", gap: 10, padding: "12px 16px", background: "var(--white)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-xs)" }}>
            <Icon name="plus-circle" size={16} color="var(--fg-tertiary)" />
            <span style={{ flex: 1, fontSize: 13.5, color: "var(--fg-secondary)" }}>Servicios adicionales</span>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 600, color: "var(--navy-900)", fontVariantNumeric: "tabular-nums" }}>{QR.fmtUSD(extrasSubtotal)}</span>
          </div>
        </div>
      )}

      {/* Plataforma recomendada y por qué */}
      <div style={{ marginTop: 16, background: "var(--white)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", padding: "20px 22px", display: "flex", gap: 14, alignItems: "flex-start", boxShadow: "var(--shadow-sm)" }}>
        <span style={{ flex: "none", width: 40, height: 40, borderRadius: "var(--radius-md)", background: "var(--paper-2)", color: "var(--navy-700)", display: "flex", alignItems: "center", justifyContent: "center" }}>
          <Icon name="layers" size={20} />
        </span>
        <div style={{ flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
            <span style={{ fontSize: 15, fontWeight: 600, color: "var(--navy-900)" }}>Plataforma: {platform ? platform.label : "—"}</span>
            {wasRecommended && <span style={{ fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 999, background: "var(--accent-100)", color: "var(--accent-700)" }}>Recomendada</span>}
          </div>
          <p style={{ marginTop: 6, fontSize: 14, lineHeight: "21px", color: "var(--fg-secondary)" }}>{rec.reason}</p>
        </div>
        {!readOnly && (
          <button type="button" className="cotz-linkbtn" onClick={() => onEditStep(3)}>Cambiar</button>
        )}
      </div>

      {/* Desglose colapsable */}
      <div style={{ marginTop: 16, background: "var(--white)", border: "1px solid var(--border-default)", borderRadius: "var(--radius-lg)", overflow: "hidden", boxShadow: "var(--shadow-sm)" }}>
        <button type="button" onClick={() => setOpenBreakdown(o => !o)} aria-expanded={openBreakdown} style={{
          width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "18px 22px", background: "transparent",
          border: "none", cursor: "pointer", fontFamily: "var(--font-sans)", textAlign: "left",
        }}>
          <Icon name="receipt-text" size={18} color="var(--navy-700)" />
          <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: "var(--navy-900)" }}>¿Qué incluye este precio?</span>
          <span style={{ transform: openBreakdown ? "rotate(180deg)" : "none", transition: "transform 200ms var(--ease-out)", color: "var(--fg-tertiary)", display: "inline-flex" }}>
            <Icon name="chevron-down" size={18} />
          </span>
        </button>
        {openBreakdown && (() => {
          const buildItems = breakdown.filter(it => it.kind === "base" || it.kind === "platform");
          const extraItems = breakdown.filter(it => !it.kind && it.amount !== 0);
          const includedItems = breakdown.filter(it => it.kind === "included");
          const buildSubtotal = buildItems.reduce((a, it) => a + it.amount, 0);
          const extraSubtotal = extraItems.reduce((a, it) => a + it.amount, 0);

          const Row = ({ item }) => (
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderTop: "1px solid var(--border-subtle)", fontSize: 14 }}>
              {item.kind === "included"
                ? <Icon name="check" size={15} color="var(--success-700)" strokeWidth={2.5} />
                : <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--navy-400)", flex: "none" }} />}
              <span style={{ flex: 1, color: item.kind === "included" ? "var(--fg-tertiary)" : "var(--navy-900)" }}>{item.label}</span>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13.5, color: item.amount === 0 ? "var(--fg-muted)" : "var(--navy-900)", fontVariantNumeric: "tabular-nums" }}>
                {item.amount === 0 ? "Incluido" : (item.amount > 0 ? "+" : "−") + QR.fmtUSD(Math.abs(item.amount))}
              </span>
            </div>
          );
          const GroupHead = ({ children, subtotal }) => (
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", paddingTop: 18, paddingBottom: 2 }}>
              <span style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", color: "var(--fg-tertiary)" }}>{children}</span>
              {subtotal != null && <span style={{ fontFamily: "var(--font-mono)", fontSize: 13, fontWeight: 600, color: "var(--navy-900)", fontVariantNumeric: "tabular-nums" }}>{QR.fmtUSD(subtotal)}</span>}
            </div>
          );

          return (
            <div style={{ padding: "0 22px 16px", animation: "cotz-step 200ms var(--ease-out)" }}>
              <GroupHead subtotal={buildSubtotal}>Construcción del sitio</GroupHead>
              {buildItems.map((item, i) => <Row key={"b" + i} item={item} />)}

              {extraItems.length > 0 && (
                <React.Fragment>
                  <GroupHead subtotal={extraSubtotal}>Servicios adicionales (opcionales)</GroupHead>
                  {extraItems.map((item, i) => <Row key={"e" + i} item={item} />)}
                </React.Fragment>
              )}

              <GroupHead>Incluido sin costo</GroupHead>
              {includedItems.map((item, i) => <Row key={"i" + i} item={item} />)}

              <div style={{ display: "flex", justifyContent: "space-between", padding: "14px 0 4px", marginTop: 8, borderTop: "1.5px solid var(--border-strong)", fontSize: 15, fontWeight: 600, color: "var(--navy-900)" }}>
                <span>Estimado central</span>
                <span style={{ fontFamily: "var(--font-mono)", fontVariantNumeric: "tabular-nums" }}>{QR.fmtUSD(quote.mid)} USD</span>
              </div>
            </div>
          );
        })()}
      </div>

      {/* Compliance / siempre incluido */}
      <div style={{ marginTop: 16, padding: "18px 20px", background: "var(--paper-2)", borderRadius: "var(--radius-lg)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <Icon name="shield-check" size={16} color="var(--navy-700)" />
          <span style={{ fontSize: 13.5, fontWeight: 600, color: "var(--navy-900)" }}>Compliance legal incluido en toda cotización</span>
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          <IncludedChip icon="file-text" label="Términos y condiciones" />
          <IncludedChip icon="lock" label="Aviso de privacidad" />
          <IncludedChip icon="cookie" label="Política de cookies" />
        </div>
      </div>

      {/* Vista interna — SOLO equipo Sell-U, nunca en la vista compartida del cliente */}
      {!readOnly && (
        <div style={{ marginTop: 16, border: "1.5px dashed var(--navy-400)", borderRadius: "var(--radius-lg)", background: "var(--navy-50)", overflow: "hidden" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "14px 20px", borderBottom: "1px dashed var(--navy-300)" }}>
            <Icon name="eye-off" size={15} color="var(--navy-700)" />
            <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--navy-700)" }}>Vista interna · equipo Sell-U</span>
            <span style={{ marginLeft: "auto", fontSize: 11, fontWeight: 600, padding: "3px 9px", borderRadius: 999, background: "var(--navy-700)", color: "var(--paper)" }}>No visible para el cliente</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 1, background: "var(--navy-200)" }} className="cotz-internal-grid">
            {[
              { k: "Horas de producción", v: internal.hours + " h", s: "Fijas para " + QR.PROJECT_TYPES[state.projectType].label.toLowerCase() },
              { k: "Costo de producción", v: QR.fmtUSD(internal.cost), s: internal.hours + " h × " + QR.fmtUSD(internal.rate) + "/h" },
              { k: "Margen estimado", v: QR.fmtUSD(internal.margin), s: "≈ " + internal.marginPct + "% sobre " + QR.fmtUSD(quote.mid), pos: internal.margin >= 0 },
            ].map((m, i) => (
              <div key={i} style={{ background: "var(--navy-50)", padding: "16px 20px" }}>
                <div style={{ fontSize: 11.5, fontWeight: 600, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--navy-600)" }}>{m.k}</div>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 24, fontWeight: 600, letterSpacing: "-0.01em", marginTop: 6, color: m.pos === false ? "var(--danger-700)" : "var(--navy-900)", fontVariantNumeric: "tabular-nums" }}>{m.v}</div>
                <div style={{ fontSize: 12, color: "var(--fg-tertiary)", marginTop: 4 }}>{m.s}</div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* CTAs */}
      {!readOnly && (
        <div style={{ marginTop: 24 }}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }} className="cotz-cta-grid">
            <button type="button" className="cotz-btn cotz-btn-lg cotz-btn-secondary" style={{ justifyContent: "center" }} onClick={() => setShowCal(true)}>
              <Icon name="calendar" size={18} /> Agendar llamada
            </button>
            <button type="button" className="cotz-btn cotz-btn-lg cotz-btn-primary" style={{ justifyContent: "center" }} onClick={() => setShowStripe(true)}>
              <Icon name="zap" size={18} /> Bloquear cupo con 50%
            </button>
          </div>
          <div style={{ display: "flex", justifyContent: "center", gap: 24, marginTop: 18, flexWrap: "wrap" }}>
            <button type="button" className="cotz-linkbtn" onClick={() => setShowEmail(true)}>
              <Icon name="mail" size={15} /> Enviarme esta cotización por email
            </button>
            <button type="button" className="cotz-linkbtn" onClick={copyShare}>
              <Icon name={copied ? "check" : "link"} size={15} /> {copied ? "¡Enlace copiado!" : "Compartir cotización"}
            </button>
          </div>
        </div>
      )}

      {readOnly && (
        <div style={{ marginTop: 24, textAlign: "center" }}>
          <button type="button" className="cotz-btn cotz-btn-lg cotz-btn-primary" style={{ justifyContent: "center" }} onClick={onRestart}>
            Crear mi propia cotización →
          </button>
        </div>
      )}

      {!readOnly && (
        <div style={{ marginTop: 28, textAlign: "center" }}>
          <button type="button" className="cotz-linkbtn" onClick={onRestart} style={{ color: "var(--fg-tertiary)" }}>
            <Icon name="rotate-ccw" size={14} /> Empezar de nuevo
          </button>
        </div>
      )}

      <CalendlyModal open={showCal} onClose={() => setShowCal(false)} />
      <StripeModal open={showStripe} onClose={() => setShowStripe(false)} deposit={deposit} />
      <EmailModal open={showEmail} onClose={() => setShowEmail(false)} />
    </div>
  );
}

Object.assign(window, { QuoteResult });
