// ═══════════════════════════════════════════════════════════════════
// src/sections/CtaForm.jsx
// Final conversion section — lead capture form + contact options.
// Validation is local; submission wires to an HTTP endpoint or
// webhook by replacing the TODO comment below.
// ═══════════════════════════════════════════════════════════════════

const { useState: useFormState } = React;

// ── Phone mask ───────────────────────────────────────────────────────
function maskPhone(raw) {
  const d = raw.replace(/\D/g, "").slice(0, 11);
  if (d.length <= 2)  return d;
  if (d.length <= 6)  return `(${d.slice(0,2)}) ${d.slice(2)}`;
  if (d.length <= 10) return `(${d.slice(0,2)}) ${d.slice(2,6)}-${d.slice(6)}`;
  return                     `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}`;
}

// ── Validation rules ─────────────────────────────────────────────────
function validateForm(data) {
  const errors = {};
  if (!data.name.trim() || data.name.trim().length < 2) errors.name = "Informe seu nome";
  if (!data.phone.trim() || data.phone.replace(/\D/g, "").length < 10) errors.phone = "Informe um telefone válido";
  if (!data.service) errors.service = "Selecione um tratamento";
  return errors;
}

// ── Sub-components ────────────────────────────────────────────────────
function SuccessState({ firstName }) {
  return (
    <div className="form">
      <div className="form-success">
        <div className="check"><Icon.check width="28" height="28"/></div>
        <h3>Obrigado, {firstName}!</h3>
        <p>Recebemos seu pedido de avaliação.<br/>Em até 30 minutos entraremos em contato.</p>
        <a href={CONTACT.waLink} className="btn btn-primary" style={{ marginTop: "12px" }}
           target="_blank" rel="noopener noreferrer">
          <Icon.whatsapp className="wa-icon"/> Adiantar pelo WhatsApp
        </a>
      </div>
    </div>
  );
}

function LeadForm({ onSuccess }) {
  const [data, setData]     = useFormState({ name: "", phone: "", service: "", message: "" });
  const [errors, setErrors] = useFormState({});

  const set = (field) => (e) => setData({ ...data, [field]: e.target.value });

  const handleSubmit = (e) => {
    e.preventDefault();
    const errs = validateForm(data);
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    // TODO: replace with real API call, e.g.:
    // fetch("/api/leads", { method: "POST", body: JSON.stringify(data) });
    onSuccess(data.name.split(" ")[0]);
  };

  return (
    <form className="form" onSubmit={handleSubmit} noValidate>
      <div className={"field" + (errors.name ? " error" : "")}>
        <label htmlFor="f-name">Nome completo</label>
        <input id="f-name" type="text" value={data.name} onChange={set("name")}
               placeholder="Seu nome" autoComplete="name"/>
        {errors.name && <span className="error-text">{errors.name}</span>}
      </div>

      <div className="form-row">
        <div className={"field" + (errors.phone ? " error" : "")}>
          <label htmlFor="f-phone">WhatsApp</label>
          <input id="f-phone" type="tel" value={data.phone} autoComplete="tel"
                 onChange={(e) => setData({ ...data, phone: maskPhone(e.target.value) })}
                 placeholder="(11) 9 0000-0000"/>
          {errors.phone && <span className="error-text">{errors.phone}</span>}
        </div>

        <div className={"field" + (errors.service ? " error" : "")}>
          <label htmlFor="f-svc">Tratamento</label>
          <select id="f-svc" value={data.service} onChange={set("service")}>
            <option value="">Selecione</option>
            <option>Limpeza &amp; profilaxia</option>
            <option>Clareamento</option>
            <option>Aparelho ortodôntico</option>
            <option>Extração / siso</option>
            <option>Implante dentário</option>
            <option>Estética / lentes</option>
            <option>Outro / não sei</option>
          </select>
          {errors.service && <span className="error-text">{errors.service}</span>}
        </div>
      </div>

      <div className="field">
        <label htmlFor="f-msg">
          Mensagem <span style={{ textTransform: "none", color: "var(--ink-300)" }}>(opcional)</span>
        </label>
        <textarea id="f-msg" value={data.message} onChange={set("message")}
                  placeholder="Conte-nos o que você procura..."/>
      </div>

      <button type="submit" className="btn btn-primary">
        <Icon.whatsapp className="wa-icon"/> Quero minha avaliação gratuita
      </button>

      <div className="form-foot">
        Ao enviar você concorda com nossa <a href="#">política de privacidade</a>.<br/>
        Não compartilhamos seus dados.
      </div>
    </form>
  );
}

// ── Section ───────────────────────────────────────────────────────────
function CtaForm() {
  const [successName, setSuccessName] = useFormState(null);

  return (
    <section id="agendar" className="section">
      <div className="container">
        <div className="cta-form reveal">

          {/* Left copy */}
          <div>
            <div className="eyebrow">Avaliação gratuita</div>
            <h2 className="display" style={{ marginTop: "16px" }}>
              Vamos cuidar do<br/>seu sorriso <em>juntos.</em>
            </h2>
            <p className="lede">
              Preencha os dados ou fale direto pelo WhatsApp.
              Retornamos em até 30 minutos em horário comercial — sem robôs.
            </p>
            <div style={{ marginTop: "32px", display: "flex", gap: "12px", flexWrap: "wrap" }}>
              <a href={CONTACT.waLink} className="btn btn-primary"
                 target="_blank" rel="noopener noreferrer">
                <Icon.whatsapp className="wa-icon"/> WhatsApp direto
              </a>
              <a href={CONTACT.phoneLink} className="btn btn-ghost">
                <Icon.phone width="16" height="16"/> {CONTACT.phone}
              </a>
            </div>
          </div>

          {/* Right form */}
          {successName
            ? <SuccessState firstName={successName}/>
            : <LeadForm onSuccess={setSuccessName}/>
          }

        </div>
      </div>
    </section>
  );
}
