// ── Form, FAQ, Final CTA, Footer — Imersão Mundo China ──────

// Format BR mobile WhatsApp number progressively: (11) 99999-9999
function maskWhats(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 digitsOnly(v) { return (v || "").replace(/\D/g, ""); }
function validEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test((v || "").trim()); }

// VIP credential displaying the VIP ticket image with a 3D tilt and shine hover effect.
function VipCredential() {
  const cardRef = React.useRef(null);
  const [style, setStyle] = React.useState({
    transform: "perspective(1000px) rotate(-2.5deg) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)",
    transition: "transform 0.5s cubic-bezier(0.25, 1, 0.5, 1)"
  });
  const [shineStyle, setShineStyle] = React.useState({
    opacity: 0,
    background: "radial-gradient(circle at 50% 50%, rgba(255,255,255,0.2) 0%, transparent 60%)"
  });

  const handleMouseMove = (e) => {
    const card = cardRef.current;
    if (!card) return;
    const rect = card.getBoundingClientRect();
    const x = e.clientX - rect.left; // x position within the element
    const y = e.clientY - rect.top;  // y position within the element
    const xc = rect.width / 2;
    const yc = rect.height / 2;
    // Calculate rotation (-10 to 10 degrees)
    const rotateY = ((x - xc) / xc) * 10; 
    const rotateX = -((y - yc) / yc) * 10;

    setStyle({
      transform: `perspective(1000px) rotate(-2.5deg) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.04, 1.04, 1.04)`,
      transition: "transform 0.1s ease-out"
    });

    // Shine effect follows the cursor
    const shineX = (x / rect.width) * 100;
    const shineY = (y / rect.height) * 100;
    setShineStyle({
      opacity: 1,
      background: `radial-gradient(circle at ${shineX}% ${shineY}%, rgba(var(--go-3-rgb),0.3) 0%, transparent 65%)`
    });
  };

  const handleMouseLeave = () => {
    setStyle({
      transform: "perspective(1000px) rotate(-2.5deg) rotateX(0deg) rotateY(0deg) scale3d(1, 1, 1)",
      transition: "transform 0.5s cubic-bezier(0.25, 1, 0.5, 1)"
    });
    setShineStyle({
      opacity: 0,
      background: "radial-gradient(circle at 50% 50%, rgba(255,255,255,0.2) 0%, transparent 60%)",
      transition: "opacity 0.5s ease-out"
    });
  };

  return (
    <div 
      ref={cardRef}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
      style={{
        position: "relative",
        borderRadius: "16px",
        overflow: "hidden",
        cursor: "pointer",
        ...style,
        boxShadow: "0 22px 48px rgba(0,0,0,0.8), 0 0 0 1px rgba(var(--go-rgb),0.25)",
        transformStyle: "preserve-3d"
      }}
    >
      <img 
        src="assets/ticket-vip.jpg" 
        alt="Credencial VIP Imersão Mundo China" 
        style={{
          width: "100%",
          height: "auto",
          display: "block",
          borderRadius: "16px",
          pointerEvents: "none"
        }} 
      />
      {/* Shine overlay */}
      <div 
        style={{
          position: "absolute",
          inset: 0,
          pointerEvents: "none",
          mixBlendMode: "overlay",
          ...shineStyle,
          borderRadius: "16px"
        }} 
      />
    </div>
  );
}

function LeadForm({ innerRef }) {
  const [data, setData] = React.useState({ nome: "", whats: "", email: "", segmento: "", faturamento: "", jaCompra: "", interesse: "" });
  const [touched, setTouched] = React.useState({});
  const [focus, setFocus] = React.useState(null);

  const errors = {
    nome: data.nome.trim().length < 3 ? "Digite seu nome completo." : null,
    whats: digitsOnly(data.whats).length < 10 ? "Informe um WhatsApp válido com DDD." : null,
    email: !validEmail(data.email) ? "Informe um e-mail válido." : null,
  };
  const valid = !errors.nome && !errors.whats && !errors.email;

  const submit = (e) => {
    if (e) e.preventDefault();
    setTouched({ nome: true, whats: true, email: true });
    if (!valid) return;

    // Generate unique eventId for deduplication
    const eventId = 'lead_' + Date.now() + '_' + Math.random().toString(36).substring(2, 9);

    // Store lead credentials in localStorage for pre-filling checkout
    localStorage.setItem('leadData', JSON.stringify({
      name: data.nome,
      email: data.email,
      phone: data.whats
    }));

    // Trigger Meta Pixel Advanced Matching and Lead event
    if (window.initPixelAdvancedMatching) {
      window.initPixelAdvancedMatching(data.email, data.whats, data.nome);
    }
    if (window.trackPixelEvent) {
      window.trackPixelEvent('Lead', {}, { eventID: eventId });
    }

    // Call server webhook in background (fire-and-forget) to handle CAPI and LeadConnector CRM
    fetch('/api/webhook', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: data.nome,
        phone: data.whats,
        email: data.email,
        segmento: data.segmento,
        faturamento: data.faturamento,
        jaCompra: data.jaCompra,
        interesse: data.interesse,
        eventId: eventId,
        eventName: 'Lead'
      })
    }).catch(err => console.error('Error calling webhook:', err));

    // Redirect to selection page instantly
    window.location.href = "ingressos.html";
  };


  const setField = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const inputStyle = (k, err) => ({
    fontFamily: "var(--f-body)", fontSize: "1rem", padding: "14px 16px", borderRadius: "10px", background: "var(--deep)", color: "var(--txt-white)", outline: "none", width: "100%", boxSizing: "border-box",
    border: `1px solid ${err ? "var(--rd)" : (focus === k ? "var(--go-4)" : "rgba(176,124,37,0.20)")}`,
    boxShadow: focus === k ? "0 0 0 3px rgba(var(--go-rgb),0.15)" : "none",
    transition: "all .25s var(--ease-out)", WebkitAppearance: "none", appearance: "none",
  });

  const renderText = ({ k, ph, type = "text", autocomplete, inputmode, mask }) => {
    const showErr = touched[k] && errors[k];
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
        <label htmlFor={`pf-${k}`} style={{ position: "absolute", left: "-9999px" }}>{ph}</label>
        <input id={`pf-${k}`} placeholder={ph} value={data[k]} type={type} autoComplete={autocomplete} inputMode={inputmode}
          aria-invalid={showErr ? "true" : "false"}
          onChange={(e) => setField(k, mask ? mask(e.target.value) : e.target.value)}
          onFocus={() => setFocus(k)}
          onBlur={() => { setFocus(null); setTouched((t) => ({ ...t, [k]: true })); }}
          style={inputStyle(k, showErr)} />
        {showErr && <span role="alert" style={{ fontFamily: "var(--f-body)", fontSize: ".74rem", color: "var(--rd-4)", marginLeft: "2px" }}>{errors[k]}</span>}
      </div>
    );
  };

  const renderSelect = ({ k, label, options }) => (
    <div style={{ display: "flex", flexDirection: "column", gap: "6px", position: "relative" }}>
      <select id={`pf-${k}`} value={data[k]} onChange={(e) => setField(k, e.target.value)}
        onFocus={() => setFocus(k)} onBlur={() => setFocus(null)}
        style={{ ...inputStyle(k, false), color: data[k] ? "var(--txt-white)" : "var(--txt-dim)", cursor: "pointer", paddingRight: "40px" }}>
        <option value="" disabled>{label}</option>
        {options.map((o) => <option key={o} value={o} style={{ color: "#fff", background: "#0A0F1E" }}>{o}</option>)}
      </select>
      <span aria-hidden="true" style={{ position: "absolute", right: "16px", top: "17px", pointerEvents: "none", color: "var(--go-4)" }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9" /></svg>
      </span>
    </div>
  );

  return (
    <Section glow style={{ scrollMarginTop: "0" }}>
      <div ref={innerRef} style={{ position: "absolute", top: "-80px" }} />
      <div className="pf-form-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "48px", alignItems: "center" }}>
        <Reveal>
          <SectionTag n="07">Inscrição</SectionTag>
          <h2 className="pf-section-head" style={{ fontFamily: "var(--f-display)", fontWeight: 400, fontSize: "clamp(1.9rem,3.6vw,2.8rem)", lineHeight: 1.14, letterSpacing: "-0.015em", color: "var(--cream)", margin: "0 0 18px" }}>Garanta sua vaga<br />na Imersão Mundo China</h2>
          <p style={{ fontFamily: "var(--f-body)", fontSize: "1.05rem", lineHeight: 1.65, color: "var(--txt-body)", marginBottom: "32px" }}>O evento é presencial, nos dias <strong style={{ color: "var(--cream)" }}>24 e 25 de junho de 2026</strong>, em <strong style={{ color: "var(--cream)" }}>Alphaville</strong>, e as vagas podem ser limitadas. Preencha seus dados para receber as informações de participação.</p>
          <div className="pf-ticket-wrap" style={{ position: "relative", maxWidth: "440px", marginTop: "8px" }}>
            <div style={{ position: "absolute", inset: "-20px -10px -10px", background: "radial-gradient(ellipse at 50% 70%, rgba(var(--go-rgb),0.24), transparent 65%)", filter: "blur(8px)", pointerEvents: "none" }} />
            <div style={{ position: "relative" }}><VipCredential /></div>
            <div style={{ marginTop: "20px", display: "flex", alignItems: "center", gap: "12px", fontFamily: "var(--f-body)", fontWeight: 600, fontSize: ".66rem", letterSpacing: ".24em", textTransform: "uppercase", color: "var(--bronze)" }}>
              <span style={{ width: "26px", height: "1px", background: "var(--bronze)" }} />
              Sua credencial será emitida em seu nome
            </div>
          </div>
        </Reveal>
        <Reveal delay={0.1}>
          <form className="pf-form-card" noValidate onSubmit={submit}
            style={{ background: "linear-gradient(165deg, #151210 0%, #0A0907 100%)", border: "1px solid rgba(176,124,37,0.25)", borderRadius: "16px", padding: "32px", boxShadow: "0 28px 60px -28px rgba(0,0,0,0.85), inset 0 1px 0 rgba(var(--go-rgb),0.06)" }}>
            <>
                <div style={{ fontFamily: "var(--f-body)", fontWeight: 600, fontSize: ".66rem", letterSpacing: ".24em", textTransform: "uppercase", color: "var(--champagne)", marginBottom: "20px" }}>Entrar na lista de vagas</div>
                <div style={{ display: "flex", flexDirection: "column", gap: "14px" }}>
                  {renderText({ k: "nome", ph: "Nome completo", autocomplete: "name" })}
                  <div className="pf-field-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px" }}>
                    {renderText({ k: "whats", ph: "WhatsApp (com DDD)", type: "tel", autocomplete: "tel", inputmode: "tel", mask: maskWhats })}
                    {renderText({ k: "email", ph: "E-mail", type: "email", autocomplete: "email", inputmode: "email" })}
                  </div>
                  <div className="pf-field-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px" }}>
                    {renderSelect({ k: "segmento", label: "Segmento de atuação", options: ["Varejo / Loja física", "E-commerce", "Distribuidor / Atacado", "Infoproduto de produto físico", "Vendedor / Representante", "Outro"] })}
                    {renderSelect({ k: "faturamento", label: "Quanto fatura hoje", options: ["Ainda não faturo", "Até R$ 30 mil/mês", "R$ 30 mil - R$ 100 mil/mês", "R$ 100 mil - R$ 500 mil/mês", "Acima de R$ 500 mil/mês"] })}
                  </div>
                  <div className="pf-field-row" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px" }}>
                    {renderSelect({ k: "jaCompra", label: "Já importa ou compra?", options: ["Já importo da China", "Compro de fornecedor no Brasil", "Ainda não compro em volume"] })}
                    {renderSelect({ k: "interesse", label: "Principal interesse", options: ["Fornecedores", "Margem", "Feira de outubro", "Logística", "Networking", "Escala"] })}
                  </div>
                </div>
                <div style={{ marginTop: "18px" }}>
                  <Button variant="primary" size="md" shimmer onClick={submit} style={{ width: "100%", justifyContent: "center" }}>Garantir minha vaga →</Button>
                </div>
                <div style={{ fontFamily: "var(--f-body)", fontWeight: 500, fontSize: ".62rem", letterSpacing: ".18em", textTransform: "uppercase", color: "var(--bronze)", textAlign: "center", marginTop: "16px" }}>Seus dados estão seguros · só o que importa sobre o evento</div>
              </>
          </form>
        </Reveal>
      </div>
      <style>{`@media (max-width: 480px){ .pf-field-row { grid-template-columns: 1fr !important; } }`}</style>
    </Section>
  );
}

// ── FAQ ──
const FAQS = [
  { q: "O evento é presencial? Onde será?", a: "Sim, é totalmente presencial, na Alameda Tocantins, 956 - Alphaville Industrial, Barueri - SP (CEP 06455-020)." },
  { q: "Quais são as datas?", a: "Dois dias: 24 e 25 de junho de 2026." },
  { q: "É para iniciantes ou para quem já fatura?", a: "O foco é em quem já vende, já compra produtos ou quer escalar margem. Não é um curso de começar do zero: é para quem quer comprar com mais estratégia." },
  { q: "Preciso já importar da China atualmente?", a: "Não. Serve tanto para quem já importa quanto para quem hoje compra de fornecedor brasileiro e quer chegar mais perto da fonte." },
  { q: "Vai falar sobre fornecedores e negociação?", a: "Sim. É o coração da imersão: como enxergar fornecedores por trás dos intermediários e se preparar para negociar direto." },
  { q: "Vai me preparar para a feira de outubro?", a: "Sim. Um dos objetivos é chegar à maior feira de fornecedores do mundo, em outubro, sabendo exatamente o que procurar." },
  { q: "O cadastro já garante a vaga?", a: "O cadastro entra na lista de interesse. A vaga é confirmada ao concluir a inscrição, e o espaço é limitado." },
  { q: "É promessa de lucro rápido?", a: "Não, e fugimos disso de propósito. A imersão entrega visão, direção, networking e preparação para quem quer entender melhor compra, fornecedores e oportunidades no caminho China-Brasil." },
];
function FAQ() {
  const [open, setOpen] = React.useState(0);
  return (
    <Section>
      <SectionHead n="09" tag="Dúvidas" title="Antes de você perguntar." />
      <div style={{ marginTop: "40px", maxWidth: "780px" }}>
        {FAQS.map((f, i) => {
          const isOpen = open === i;
          return (
            <div key={i} style={{ borderBottom: "1px solid rgba(176,124,37,0.18)" }}>
              <button onClick={() => setOpen(isOpen ? -1 : i)}
                aria-expanded={isOpen}
                aria-controls={`pf-faq-a-${i}`}
                style={{ width: "100%", display: "flex", justifyContent: "space-between", alignItems: "center", gap: "16px", background: "none", border: "none", cursor: "pointer", padding: "22px 0", textAlign: "left", color: "inherit" }}>
                <span style={{ fontFamily: "var(--f-display)", fontWeight: 400, fontSize: "1.1rem", color: isOpen ? "var(--cream)" : "var(--txt-head)", letterSpacing: "-0.005em", lineHeight: 1.3 }}>{f.q}</span>
                <span aria-hidden="true" style={{ flexShrink: 0, color: "var(--go-4)", fontFamily: "var(--f-display)", fontSize: "1.6rem", lineHeight: 1, transform: isOpen ? "rotate(45deg)" : "none", transition: "transform .3s var(--ease-out)" }}>+</span>
              </button>
              <div id={`pf-faq-a-${i}`} role="region" style={{ display: "grid", gridTemplateRows: isOpen ? "1fr" : "0fr", transition: "grid-template-rows .4s var(--ease-out)" }}>
                <div style={{ overflow: "hidden", minHeight: 0 }}>
                  <p style={{ fontFamily: "var(--f-body)", fontSize: "1rem", lineHeight: 1.65, color: "var(--txt-soft)", margin: "0 0 22px" }}>{f.a}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </Section>
  );
}

// ── FINAL CTA ──
function FinalCTA({ onCta }) {
  return (
    <Section glow className="pf-section--final" style={{ textAlign: "center", padding: "120px 0" }}>
      <Reveal>
        <h2 className="pf-section-head" style={{ fontFamily: "var(--f-display)", fontWeight: 400, fontSize: "clamp(2rem,5vw,4rem)", lineHeight: 1.08, letterSpacing: "-0.015em", color: "var(--cream)", margin: "0 0 22px" }}>A China parece distante<br /><span style={{ color: "var(--go-4)", fontStyle: "italic" }}>até você entender quem está no meio do caminho.</span></h2>
        <p style={{ fontFamily: "var(--f-body)", fontSize: "clamp(1rem,1.4vw,1.15rem)", lineHeight: 1.65, color: "var(--txt-soft)", maxWidth: "660px", margin: "0 auto 36px" }}>Entre para a Imersão Mundo China e descubra como comprar com mais estratégia, negociar mais perto da fonte e se preparar para a feira de fornecedores em outubro.</p>
        <Button variant="primary" size="lg" onClick={onCta} shimmer>Garantir minha vaga →</Button>
      </Reveal>
    </Section>
  );
}

// ── FOOTER ──
function Footer() {
  return (
    <footer style={{ padding: "60px 0", borderTop: "1px solid rgba(176,124,37,0.18)", textAlign: "center", background: "var(--void)" }}>
      <Wrap>
        <div style={{ marginBottom: "20px" }}>
          <img src="assets/logo-mundo-china-footer.png" alt="Imersão Mundo China" style={{ height: "64px", width: "auto", filter: "drop-shadow(0 4px 12px rgba(0,0,0,0.5))" }} />
        </div>
        <div style={{ fontFamily: "var(--f-body)", fontWeight: 600, fontSize: ".7rem", letterSpacing: ".24em", textTransform: "uppercase", color: "var(--champagne)", marginBottom: "8px" }}>Evento presencial · 24 e 25 de Junho de 2026 · com Soong</div>
        <address style={{ fontFamily: "var(--f-body)", fontSize: ".78rem", letterSpacing: ".06em", color: "var(--txt-dim)", fontStyle: "normal" }}>Alameda Tocantins, 956 · Alphaville Industrial · Barueri, SP · CEP 06455-020</address>
      </Wrap>
    </footer>
  );
}

Object.assign(window, { LeadForm, FAQ, FinalCTA, Footer, VipCredential });
