// Fly Media — Cotizador
// Brief guiado: seleccionas opciones, cuentas el proyecto y se envía
// a alexperalta@flymedia.com.mx vía /api/cotizacion (Vercel Function).

const { useState } = React;
const { motion } = window.framerMotion;

const EASE = [0.16, 1, 0.3, 1];
const REDUCED = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const fadeRise = (delay = 0) => REDUCED ? {} : ({
  initial: { opacity: 0, y: 24, filter: 'blur(8px)' },
  animate: { opacity: 1, y: 0, filter: 'blur(0px)' },
  transition: { duration: 0.7, ease: EASE, delay }
});

// ---------- Iconos ----------
const Svg = ({ children, size = 20, stroke = 1.75, ...rest }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
       stroke="currentColor" strokeWidth={stroke}
       strokeLinecap="round" strokeLinejoin="round" {...rest}>
    {children}
  </svg>
);
const ArrowRight = (p) => <Svg {...p}><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></Svg>;
const ArrowLeft = (p) => <Svg {...p}><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></Svg>;
const Check = (p) => <Svg {...p}><polyline points="20 6 9 17 4 12" /></Svg>;
const WhatsAppIcon = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
  </svg>
);

// ---------- WhatsApp (config.js) ----------
const FLY = window.FLY_CONFIG || {};
const waLink = (msg) =>
  `https://wa.me/${FLY.whatsapp || ""}?text=${encodeURIComponent(msg || FLY.whatsappMsg || "Hola Fly Media, quiero información sobre un video.")}`;

// ---------- Opciones ----------
const SERVICIOS = [
  "Corporativo",
  "Producción con IA",
  "Inmobiliario",
  "Redes Sociales",
  "Evento",
  "Aún no estoy seguro"
];
const PLAZOS = ["Este mes", "En 1–3 meses", "Más adelante", "Sin fecha definida"];
const PRESUPUESTOS = [
  "Hasta $50 mil MXN",
  "$50–150 mil MXN",
  "$150–400 mil MXN",
  "Más de $400 mil MXN",
  "Necesito orientación"
];

// ---------- Componentes ----------
function ChipGroup({ options, value, onChange, name }) {
  return (
    <div className="chip-grid" role="radiogroup" aria-label={name}>
      {options.map((opt) => {
        const selected = value === opt;
        return (
          <button
            key={opt}
            type="button"
            role="radio"
            aria-checked={selected}
            className={`chip ${selected ? "chip-selected" : ""}`}
            onClick={() => onChange(opt)}
          >
            {selected && <Check size={14} stroke={2.5} />}
            {opt}
          </button>
        );
      })}
    </div>
  );
}

function Step({ num, title, hint, error, children, delay = 0 }) {
  return (
    <motion.section className="cot-step" {...fadeRise(delay)}>
      <div className="cot-step-head">
        <span className="cot-step-num">{num}</span>
        <div>
          <h2 className="cot-step-title">{title}</h2>
          {hint && <p className="cot-step-hint">{hint}</p>}
        </div>
      </div>
      {children}
      {error && <p className="cot-error" role="alert">{error}</p>}
    </motion.section>
  );
}

// ---------- Cotizador ----------
const EMPTY = {
  servicio: "", plazo: "", presupuesto: "",
  empresa: "", giro: "", detalle: "",
  nombre: "", email: "", telefono: "",
  website: "" // honeypot
};

function Cotizador() {
  const [form, setForm] = useState(EMPTY);
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState("idle"); // idle | sending | ok | error
  const set = (k) => (v) => setForm((f) => ({ ...f, [k]: v }));
  const setInput = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const validate = () => {
    const e = {};
    if (!form.servicio) e.servicio = "Elige una opción (o \"Aún no estoy seguro\").";
    if (!form.nombre.trim()) e.nombre = "Necesitamos tu nombre.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = "Escribe un correo válido para responderte.";
    return e;
  };

  const submit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length) {
      const first = document.querySelector(".cot-error");
      if (first) first.scrollIntoView({ behavior: "smooth", block: "center" });
      return;
    }
    setStatus("sending");
    try {
      const res = await fetch("/api/cotizacion", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form)
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.ok) throw new Error(data.error || "send failed");
      setStatus("ok");
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setStatus("error");
    }
  };

  if (status === "ok") {
    return (
      <motion.div className="cot-success" {...fadeRise(0)}>
        <div className="cot-success-ring"><Check size={30} stroke={2.25} /></div>
        <h2>Brief recibido.</h2>
        <p>
          Gracias, {form.nombre.split(" ")[0]}. Ya tenemos tu proyecto sobre la mesa.
          Te respondemos con una propuesta en menos de <strong>24 horas hábiles</strong>.
        </p>
        <div className="cta-btn-row">
          <a href="/" className="btn btn-ghost"><ArrowLeft size={16} /> Volver al sitio</a>
          <a href={waLink("Hola Fly Media, acabo de enviar un brief por el cotizador.")} target="_blank" rel="noopener" className="btn btn-primary btn-wa-solid">
            <WhatsAppIcon size={17} /> Adelantar por WhatsApp
          </a>
        </div>
      </motion.div>
    );
  }

  return (
    <form className="cot-form" onSubmit={submit} noValidate>
      <Step num="01" title="¿Qué tipo de video necesitas?" error={errors.servicio} delay={0.15}>
        <ChipGroup name="Tipo de video" options={SERVICIOS} value={form.servicio} onChange={set("servicio")} />
      </Step>

      <Step num="02" title="¿Para cuándo lo necesitas?" delay={0.22}>
        <ChipGroup name="Plazo" options={PLAZOS} value={form.plazo} onChange={set("plazo")} />
      </Step>

      <Step
        num="03"
        title="Presupuesto estimado"
        hint="Nos sirve para proponerte un alcance real, no para inflar el precio."
        delay={0.29}
      >
        <ChipGroup name="Presupuesto" options={PRESUPUESTOS} value={form.presupuesto} onChange={set("presupuesto")} />
      </Step>

      <Step num="04" title="Tu empresa y el proyecto" delay={0.36}>
        <div className="field-grid">
          <label className="field">
            <span>Empresa o marca</span>
            <input type="text" value={form.empresa} onChange={setInput("empresa")} placeholder="Nombre de la empresa" autoComplete="organization" />
          </label>
          <label className="field">
            <span>Giro o industria</span>
            <input type="text" value={form.giro} onChange={setInput("giro")} placeholder="Ej. inmobiliaria, restaurante, industria" />
          </label>
        </div>
        <label className="field">
          <span>Cuéntanos del proyecto <em>(opcional)</em></span>
          <textarea
            rows={5}
            value={form.detalle}
            onChange={setInput("detalle")}
            placeholder="Qué quieres comunicar, dónde se va a publicar, referencias que te gusten…"
          />
        </label>
      </Step>

      <Step num="05" title="¿A dónde te respondemos?" delay={0.43}>
        <div className="field-grid">
          <label className="field">
            <span>Tu nombre *</span>
            <input type="text" value={form.nombre} onChange={setInput("nombre")} placeholder="Nombre y apellido" autoComplete="name" />
            {errors.nombre && <span className="cot-error" role="alert">{errors.nombre}</span>}
          </label>
          <label className="field">
            <span>Correo *</span>
            <input type="email" value={form.email} onChange={setInput("email")} placeholder="tu@correo.com" autoComplete="email" />
            {errors.email && <span className="cot-error" role="alert">{errors.email}</span>}
          </label>
        </div>
        <label className="field">
          <span>WhatsApp o teléfono <em>(opcional)</em></span>
          <input type="tel" value={form.telefono} onChange={setInput("telefono")} placeholder="+52 614 000 0000" autoComplete="tel" />
        </label>
        {/* honeypot anti-spam: oculto para humanos */}
        <label className="cot-hp" aria-hidden="true">
          Website
          <input type="text" tabIndex={-1} autoComplete="off" value={form.website} onChange={setInput("website")} />
        </label>
      </Step>

      <motion.div className="cot-submit" {...fadeRise(0.5)}>
        <button type="submit" className="btn btn-primary btn-lg" disabled={status === "sending"}>
          {status === "sending" ? "Enviando…" : <>Enviar brief <ArrowRight size={16} /></>}
        </button>
        {status === "error" && (
          <p className="cot-error cot-error-send" role="alert">
            No pudimos enviar el brief. Inténtalo de nuevo o{" "}
            <a href={waLink()} target="_blank" rel="noopener">mándanos un WhatsApp</a>.
          </p>
        )}
        <p className="cot-foot-note">
          Respuesta en menos de 24 h hábiles · Sin compromiso
        </p>
      </motion.div>
    </form>
  );
}

// ---------- Página ----------
function App() {
  return (
    <>
      <header className="nav scrolled cot-nav">
        <a href="/" className="nav-logo" aria-label="Fly Media — Inicio">
          <img className="logo-mark" src="assets/logo-icon.png" alt="" />
          <img className="logo-wordmark" src="assets/logo-wordmark-dark.png" alt="" />
        </a>
        <a href="/" className="btn btn-ghost nav-cta">
          <ArrowLeft size={15} /> Volver al sitio
        </a>
      </header>

      <main className="cot-page">
        <motion.div className="cot-head" {...fadeRise(0)}>
          <div className="eyebrow"><span className="eyebrow-dot" />Cotizador</div>
          <h1>Cuéntanos<br />tu proyecto.</h1>
          <p className="cot-lead">
            Dos minutos. Seleccionas, nos cuentas y te armamos una propuesta
            con alcance real. Si prefieres algo más directo,{" "}
            <a href={waLink()} target="_blank" rel="noopener">escríbenos por WhatsApp</a>.
          </p>
        </motion.div>
        <Cotizador />
      </main>

      <a
        href={waLink()}
        target="_blank"
        rel="noopener"
        className="wa-fab"
        aria-label="Escríbenos por WhatsApp"
        title="Escríbenos por WhatsApp"
      >
        <WhatsAppIcon size={27} />
      </a>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
