/* PL-AI — landing: primitivos + nav + footer + modal + fab */

function Button({ variant = "primary", size, block, href, children, onClick, icon }) {
  const cls = ["btn", "btn--" + variant, size === "lg" && "btn--lg", block && "btn--block"].filter(Boolean).join(" ");
  const inner = [children, icon && React.createElement(Icon, { name: icon, key: "i" })];
  if (href) return React.createElement("a", { className: cls, href, onClick }, inner);
  return React.createElement("button", { className: cls, onClick }, inner);
}

function Eyebrow({ children, invert }) {
  return <p className={"eyebrow" + (invert ? " eyebrow--invert" : "")}>{children}</p>;
}

function SectionHead({ eyebrow, title, sub }) {
  return (
    <div className="section__head reveal">
      {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
      <h2 className="section__title">{title}</h2>
      {sub && <p className="section__sub">{sub}</p>}
    </div>
  );
}

function Brand({ onDark }) {
  return (
    <a className="brand" href="#top">
      <img className="brand__mark" src="assets/logo-mark.svg" alt="" />
      <span className="brand__name"><b>PL-AI</b></span>
    </a>
  );
}

const NAV_LINKS = [
  ["Funcionalidades", "#features"],
  ["Como funciona", "#how"],
  ["Para quem é", "#usecases"],
  ["Planos", "#pricing"],
  ["Dúvidas", "#faq"],
];

function Nav({ onSignup }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const fn = () => setScrolled(window.scrollY > 12);
    fn();
    window.addEventListener("scroll", fn, { passive: true });
    return () => window.removeEventListener("scroll", fn);
  }, []);
  return (
    <nav className={"nav" + (scrolled ? " nav--scrolled" : "")}>
      <div className="container nav__inner">
        <Brand />
        <div className="nav__links">
          {NAV_LINKS.map(([t, h]) => <a className="nav__link" key={h} href={h}>{t}</a>)}
        </div>
        <div className="nav__spacer" />
        <div className="nav__actions">
          <Button variant="ghost" onClick={onSignup}>Entrar</Button>
          <Button variant="primary" onClick={onSignup}>Criar conta</Button>
        </div>
        <button className="nav__burger" aria-label="Menu" onClick={() => setOpen(o => !o)}>
          <Icon name={open ? "x" : "menu"} />
        </button>
      </div>
      <div className={"nav__mobile" + (open ? " is-open" : "")}>
        {NAV_LINKS.map(([t, h]) => <a key={h} href={h} onClick={() => setOpen(false)}>{t}</a>)}
        <a href="#" onClick={(e) => { e.preventDefault(); setOpen(false); onSignup(); }}>Assinar R$ 5/mês →</a>
      </div>
    </nav>
  );
}

const FOOTER_COLS = [
  ["Produto", ["Planos", "Funcionalidades", "API", "Roadmap", "Changelog"]],
  ["Empresa", ["Sobre", "Blog", "Vagas", "Contato"]],
  ["Recursos", ["Documentação", "Tutoriais", "Comunidade", "Suporte"]],
  ["Legal", ["Termos de uso", "Privacidade", "LGPD", "Cookies"]],
];

function Footer() {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer__grid">
          <div className="footer__brand">
            <div className="brand" style={{ pointerEvents: "none" }}>
              <img className="brand__mark" src="assets/logo-mark.svg" alt="" />
              <span className="brand__name" style={{ color: "#fff" }}><b style={{ color: "var(--purple-400)" }}>PL-AI</b></span>
            </div>
            <p className="footer__tag">Co-piloto de WhatsApp pra times que querem render mais. Feito no Brasil.</p>
          </div>
          {FOOTER_COLS.map(([h, items]) => (
            <div className="footer__col" key={h}>
              <h4>{h}</h4>
              {items.map(i => <a key={i} href="#">{i}</a>)}
            </div>
          ))}
        </div>
        <div className="footer__bottom">
          <span className="footer__copy">© 2026 PL-AI. Feito no Brasil, pra quem atende muito no WhatsApp.</span>
          <div className="footer__social">
            {["instagram", "linkedin", "youtube", "twitter"].map(n => (
              <a key={n} href="#" aria-label={n}><Icon name={n} /></a>
            ))}
          </div>
        </div>
      </div>
    </footer>
  );
}

function WhatsAppFab({ onClick }) {
  return (
    <button className="wfab" onClick={onClick}>
      <Icon name="whatsapp" /> Testar a PL-AI
    </button>
  );
}

function SignupModal({ onClose, plan }) {
  // steps: 1=email+plan+metodo, 2=pagamento, 3=perfil (nome/negócio/tel/senha), 4=indo pro painel
  const [step, setStep] = React.useState(1);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [selectedPlan, setSelectedPlan] = React.useState(plan || "starter");
  const [payMethod, setPayMethod] = React.useState("paypal"); // Stripe temporariamente escondido — só PayPal ativo
  const [signupData, setSignupData] = React.useState(null);
  const [profile, setProfile] = React.useState({ name: "", business_name: "", phone: "", password: "", vertical: "custom" });
  const stripeRef = React.useRef(null);
  const elementsRef = React.useRef(null);
  const paymentElementMounted = React.useRef(false);
  const paypalButtonMounted = React.useRef(false);

  React.useEffect(() => {
    const fn = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", fn);
    return () => window.removeEventListener("keydown", fn);
  }, []);

  const PLAN_INFO = {
    starter:  { label: "Starter",  price: "R$ 5",   amountCents: 500,   desc: "Assinatura base. Ideal pra começar." },
    plus:     { label: "Plus",     price: "R$ 47",  amountCents: 4700,  desc: "Mais conversas e recursos pra crescer." },
    pro:      { label: "Pro",      price: "R$ 149", amountCents: 14900, desc: "Mais volume e recursos." },
    business: { label: "Business", price: "R$ 500", amountCents: 50000, desc: "Ilimitado + white-label." },
  };
  const cur = PLAN_INFO[selectedPlan] || PLAN_INFO.starter;

  // STEP 1 → 2: só email + plano + método
  async function submitStep1(e) {
    e.preventDefault();
    setErr("");
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) { setErr("email inválido"); return; }
    setLoading(true);
    try {
      const endpoint = payMethod === "paypal" ? "/api/signup/paypal-create" : "/api/signup/subscribe";
      const r = await fetch(endpoint, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ email, plan: selectedPlan }),
      });
      const d = await r.json();
      if (!r.ok || (!d.client_secret && !d.signup_id)) throw new Error(d.error || "falha ao preparar pagamento");
      setSignupData(d);
      setStep(2);
    } catch (e) {
      setErr(e.message || "erro");
    } finally {
      setLoading(false);
    }
  }

  // Step 2: monta Stripe Elements (só se card)
  React.useEffect(() => {
    if (step !== 2 || !signupData || payMethod !== "card" || paymentElementMounted.current) return;
    (async () => {
      if (!window.Stripe) {
        await new Promise((res, rej) => {
          const s = document.createElement("script");
          s.src = "https://js.stripe.com/v3/";
          s.onload = res;
          s.onerror = () => rej(new Error("falha carregando Stripe.js"));
          document.head.appendChild(s);
        });
      }
      try {
        const stripe = window.Stripe(signupData.publishable_key);
        const elements = stripe.elements({
          clientSecret: signupData.client_secret,
          appearance: {
            theme: "night",
            variables: { colorPrimary: "#10b981", colorBackground: "#0f0f14", colorText: "#e8e8ee", colorDanger: "#e5484d", fontFamily: "Geist, system-ui, sans-serif", borderRadius: "10px" },
          },
        });
        const pe = elements.create("payment", { layout: "tabs" });
        pe.mount("#stripe-payment-element");
        stripeRef.current = stripe;
        elementsRef.current = elements;
        paymentElementMounted.current = true;
      } catch (e) {
        setErr("erro carregando formulário de cartão: " + e.message);
      }
    })();
  }, [step, signupData, payMethod]);

  // Step 2: monta PayPal Button (só o botão Cartão de Débito/Crédito)
  React.useEffect(() => {
    if (step !== 2 || !signupData || payMethod !== "paypal" || paypalButtonMounted.current) return;
    (async () => {
      const sdkSrc = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(signupData.client_id)}&currency=BRL&intent=capture&components=buttons`;
      if (!window.paypal || (window.__pp_client_id && window.__pp_client_id !== signupData.client_id) || !window.paypal.Buttons) {
        const existing = document.querySelectorAll("script[data-paypal-sdk]");
        existing.forEach(s => s.remove());
        window.paypal = undefined;
        await new Promise((res, rej) => {
          const s = document.createElement("script");
          s.src = sdkSrc;
          s.setAttribute("data-paypal-sdk", "1");
          s.onload = res;
          s.onerror = () => rej(new Error("falha carregando PayPal SDK"));
          document.head.appendChild(s);
        });
        window.__pp_client_id = signupData.client_id;
      }
      try {
        const container = document.getElementById("paypal-button-container");
        if (container) container.innerHTML = "";
        window.paypal.Buttons({
          fundingSource: window.paypal.FUNDING.CARD,
          style: { shape: "rect", color: "black", layout: "vertical", label: "pay" },
          createOrder: async () => {
            const r = await fetch("/api/signup/paypal-order", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ signup_id: signupData.signup_id }),
            });
            const j = await r.json();
            if (!r.ok || !j.order_id) throw new Error(j.error || "falha criando pedido");
            return j.order_id;
          },
          onApprove: async (data) => {
            setLoading(true);
            const fin = await fetch("/api/signup/paypal-finalize", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ signup_id: signupData.signup_id, order_id: data.orderID }),
            });
            const j = await fin.json();
            setLoading(false);
            if (!fin.ok || !j.panel_url) { setErr(j.error || "falha finalizando"); return; }
            setSignupData(prev => ({ ...prev, panel_url: j.panel_url, tenant_slug: j.slug }));
            setStep(3);
          },
          onError: (err) => { setErr("erro PayPal: " + (err?.message || String(err).slice(0,100))); },
          onCancel: () => { setErr("pagamento cancelado"); },
        }).render("#paypal-button-container");
        paypalButtonMounted.current = true;
      } catch (e) {
        setErr("erro montando PayPal: " + e.message);
      }
    })();
  }, [step, signupData, payMethod]);

  // Step 2 → 3 (Stripe): confirma SetupIntent + finalize
  async function submitStep2Stripe(e) {
    e.preventDefault();
    setErr("");
    if (!stripeRef.current || !elementsRef.current) { setErr("cartão ainda carregando..."); return; }
    setLoading(true);
    try {
      const { error: setupErr, setupIntent } = await stripeRef.current.confirmSetup({
        elements: elementsRef.current,
        redirect: "if_required",
      });
      if (setupErr) throw new Error(setupErr.message || "cartão recusado");
      if (!setupIntent || setupIntent.status !== "succeeded") throw new Error("cartão não pôde ser validado");
      const pmId = setupIntent.payment_method;
      if (!pmId) throw new Error("payment_method não retornado");
      const finRes = await fetch("/api/signup/finalize", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ signup_id: signupData.signup_id, payment_method_id: pmId }),
      });
      const finD = await finRes.json();
      if (!finRes.ok || !finD.panel_url) throw new Error(finD.error || "falha finalizando");
      setSignupData(prev => ({ ...prev, panel_url: finD.panel_url, tenant_slug: finD.slug }));
      setStep(3);
    } catch (e) {
      setErr(e.message || "erro");
    } finally {
      setLoading(false);
    }
  }

  // Step 3 → 4: envia perfil, redireciona
  async function submitStep3(e) {
    e.preventDefault();
    setErr("");
    if (profile.password.length < 6) { setErr("senha precisa ter no mínimo 6 caracteres"); return; }
    setLoading(true);
    try {
      const r = await fetch("/api/signup/complete-profile", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ signup_id: signupData.signup_id, ...profile }),
      });
      const d = await r.json();
      if (!r.ok || !d.panel_url) throw new Error(d.error || "falha completando perfil");
      setStep(4);
      setTimeout(() => { window.location.href = d.panel_url; }, 500);
    } catch (e) {
      setErr(e.message || "erro");
    } finally {
      setLoading(false);
    }
  }

  const updProfile = (k) => (e) => setProfile(prev => ({ ...prev, [k]: e.target.value }));

  const chipStyle = (k, selected) => ({
    flex: 1, padding: "12px 8px", border: "1px solid var(--border)", borderRadius: 10,
    background: selected ? "rgba(16,185,129,.10)" : "transparent",
    color: "var(--fg1)", cursor: "pointer", fontWeight: 600,
    borderColor: selected ? "var(--primary)" : "var(--border)",
    display: "flex", flexDirection: "column", gap: 2, alignItems: "center", fontSize: 13,
  });

  return (
    <div className="modal" onClick={onClose}>
      <div className="modal__panel" onClick={e => e.stopPropagation()}>
        <button className="modal__close" onClick={onClose} aria-label="Fechar"><Icon name="x" size={20} /></button>

        {step === 1 && (
          <>
            <h3 className="modal__title">Testar PL-AI</h3>
            <p className="modal__sub">Só o email pra começar. Escolhe o plano, paga, e depois completa o resto. Cobrança mensal, cancela quando quiser.</p>
            <div style={{ display: "flex", gap: 8, marginBottom: 14, flexWrap: "wrap" }}>
              <button type="button" onClick={() => setSelectedPlan("starter")} style={chipStyle("starter", selectedPlan === "starter")}>
                <span>Starter</span><span style={{fontSize:12,color:"var(--fg3)"}}>R$ 5/mês</span>
              </button>
              <button type="button" onClick={() => setSelectedPlan("plus")} style={chipStyle("plus", selectedPlan === "plus")}>
                <span>Plus</span><span style={{fontSize:12,color:"var(--fg3)"}}>R$ 47/mês</span>
              </button>
              <button type="button" onClick={() => setSelectedPlan("pro")} style={chipStyle("pro", selectedPlan === "pro")}>
                <span>Pro</span><span style={{fontSize:12,color:"var(--fg3)"}}>R$ 149/mês</span>
              </button>
              <button type="button" onClick={() => setSelectedPlan("business")} style={chipStyle("business", selectedPlan === "business")}>
                <span>Business</span><span style={{fontSize:12,color:"var(--fg3)"}}>R$ 500/mês</span>
              </button>
            </div>
            <p style={{ fontSize: 12, color: "var(--fg3)", margin: "0 0 10px", padding: "8px 12px", background: "rgba(16,185,129,.06)", borderRadius: 8, border: "1px solid rgba(16,185,129,.15)" }}>
              <b>{cur.label} — {cur.price}/mês.</b> {cur.desc}
            </p>
            <form onSubmit={submitStep1}>
              <input className="field" type="email" placeholder="seu@email.com" required autoFocus value={email} onChange={e => setEmail(e.target.value)} />
              {/* Toggle Cartão/PayPal escondido temporariamente — só PayPal ativo */}
              {err && <p style={{ color: "#e5484d", fontSize: 13, margin: "10px 0 0" }}>⚠ {err}</p>}
              <Button variant="primary" block>{loading ? "Preparando..." : (payMethod === "paypal" ? "Continuar pro pagamento →" : "Continuar pro pagamento →")}</Button>
              <p style={{ fontSize: 11.5, color: "var(--fg3)", marginTop: 10, textAlign: "center" }}>Pagamento seguro. "Cartão de débito ou crédito. Cobrança mensal."</p>
            </form>
          </>
        )}

        {step === 2 && signupData && (
          <>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <button type="button" onClick={() => { setStep(1); paymentElementMounted.current = false; paypalButtonMounted.current = false; setSignupData(null); setErr(""); }} style={{ background: "transparent", border: 0, cursor: "pointer", color: "var(--fg3)", padding: 0, fontSize: 20, lineHeight: 1 }}>←</button>
              <h3 className="modal__title" style={{ margin: 0 }}>Pagamento</h3>
            </div>
            <p className="modal__sub"><b>{cur.label}</b> — <b>{cur.price}</b>. Pagamento único agora. Email: {email}</p>
            {payMethod === "card" ? (
              <form onSubmit={submitStep2Stripe}>
                <div id="stripe-payment-element" style={{ marginBottom: 14, minHeight: 220 }}></div>
                {err && <p style={{ color: "#e5484d", fontSize: 13, margin: "0 0 10px" }}>⚠ {err}</p>}
                <Button variant="primary" block>{loading ? "Processando..." : `Pagar ${cur.price} →`}</Button>
                <p style={{ fontSize: 11.5, color: "var(--fg3)", marginTop: 10, textAlign: "center" }}>🔒 Cartão criptografado pela Stripe. Não guardamos nada.</p>
              </form>
            ) : (
              <div style={{ paddingBottom: 12 }}>
                <div id="paypal-button-container" style={{ minHeight: 55, marginBottom: 10 }}></div>
                {err && <p style={{ color: "#e5484d", fontSize: 13, margin: "0 0 10px" }}>⚠ {err}</p>}
                {loading && <p style={{ fontSize: 13, color: "var(--fg3)", textAlign: "center" }}>Processando...</p>}
                <p style={{ fontSize: 11.5, color: "var(--fg3)", marginTop: 10, textAlign: "center" }}>🔒 Pagamento seguro. Cartão de débito ou crédito.</p>
              </div>
            )}
          </>
        )}

        {step === 3 && signupData && (
          <>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
              <div style={{ width: 28, height: 28, borderRadius: "50%", background: "rgba(52, 199, 89, 0.15)", color: "#34c759", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 700 }}>✓</div>
              <h3 className="modal__title" style={{ margin: 0 }}>Pagamento confirmado!</h3>
            </div>
            <p className="modal__sub">Agora só falta completar seus dados pra ter acesso ao painel.</p>
            <form onSubmit={submitStep3}>
              <input className="field" placeholder="Seu nome" required autoFocus value={profile.name} onChange={updProfile("name")} />
              <input className="field" placeholder="Nome do seu negócio" required value={profile.business_name} onChange={updProfile("business_name")} />
              <input className="field" placeholder="WhatsApp com DDD (opcional)" value={profile.phone} onChange={updProfile("phone")} />
              <input className="field" type="password" placeholder="Escolha uma senha (mín. 6)" required minLength={6} value={profile.password} onChange={updProfile("password")} />
              <select className="field" value={profile.vertical} onChange={updProfile("vertical")}>
                <option value="custom">Outro / negócio geral</option>
                <option value="dentista">Clínica odontológica</option>
                <option value="salao">Salão de beleza / estética</option>
                <option value="restaurante">Restaurante / delivery</option>
                <option value="loja">Loja / e-commerce</option>
              </select>
              {err && <p style={{ color: "#e5484d", fontSize: 13, margin: "10px 0 0" }}>⚠ {err}</p>}
              <Button variant="primary" block>{loading ? "Salvando..." : "Entrar no painel →"}</Button>
              <p style={{ fontSize: 11.5, color: "var(--fg3)", marginTop: 10, textAlign: "center" }}>Sua senha vale só pra você. Podemos mudar depois no painel.</p>
            </form>
          </>
        )}

        {step === 4 && (
          <div style={{ textAlign: "center", padding: "20px 0" }}>
            <div style={{ width: 56, height: 56, margin: "0 auto 16px", border: "3px solid rgba(16,185,129,.2)", borderTopColor: "var(--primary)", borderRadius: "50%", animation: "spin 0.8s linear infinite" }}></div>
            <h3 style={{ margin: "0 0 8px", fontSize: 18 }}>Entrando no painel...</h3>
            <p style={{ color: "var(--fg3)", fontSize: 13, margin: 0 }}>Só um instante.</p>
            <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Button, Eyebrow, SectionHead, Brand, Nav, Footer, WhatsAppFab, SignupModal });
