// OZ — LP de captura para grupo de WhatsApp (CPA Chinesa)
// Hero único, mobile-first.

const { useState, useEffect, useMemo, useRef } = React;
const { useTweaks, TweaksPanel, TweakSection, TweakColor, TweakSlider, TweakToggle, TweakRadio, TweakText } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#d0d0d0",
  "headline": "primary",
  "aurora": 55,
  "grain": true,
  "showLogo": true,
  "members": 1284,
  "ctaLabel": "Quero entrar no grupo"
} /*EDITMODE-END*/;

// Headline variants — all built from the user's copy
const HEADLINES = {
  primary:
  <>
    <span className="accent">5k/mês</span> no seu{" "}
    <span style={{ whiteSpace: "nowrap" }}>primeiro mês</span><br />
    com CPA chinesa{" "}<span style={{ whiteSpace: "nowrap" }}>— <em>do zero!</em></span>
  </>,

  bold:
  <>
    <span className="accent">5k/mês</span> no seu{" "}
    <span style={{ whiteSpace: "nowrap" }}>primeiro mês</span><br />
    com CPA chinesa{" "}<span style={{ whiteSpace: "nowrap" }}>— <em>do zero!</em></span>
  </>,

  loud:
  <>
    Do <span className="strike">CLT</span><br />
    ao <em className="accent">CPA chinesa</em>.
  </>

};

// ───────── Phone mask (BR) ─────────
function maskPhone(value) {
  const digits = (value || "").replace(/\D/g, "").slice(0, 11);
  const a = digits.slice(0, 2);
  const b = digits.slice(2, 7);
  const c = digits.slice(7, 11);
  if (digits.length <= 2) return digits.length ? `(${a}` : "";
  if (digits.length <= 7) return `(${a}) ${b}`;
  return `(${a}) ${b}-${c}`;
}

function isValidPhone(value) {
  const d = (value || "").replace(/\D/g, "");
  return d.length === 10 || d.length === 11;
}

// ───────── Inline icons ─────────
const IcoUser = () =>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="8" r="3.5" />
    <path d="M4.5 20a7.5 7.5 0 0 1 15 0" />
  </svg>;

const IcoPhone = () =>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 4h3l2 5-2.5 1.5a11 11 0 0 0 6 6L15 14l5 2v3a2 2 0 0 1-2 2A15 15 0 0 1 3 6a2 2 0 0 1 2-2z" />
  </svg>;

const IcoLock = () =>
<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="4.5" y="11" width="15" height="9.5" rx="2.5" />
    <path d="M8 11V8a4 4 0 0 1 8 0v3" />
  </svg>;

const IcoCheck = () =>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 12.5l4.5 4.5L19 7.5" />
  </svg>;


// ───────── Success state ─────────
function SuccessCard({ name, onReset }) {
  const firstName = (name || "").trim().split(/\s+/)[0] || "tudo certo";
  const WA_LINK = "https://chat.whatsapp.com/FgaPLFPnyrXKpUoI0Ifp5P?mode=gi_t";
  const [count, setCount] = useState(5);
  useEffect(() => {
    if (count <= 0) {
      window.location.href = WA_LINK;
      return;
    }
    const t = setTimeout(() => setCount((c) => c - 1), 1000);
    return () => clearTimeout(t);
  }, [count]);

  return (
    <div className="success-card" role="status" aria-live="polite">
      <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
        <div className="ring"><IcoCheck /></div>
        <div>
          <h3 style={{ marginBottom: 2 }}>Quase lá, {firstName}.</h3>
          <p style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--ink-dim)" }}>
            Vaga reservada · #OZ-{String(Math.floor(1000 + Math.random() * 8999))}
          </p>
        </div>
      </div>
      <p>
        Abrindo o WhatsApp em <b style={{ color: "var(--accent)", fontFamily: "var(--mono)" }}>{count}s</b>.
        Se nada acontecer, toque no botão abaixo.
      </p>
      <div style={{ display: "flex", gap: 10 }}>
        <a
          href={WA_LINK}
          target="_blank"
          rel="noopener noreferrer"
          style={{
            flex: 1,
            display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
            padding: "14px 16px",
            borderRadius: 12,
            background: "var(--accent)",
            color: "#062b14",
            fontWeight: 600,
            fontSize: 14,
            textDecoration: "none"
          }}>
          Abrir WhatsApp manualmente →
        </a>
      </div>
      <button
        type="button"
        onClick={onReset}
        style={{
          background: "transparent",
          border: 0,
          padding: 0,
          color: "var(--ink-faint)",
          fontFamily: "var(--mono)",
          fontSize: 10.5,
          letterSpacing: "0.08em",
          textTransform: "uppercase",
          cursor: "pointer",
          alignSelf: "flex-start"
        }}>
        
        ← voltar
      </button>
    </div>);

}

// ───────── App ─────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  const [name, setName] = useState("");
  const [phone, setPhone] = useState("");
  const [touched, setTouched] = useState({ name: false, phone: false });
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);

  // Apply tweaks → CSS vars
  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", t.accent);
    // derive a soft-glow variant via color-mix at runtime
    root.style.setProperty("--accent-soft", `color-mix(in oklab, ${t.accent} 18%, transparent)`);
    root.style.setProperty("--aurora", String((t.aurora ?? 55) / 100));
  }, [t.accent, t.aurora]);

  const validName = name.trim().length >= 2;
  const validPhone = isValidPhone(phone);
  const canSubmit = validName && validPhone && !loading;

  const SHEET_URL = "https://script.google.com/macros/s/AKfycbxRugpsNgKK9NHfyl_RD-Zth64U3BNQyjXyPjhzP5PlekXyiCCVnzlnw0LT0P4mIl0j/exec";

  const submit = async (e) => {
    e?.preventDefault?.();
    setTouched({ name: true, phone: true });
    if (!canSubmit) return;
    setLoading(true);
    try {
      await fetch(SHEET_URL, {
        method: "POST",
        mode: "no-cors",
        headers: { "Content-Type": "text/plain" },
        body: JSON.stringify({ name, phone, ts: new Date().toLocaleString("pt-BR", { timeZone: "America/Sao_Paulo" }) }),
      });
    } catch {}
    setLoading(false);
    setDone(true);
    // Dispara evento de Lead pro Meta Pixel
    try { window.fbq?.("track", "Lead"); } catch {}
    try {
      const leads = JSON.parse(localStorage.getItem("oz_leads") || "[]");
      leads.push({ name, phone, ts: Date.now() });
      localStorage.setItem("oz_leads", JSON.stringify(leads));
    } catch {}
  };

  const reset = () => {
    setDone(false);
    setName("");
    setPhone("");
    setTouched({ name: false, phone: false });
  };

  const members = t.members ?? 1284;

  return (
    <>
      <div className="stage">
        <div className="aurora" />
        <div className="grid" />
        <div className="vignette" />
        <div className={"grain " + (t.grain ? "" : "off")} />

        <div className="content shell" style={{ gap: "0px" }}>
          <header className="topbar">
            <div className="brand">
              {t.showLogo && <div className="brand-mark" />}
            </div>
            <div className="status-pill">
              <span className="status-dot" />
              Grupo aberto
            </div>
          </header>

          <main className="hero">
            <div className="eyebrow">
              <span className="eyebrow-badge">
                <img src="/networking/china.png" alt="China" />
              </span>
              <span>Networking · Vagas limitadas</span>
            </div>

            <h1 className="headline">
              {HEADLINES[t.headline] || HEADLINES.primary}
            </h1>

            <p className="sub">
              Entre no grupo de networking de quem está faturando com <b>CPA chinesa</b>.
              Calls semanais e a estrutura que te tira do <b>zero</b> aos primeiros{" "}
              <span className="pill-num">R$ 5.000/mês</span>.
            </p>

            {!done ?
            <form className="form" onSubmit={submit} noValidate>
                <div className="field">
                  <input
                  type="text"
                  autoComplete="given-name"
                  placeholder="Seu primeiro nome"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  onBlur={() => setTouched((p) => ({ ...p, name: true }))}
                  aria-invalid={touched.name && !validName} />
                  <span className="ico"><IcoUser /></span>
                  {touched.name && !validName && (
                    <div className="field-error">Nome muito curto</div>
                  )}
                </div>

                <div className="field">
                  <input
                  type="tel"
                  inputMode="tel"
                  autoComplete="tel"
                  placeholder="WhatsApp · (11) 99999-9999"
                  value={phone}
                  onChange={(e) => setPhone(maskPhone(e.target.value))}
                  onBlur={() => setTouched((p) => ({ ...p, phone: true }))}
                  aria-invalid={touched.phone && !validPhone} />
                  <span className="ico"><IcoPhone /></span>
                  {touched.phone && !validPhone && (
                    <div className="field-error">Número inválido</div>
                  )}
                </div>

                <div className="cta-wrap">
                  <LiquidButton
                  label={t.ctaLabel || "Quero entrar no grupo"}
                  loading={loading}
                  disabled={!canSubmit}
                  onClick={submit} />
                
                </div>

                <div className="micro">
                  <span className="lock"><IcoLock /></span>
                  100% gratuito
                  <span className="dot-sep" />
                  <span className="num-inline">{members.toLocaleString("pt-BR")} membros ativos</span>
                </div>
              </form> :

            <SuccessCard name={name} onReset={reset} />
            }
          </main>

          <footer className="foot">
            <div className="foot-bottom">
              <a
                href="https://www.instagram.com/07corporation/"
                target="_blank"
                rel="noopener noreferrer"
                className="foot-ig"
              >
                @07corporation
              </a>
              <div className="links">
                <a href="#">termos</a>
                <span className="dot-sep" />
                <a href="#">privacidade</a>
              </div>
            </div>
          </footer>
        </div>
      </div>

      {/* ─── Tweaks ─── */}
      <TweaksPanel title="Tweaks · LP OZ">
        <TweakSection label="Marca & cor">
          <TweakColor
            label="Cor de acento"
            value={t.accent}
            onChange={(v) => setTweak("accent", v)}
            options={["#25D366", "#A3E635", "#F5D782", "#FFFFFF"]} />
          
          <TweakToggle
            label="Logo OZ no topo"
            value={t.showLogo}
            onChange={(v) => setTweak("showLogo", v)} />
          
        </TweakSection>

        <TweakSection label="Copy">
          <TweakRadio
            label="Headline"
            value={t.headline}
            onChange={(v) => setTweak("headline", v)}
            options={[
            { value: "primary", label: "Primeiro mês" },
            { value: "bold", label: "5k direto" },
            { value: "loud", label: "CLT → CPA" }]
            } />
          
          <TweakText
            label="Texto do botão"
            value={t.ctaLabel}
            onChange={(v) => setTweak("ctaLabel", v)} />
          
        </TweakSection>

        <TweakSection label="Atmosfera">
          <TweakSlider
            label="Intensidade da aurora"
            value={t.aurora}
            onChange={(v) => setTweak("aurora", v)}
            min={0} max={100} step={1}
            unit="%" />
          
          <TweakToggle
            label="Grão de filme"
            value={t.grain}
            onChange={(v) => setTweak("grain", v)} />
          
        </TweakSection>

        <TweakSection label="Prova social">
          <TweakSlider
            label="Membros no grupo"
            value={t.members}
            onChange={(v) => setTweak("members", v)}
            min={50} max={9999} step={1} />
          
        </TweakSection>
      </TweaksPanel>
    </>);

}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);