// Interactive budget calculator

const CALC_OPTIONS = {
  type: [
    { id: "landing", label: "Landing / 1 página", desc: "Solo presentación", base: 250 },
    { id: "instit", label: "Sitio institucional", desc: "Multi-sección", base: 350 },
    { id: "tienda", label: "Tienda / Catálogo", desc: "Vendés online", base: 600 },
    { id: "sistema", label: "Sistema de gestión", desc: "Panel a medida", base: 1200 },
    { id: "app", label: "App móvil", desc: "iOS + Android", base: 1800 },
  ],
  pages: [
    { id: 1, label: "1–3", mult: 1 },
    { id: 2, label: "4–8", mult: 1.25 },
    { id: 3, label: "9–15", mult: 1.55 },
    { id: 4, label: "15+", mult: 1.9 },
  ],
  extras: [
    { id: "blog", label: "Blog con secciones", price: 80 },
    { id: "admin", label: "Panel administrador", price: 180 },
    { id: "pagos", label: "Pasarela de pagos", price: 120 },
    { id: "reservas", label: "Sistema de turnos / reservas", price: 220 },
    { id: "multi", label: "Multi-idioma", price: 90 },
    { id: "seo", label: "SEO avanzado + Analytics", price: 140 },
    { id: "ia", label: "Chatbot con IA", price: 280 },
    { id: "auto", label: "Automatizaciones (mails, WhatsApp)", price: 200 },
    { id: "api", label: "Integraciones por API", price: 250 },
    { id: "users", label: "Usuarios y roles", price: 200 },
  ],
  speed: [
    { id: "normal", label: "Normal", desc: "3–4 semanas", mult: 1 },
    { id: "rapid", label: "Rápido", desc: "1–2 semanas", mult: 1.2 },
    { id: "express", label: "Express", desc: "5–7 días", mult: 1.45 },
  ],
};

function Calculator() {
  const [type, setType] = React.useState("instit");
  const [pages, setPages] = React.useState(2);
  const [extras, setExtras] = React.useState(["seo", "admin"]);
  const [speed, setSpeed] = React.useState("normal");
  const [bump, setBump] = React.useState(false);

  const t = CALC_OPTIONS.type.find((x) => x.id === type);
  const p = CALC_OPTIONS.pages.find((x) => x.id === pages);
  const s = CALC_OPTIONS.speed.find((x) => x.id === speed);
  const extraSum = CALC_OPTIONS.extras
    .filter((e) => extras.includes(e.id))
    .reduce((a, b) => a + b.price, 0);

  const subtotal = t.base * p.mult + extraSum;
  const total = Math.round(subtotal * s.mult);
  const totalLow = Math.round(total * 0.92);
  const totalHigh = Math.round(total * 1.08);

  React.useEffect(() => {
    setBump(true);
    const id = setTimeout(() => setBump(false), 220);
    return () => clearTimeout(id);
  }, [total]);

  const toggleExtra = (id) => {
    setExtras((curr) => (curr.includes(id) ? curr.filter((x) => x !== id) : [...curr, id]));
  };

  const fmt = (n) => "$" + n.toLocaleString("es-AR");

  const summaryMsg = `Hola DINI! Cotización con la calculadora:
• Tipo: ${t.label}
• Páginas: ${p.label}
• Extras: ${extras.length ? CALC_OPTIONS.extras.filter(e => extras.includes(e.id)).map(e => e.label).join(", ") : "ninguno"}
• Tiempo: ${s.label} (${s.desc})
• Estimado: ${fmt(totalLow)} – ${fmt(totalHigh)} USD

¿Podemos avanzar?`;

  return (
    <section id="calculadora" data-screen-label="Calculadora">
      <div className="shell">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span><span>Calculadora interactiva</span></span>
          <h2 className="h-section">
            Estimá tu proyecto en{" "}
            <span className="mark-accent">menos de un minuto</span>.
          </h2>
          <p className="lede">
            Movés un par de opciones, ves el precio. Si te gusta, lo enviás directo
            a WhatsApp y te respondemos con un presupuesto formal.
          </p>
        </div>

        <div className="calc-wrap">
          <div className="calc-form">
            {/* TIPO */}
            <div className="calc-row">
              <div className="calc-label">
                <span className="calc-label-text">¿Qué necesitás?</span>
                <span className="calc-label-help">Elegí lo que más se acerca</span>
              </div>
              <div className="opt-list">
                {CALC_OPTIONS.type.map((x) => (
                  <button
                    key={x.id}
                    className={"opt-check" + (type === x.id ? " active" : "")}
                    onClick={() => setType(x.id)}
                  >
                    <div>
                      <div style={{ fontWeight: 500 }}>{x.label}</div>
                      <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{x.desc}</div>
                    </div>
                    <span className="price">desde ${x.base}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* PÁGINAS */}
            <div className="calc-row">
              <div className="calc-label">
                <span className="calc-label-text">Cantidad de páginas o secciones</span>
                <span className="calc-label-help">Aproximado, no es estricto</span>
              </div>
              <div className="opt-grid opt-grid-3" style={{ gridTemplateColumns: "repeat(4, 1fr)" }}>
                {CALC_OPTIONS.pages.map((x) => (
                  <button
                    key={x.id}
                    className={"opt" + (pages === x.id ? " active" : "")}
                    onClick={() => setPages(x.id)}
                    style={{ alignItems: "center", textAlign: "center" }}
                  >
                    <span style={{ fontFamily: "var(--font-display)", fontSize: 22, fontWeight: 600 }}>{x.label}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* EXTRAS */}
            <div className="calc-row">
              <div className="calc-label">
                <span className="calc-label-text">Funciones extras</span>
                <span className="calc-label-help">Marcá las que necesites</span>
              </div>
              <div className="opt-grid">
                {CALC_OPTIONS.extras.map((x) => (
                  <button
                    key={x.id}
                    className={"opt-check" + (extras.includes(x.id) ? " active" : "")}
                    onClick={() => toggleExtra(x.id)}
                  >
                    <span>{x.label}</span>
                    <span className="price">+${x.price}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* VELOCIDAD */}
            <div className="calc-row">
              <div className="calc-label">
                <span className="calc-label-text">¿Para cuándo lo necesitás?</span>
                <span className="calc-label-help">Tiempos aproximados</span>
              </div>
              <div className="opt-grid opt-grid-3">
                {CALC_OPTIONS.speed.map((x) => (
                  <button
                    key={x.id}
                    className={"opt" + (speed === x.id ? " active" : "")}
                    onClick={() => setSpeed(x.id)}
                  >
                    <span style={{ fontWeight: 500 }}>{x.label}</span>
                    <small>{x.desc}</small>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* SUMMARY */}
          <div className="calc-summary">
            <div>
              <div className="calc-est-label">Estimado de tu proyecto</div>
              <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 10 }}>
                <span className={"calc-est-amount" + (bump ? " bump" : "")}>
                  {fmt(totalLow)}
                </span>
                <span style={{ color: "var(--ink-3)", fontSize: 18, fontFamily: "var(--font-display)" }}>–</span>
                <span className="calc-est-amount" style={{ fontSize: "clamp(28px, 3.4vw, 42px)" }}>
                  {fmt(totalHigh)}
                </span>
              </div>
              <div className="calc-est-suffix" style={{ marginTop: 6 }}>USD · pago único</div>
            </div>

            <div className="calc-breakdown">
              <div className="row"><span>Base ({t.label})</span><b>{fmt(t.base)}</b></div>
              <div className="row"><span>Tamaño ({p.label} pág.)</span><b>×{p.mult}</b></div>
              {extras.length > 0 && (
                <div className="row"><span>Extras ({extras.length})</span><b>+{fmt(extraSum)}</b></div>
              )}
              <div className="row"><span>Tiempo ({s.label})</span><b>×{s.mult}</b></div>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <a
                href={window.DINI.waUrl(summaryMsg)}
                target="_blank"
                rel="noopener noreferrer"
                className="btn btn-primary"
                style={{ width: "100%", justifyContent: "center" }}
              >
                Enviar por WhatsApp <IconArrow size={14} />
              </a>
              <a
                href="#contacto"
                className="btn btn-ghost btn-sm"
                style={{ width: "100%", justifyContent: "center" }}
              >
                Pedir presupuesto formal
              </a>
            </div>

            <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.5 }}>
              Es un estimado de referencia. El presupuesto final depende de detalles
              que conversamos juntos. Sin compromiso.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Calculator });
