/* global React, LocationFields */
const { useState, useEffect, useRef, useCallback } = React;

// ------------------------------------------------------------
// Pactum products + role options + interest type
// ------------------------------------------------------------
const PRODUCTS = [
{ id: "abrir-escola", label: "Abrir uma escola", key: "1" },
{ id: "treinamento", label: "Treinamento de professores", key: "2" },
{ id: "consultoria", label: "Consultoria", key: "3" },
{ id: "curriculo", label: "Currículo", key: "4" }];


const ROLES = [
"Diretor",
"Coordenador pedagógico",
"Professor",
"Pai/Mãe",
"Outro"];


const INTEREST = [
{ id: "abrir", title: "Abrir uma escola", sub: "Fundar uma instituição cristã clássica", key: "A" },
{ id: "treinamento", title: "Treinamento de professores", sub: "Formação continuada para a equipe", key: "T" },
{ id: "ambos", title: "Ambos", sub: "Está interessado nas duas frentes", key: "B" }];


// ------------------------------------------------------------
// Phone mask: (xx) xxxxx-xxxx
// ------------------------------------------------------------
function maskPhone(v) {
  const d = v.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)}`;
}

function isValidEmail(v) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
}

// ------------------------------------------------------------
// Submission: posts to enviar.php which handles Kommo + email.
// In local/preview (file://, no PHP), falls back to demo mode.
// ------------------------------------------------------------
const ENDPOINT = "enviar.php";

async function submitLead(payload) {
  // Demo fallback when running without the PHP backend
  const isPreview = location.protocol === "file:" || location.hostname.endsWith(".sandbox.dev") || location.hostname.includes("localhost");
  if (isPreview && !window.__forceLive) {
    console.log("[DEMO] Lead payload →", payload);
    await new Promise((r) => setTimeout(r, 500));
    return { ok: true, id: `demo_${Date.now().toString(36)}` };
  }
  const r = await fetch(ENDPOINT, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload)
  });
  const data = await r.json().catch(() => ({}));
  if (!r.ok || !data.ok) throw new Error(data.error || "Falha no envio");
  return { ok: true, id: `lead_${Date.now().toString(36)}`, kommo: data.kommo, email: data.email };
}

// ------------------------------------------------------------
// Main form
// ------------------------------------------------------------
window.LeadForm = function LeadForm() {
  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [email, setEmail] = useState("");
  const [school, setSchool] = useState("");
  const [uf, setUf] = useState(null);
  const [city, setCity] = useState("");
  const [role, setRole] = useState("");
  const [roleOther, setRoleOther] = useState("");
  const [products, setProducts] = useState([]);
  const [interest, setInterest] = useState("");
  const [needs, setNeeds] = useState("");

  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(null); // { id }
  const [toast, setToast] = useState(null);
  const [count, setCount] = useState(() => {
    return parseInt(localStorage.getItem("pactum_lead_count") || "0", 10);
  });

  const nameRef = useRef(null);

  // Auto-focus name on mount + after reset
  useEffect(() => {
    if (!success) nameRef.current?.focus();
  }, [success]);

  // Toggle product
  const toggleProduct = useCallback((id) => {
    setProducts((p) => p.includes(id) ? p.filter((x) => x !== id) : [...p, id]);
  }, []);

  // Keyboard shortcuts
  useEffect(() => {
    function onKey(e) {
      // Ctrl/Cmd + Enter → submit
      if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
        e.preventDefault();
        if (success) {
          handleNewLead();
        } else {
          handleSubmit();
        }
        return;
      }
      // Esc on success → new lead
      if (e.key === "Escape" && success) {
        handleNewLead();
        return;
      }
      // Alt+1..4 toggle products — use e.code (Digit1) since macOS Alt+1 produces ¡
      if (e.altKey && !e.ctrlKey && !e.metaKey && !success) {
        const m = /^Digit([1-9])$/.exec(e.code || "");
        if (m) {
          const n = parseInt(m[1], 10);
          if (n >= 1 && n <= PRODUCTS.length) {
            e.preventDefault();
            toggleProduct(PRODUCTS[n - 1].id);
            return;
          }
        }
      }
      // Alt+A/T/B → interest — use e.code (KeyA, KeyT, KeyB)
      if (e.altKey && !e.ctrlKey && !e.metaKey && !success) {
        const m = /^Key([A-Z])$/.exec(e.code || "");
        if (m) {
          const k = m[1];
          const i = INTEREST.find((x) => x.key === k);
          if (i) {
            e.preventDefault();
            setInterest(i.id);
          }
        }
      }
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [success, toggleProduct]);

  function validate() {
    const errs = {};
    if (!name.trim()) errs.name = "Informe o nome.";
    if (!phone.trim()) errs.phone = "Informe o telefone.";else
    if (phone.replace(/\D/g, "").length < 10) errs.phone = "Telefone incompleto.";
    if (!email.trim()) errs.email = "Informe o e-mail.";else
    if (!isValidEmail(email.trim())) errs.email = "E-mail inválido.";
    if (!school.trim()) errs.school = "Informe a escola.";
    if (!uf) errs.uf = "Selecione o estado.";
    if (!city.trim()) errs.city = "Informe a cidade.";
    if (!role) errs.role = "Selecione o cargo.";
    if (role === "Outro" && !roleOther.trim()) errs.role = "Descreva o cargo.";
    if (products.length === 0) errs.products = "Selecione ao menos um produto.";
    if (!interest) errs.interest = "Selecione o tipo de interesse.";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }

  async function handleSubmit(e) {
    if (e?.preventDefault) e.preventDefault();
    if (submitting) return;
    if (!validate()) {
      setToast({ type: "error", msg: "Preencha os campos destacados." });
      setTimeout(() => setToast(null), 2400);
      return;
    }
    setSubmitting(true);
    const payload = {
      capturedAt: new Date().toISOString(),
      source: "evento-presencial",
      name: name.trim(),
      phone: phone.trim(),
      email: email.trim(),
      school: school.trim(),
      city: city.trim(),
      uf: uf?.sigla,
      ufName: uf?.nome,
      role: role === "Outro" ? roleOther.trim() : role,
      products: products.map((id) => PRODUCTS.find((p) => p.id === id)?.label),
      interest: INTEREST.find((i) => i.id === interest)?.title,
      needs: needs.trim()
    };
    try {
      const res = await submitLead(payload);
      const newCount = count + 1;
      setCount(newCount);
      localStorage.setItem("pactum_lead_count", String(newCount));
      setSuccess({ id: res.id, name: payload.name });
    } catch (err) {
      setToast({ type: "error", msg: "Falha no envio. Tente novamente." });
      setTimeout(() => setToast(null), 2400);
    } finally {
      setSubmitting(false);
    }
  }

  function handleNewLead() {
    setName("");setPhone("");setEmail("");setSchool("");
    setUf(null);setCity("");setRole("");setRoleOther("");
    setProducts([]);setInterest("");setNeeds("");
    setErrors({});
    setSuccess(null);
  }

  // ------------------------------------------------------------
  // SUCCESS STATE
  // ------------------------------------------------------------
  if (success) {
    return <SuccessScreen lead={success} count={count} onNew={handleNewLead} />;
  }

  // ------------------------------------------------------------
  // FORM
  // ------------------------------------------------------------
  return (
    <>
      <header className="app-header">
        <div className="shell">
          <div className="brand">
            <img src="assets/logo-pactum.png" alt="Pactum" className="brand-logo-full" />
          </div>
          <div className="session-meta">
            <div>Sessão · {new Date().toLocaleDateString("pt-BR", { day: "2-digit", month: "short" })}</div>
            <div><span className="count">{count}</span> {count === 1 ? "contato capturado" : "contatos capturados"}</div>
          </div>
        </div>
      </header>

      <main className="form-wrap">
        <div className="shell">
          <h1 className="form-title">Novo Contato</h1>
          <p className="form-sub">
            Use <kbd-inline>Tab</kbd-inline> para avançar
            e <kbd-inline>Ctrl + Enter</kbd-inline> para enviar.
          </p>

          <form onSubmit={handleSubmit} noValidate>
            {/* SECTION: contato */}
            <div className="section">
              <div className="section-label">Contato</div>

              <div className="row">
                <div className="field">
                  <label>Nome completo <span className="req">*</span></label>
                  <input
                    ref={nameRef}
                    className={`input ${errors.name ? "error" : ""}`}
                    type="text"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                    placeholder="Ex.: João da Silva Pereira"
                    autoComplete="off" />
                  
                  <div className="field-msg">{errors.name || ""}</div>
                </div>
              </div>

              <div className="row cols-2">
                <div className="field">
                  <label>Telefone (WhatsApp) <span className="req">*</span></label>
                  <input
                    className={`input ${errors.phone ? "error" : ""}`}
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(maskPhone(e.target.value))}
                    placeholder="(98) 98428-1268"
                    inputMode="tel"
                    autoComplete="off" />
                  
                  <div className="field-msg">{errors.phone || ""}</div>
                </div>
                <div className="field">
                  <label>E-mail <span className="req">*</span></label>
                  <input
                    className={`input ${errors.email ? "error" : ""}`}
                    type="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="nome@escola.com.br"
                    autoComplete="off" />
                  
                  <div className="field-msg">{errors.email || ""}</div>
                </div>
              </div>
            </div>

            {/* SECTION: escola */}
            <div className="section">
              <div className="section-label">Escola</div>

              <div className="row">
                <div className="field">
                  <label>Nome da escola <span className="req">*</span></label>
                  <input
                    className={`input ${errors.school ? "error" : ""}`}
                    type="text"
                    value={school}
                    onChange={(e) => setSchool(e.target.value)}
                    placeholder="Ex.: Escola Cristã Reformada"
                    autoComplete="off" />
                  
                  <div className="field-msg">{errors.school || ""}</div>
                </div>
              </div>

              <LocationFields
                uf={uf}
                setUf={setUf}
                city={city}
                setCity={setCity}
                errors={errors} />
              

              <div className="row cols-2">
                <div className="field">
                  <label>Cargo na escola <span className="req">*</span></label>
                  <select
                    className={`select ${errors.role ? "error" : ""}`}
                    value={role}
                    onChange={(e) => setRole(e.target.value)}>
                    
                    <option value="">Selecione…</option>
                    {ROLES.map((r) =>
                    <option key={r} value={r}>{r}</option>
                    )}
                  </select>
                  <div className="field-msg">{errors.role || ""}</div>
                </div>
                {role === "Outro" &&
                <div className="field">
                    <label>Qual cargo? <span className="req">*</span></label>
                    <input
                    className={`input ${errors.role ? "error" : ""}`}
                    type="text"
                    value={roleOther}
                    onChange={(e) => setRoleOther(e.target.value)}
                    placeholder="Descreva o cargo" />
                  
                    <div className="field-msg"></div>
                  </div>
                }
              </div>
            </div>

            {/* SECTION: interesse */}
            <div className="section">
              <div className="section-label">Interesse</div>

              <div className="field" style={{ marginBottom: 16 }}>
                <label>
                  Produtos da Pactum <span className="req">*</span>
                  <span className="key-hint">Alt + 1…4</span>
                </label>
                <div className="chip-group" role="group">
                  {PRODUCTS.map((p, i) =>
                  <button
                    type="button"
                    key={p.id}
                    className={`chip ${products.includes(p.id) ? "selected" : ""}`}
                    onClick={() => toggleProduct(p.id)}
                    aria-pressed={products.includes(p.id)}>
                    
                      {p.label}
                      <span className="chip-key">⌥{p.key}</span>
                    </button>
                  )}
                </div>
                <div className="field-msg">{errors.products || ""}</div>
              </div>

              <div className="field">
                <label>
                  Tipo de interesse <span className="req">*</span>
                  <span className="key-hint">Alt + A/T/B</span>
                </label>
                <div className="radio-cards">
                  {INTEREST.map((i) =>
                  <button
                    type="button"
                    key={i.id}
                    className={`radio-card ${interest === i.id ? "selected" : ""}`}
                    onClick={() => setInterest(i.id)}
                    aria-pressed={interest === i.id}>
                    
                      <span className="rc-key">⌥{i.key}</span>
                      <span className="rc-title">{i.title}</span>
                      <span className="rc-sub">{i.sub}</span>
                    </button>
                  )}
                </div>
                <div className="field-msg">{errors.interest || ""}</div>
              </div>
            </div>

            {/* SECTION: necessidades */}
            <div className="section">
              <div className="section-label">Programa de necessidades</div>
              <div className="field">
                <label>O que o lead descreveu como necessidade?</label>
                <textarea
                  className="textarea"
                  rows="4"
                  value={needs}
                  onChange={(e) => setNeeds(e.target.value)}
                  placeholder="Ex.: Igreja com ~120 famílias buscando fundar escola para 2027. Já tem espaço físico, falta currículo e formação de professores…" />
                
                <div className="field-msg"></div>
              </div>
            </div>
          </form>
        </div>
      </main>

      <footer className="actions">
        <div className="shell">
          <div className="shortcut-strip">
            <span><kbd>Tab</kbd> avançar</span>
            <span><kbd>↓</kbd>/<kbd>↑</kbd>/<kbd>Enter</kbd> em listas</span>
            <span><kbd>Alt</kbd>+<kbd>1…4</kbd> produtos</span>
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <button
              type="button"
              className="btn btn-ghost"
              onClick={handleNewLead}
              title="Limpar formulário">
              
              Limpar
            </button>
            <button
              type="button"
              className="btn btn-primary"
              onClick={handleSubmit}
              disabled={submitting}>
              
              {submitting ? "Enviando…" : "Salvar lead"}
              <kbd>Ctrl ↵</kbd>
            </button>
          </div>
        </div>
      </footer>

      {toast &&
      <div className={`toast ${toast.type || ""}`}>
          {toast.msg}
        </div>
      }
    </>);

};

// ------------------------------------------------------------
// Success screen
// ------------------------------------------------------------
function SuccessScreen({ lead, count, onNew }) {
  const [secs, setSecs] = useState(8);
  useEffect(() => {
    if (secs <= 0) {
      onNew();
      return;
    }
    const t = setTimeout(() => setSecs((s) => s - 1), 1000);
    return () => clearTimeout(t);
  }, [secs, onNew]);

  return (
    <>
      <header className="app-header">
        <div className="shell">
          <div className="brand">
            <img src="assets/logo-pactum.png" alt="Pactum" className="brand-logo-full" />
          </div>
          <div className="session-meta">
            <div><span className="count">{count}</span> contatos capturados</div>
            <div className="status-pill"><span className="dot"></span> Sincronizado</div>
          </div>
        </div>
      </header>

      <main className="form-wrap">
        <div className="shell">
          <div className="success">
            <div className="success-mark">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12"></polyline>
              </svg>
            </div>
            <h2>Lead salvo</h2>
            <p>{lead.name} foi enviado ao Kommo e notificado por e-mail.</p>
            <div className="success-meta">ID · {lead.id}</div>

            <div className="success-cta">
              <button className="btn btn-primary" onClick={onNew} autoFocus>
                Próximo lead <kbd>↵</kbd>
              </button>
              <span className="hint">
                Ou aguarde <span className="countdown">{secs}s</span> · <kbd-inline>Esc</kbd-inline> a qualquer momento
              </span>
            </div>
          </div>
        </div>
      </main>

      <footer className="actions">
        <div className="shell">
          <div className="shortcut-strip">
            <span><kbd>Enter</kbd> ou <kbd>Ctrl ↵</kbd> próximo lead</span>
            <span><kbd>Esc</kbd> reiniciar agora</span>
          </div>
          <div className="status-pill"><span className="dot"></span> Pronto para novo registro</div>
        </div>
      </footer>
    </>);

}