// app.jsx — Self-Study Map landing page
// Wires sections, reveal-on-scroll observer, sticky CTA, and Tweaks.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "headline": "C",
  "ctaCopy": "benefit",
  "heroLayout": "split",
  "palette": "cream",
  "dark": false,
  "showUrgencia": true
}/*EDITMODE-END*/;

// Reveal-on-scroll: stamp .in onto .reveal elements as they enter viewport.
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    if (!("IntersectionObserver" in window)) {
      els.forEach((e) => e.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    els.forEach((e) => io.observe(e));
    return () => io.disconnect();
  });
}

// Tiny confetti-ish reaction on CTA click
function fireCtaPulse(e) {
  const btn = e.currentTarget;
  btn.animate(
    [
      { transform: "translateY(0) scale(1)" },
      { transform: "translateY(-3px) scale(1.02)" },
      { transform: "translateY(0) scale(1)" },
    ],
    { duration: 350, easing: "cubic-bezier(.2,.7,.2,1)" }
  );
}

// Smooth-scroll to the offer section
function scrollToOffer() {
  const el = document.querySelector('[data-screen-label="08 Oferta"]');
  if (el) {
    const top = el.getBoundingClientRect().top + window.scrollY - 12;
    window.scrollTo({ top, behavior: "smooth" });
  }
}

function StickyCta({ ctaCopy, onCta }) {
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => {
      const hero = document.querySelector('[data-screen-label="01 Hero"]');
      const final = document.querySelector('[data-screen-label="13 CTA Final"]');
      if (!hero) return;
      const heroBottom = hero.getBoundingClientRect().bottom;
      const finalTop = final ? final.getBoundingClientRect().top : Infinity;
      setShow(heroBottom < 60 && finalTop > window.innerHeight - 40);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const cta = CTA_COPY[ctaCopy] || CTA_COPY.benefit;

  return (
    <div className={`sticky-cta ${show ? "show" : ""}`}>
      <div className="sticky-inner">
        <div className="sticky-info">
          <div className="sticky-price">R$97 <span className="sticky-old">R$151</span></div>
          <div className="sticky-meta">acesso imediato · garantia 7 dias</div>
        </div>
        <button className="sticky-btn" onClick={onCta}>
          {cta.label === "Começar a estudar com direção" ? "Quero meu acesso" : "Quero agora"}
          <span>→</span>
        </button>
      </div>
      <style>{`
        .sticky-cta {
          position: fixed; left: 0; right: 0; bottom: 0;
          padding: 12px 16px max(12px, env(safe-area-inset-bottom));
          background: color-mix(in oklch, var(--bg) 88%, transparent);
          backdrop-filter: blur(16px) saturate(160%);
          -webkit-backdrop-filter: blur(16px) saturate(160%);
          border-top: 1px solid var(--line);
          z-index: 100;
          transform: translateY(100%);
          transition: transform 0.3s cubic-bezier(.2,.7,.2,1);
        }
        .sticky-cta.show { transform: translateY(0); }
        .sticky-inner {
          max-width: 440px;
          margin: 0 auto;
          display: flex;
          align-items: center;
          gap: 12px;
        }
        .sticky-info { flex: 0 0 auto; min-width: 0; }
        .sticky-price { font-family: var(--f-serif); font-size: 22px; font-weight: 700; color: var(--ink); letter-spacing: -0.02em; line-height: 1; }
        .sticky-old { font-size: 12px; color: var(--ink-3); text-decoration: line-through; font-weight: 500; margin-left: 4px; font-family: var(--f-sans); }
        .sticky-meta { font-size: 10px; color: var(--ink-3); margin-top: 3px; }
        .sticky-btn {
          flex: 1;
          padding: 14px 18px;
          border-radius: 999px;
          background: var(--primary);
          color: white;
          font-family: var(--f-sans);
          font-weight: 700;
          font-size: 14px;
          border: 0;
          cursor: pointer;
          box-shadow: 0 4px 0 var(--primary-deep);
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          letter-spacing: -0.005em;
          transition: transform 0.12s ease;
        }
        .sticky-btn:hover { transform: translateY(-1px); }
        .sticky-btn:active { transform: translateY(2px); box-shadow: 0 1px 0 var(--primary-deep); }
      `}</style>
    </div>
  );
}

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

  // Apply palette + dark mode to root
  React.useEffect(() => {
    document.documentElement.setAttribute("data-palette", t.palette);
    document.documentElement.setAttribute("data-dark", t.dark ? "1" : "0");
  }, [t.palette, t.dark]);

  const CHECKOUT_URL = "https://pay.hotmart.com/X105846356G?bid=1779664355693";

  const handleCta = (e) => {
    if (e) fireCtaPulse(e);
    window.open(CHECKOUT_URL, "_blank", "noopener,noreferrer");
  };

  return (
    <>
      <div className="lp-frame">
        <Hero
          headline={t.headline}
          ctaCopy={t.ctaCopy}
          layout={t.heroLayout}
          onCta={handleCta}
        />
        <OpeningBlock />
        <DorSection />
        <SolucaoSection />
        <BeneficiosSection />
        <RoadmapSection />
        <ProvaSocialSection />
        <OfertaSection ctaCopy={t.ctaCopy} onCta={handleCta} />
        <ObjectionsSection />
        <GarantiaSection />
        {t.showUrgencia && <UrgenciaSection />}
        <FaqSection />
        <FinalCtaSection ctaCopy={t.ctaCopy} onCta={handleCta} />
        <LpFooter />
      </div>

      <StickyCta ctaCopy={t.ctaCopy} onCta={handleCta} />

      <TweaksPanel title="Tweaks · Self-Study Map">
        <TweakSection label="Hero" />
        <TweakRadio
          label="Headline"
          value={t.headline}
          options={[
            { value: "A", label: "A" },
            { value: "B", label: "B" },
            { value: "C", label: "C" },
          ]}
          onChange={(v) => setTweak("headline", v)}
        />
        <TweakSelect
          label="Hero layout"
          value={t.heroLayout}
          options={[
            { value: "split", label: "Split (cards lado a lado)" },
            { value: "centered", label: "Centered (planner radial)" },
            { value: "image-led", label: "Image-led (planner mockup)" },
          ]}
          onChange={(v) => setTweak("heroLayout", v)}
        />
        <TweakRadio
          label="CTA"
          value={t.ctaCopy}
          options={[
            { value: "benefit", label: "Benefício" },
            { value: "direct", label: "Direto" },
          ]}
          onChange={(v) => setTweak("ctaCopy", v)}
        />

        <TweakSection label="Tema" />
        <TweakColor
          label="Paleta"
          value={t.palette}
          options={[
            { value: "cream", label: "Cream" },
            { value: "sunset", label: "Sunset" },
            { value: "indigo", label: "Indigo" },
            { value: "olive", label: "Olive" },
          ].map((p) => p.value)}
          onChange={() => {}}
        />
        <PaletteChips value={t.palette} onChange={(v) => setTweak("palette", v)} />
        <TweakToggle
          label="Modo escuro"
          value={t.dark}
          onChange={(v) => setTweak("dark", v)}
        />

        <TweakSection label="Seções" />
        <TweakToggle
          label="Mostrar urgência"
          value={t.showUrgencia}
          onChange={(v) => setTweak("showUrgencia", v)}
        />
      </TweaksPanel>
    </>
  );
}

// Custom palette chips (since brand has named palettes, not free colors)
function PaletteChips({ value, onChange }) {
  const palettes = [
    { id: "cream", name: "Cream", colors: ["#E25C2A", "#F4C84A", "#2E6BA8"] },
    { id: "sunset", name: "Sunset", colors: ["#EAB72A", "#E25C2A", "#2E6BA8"] },
    { id: "indigo", name: "Indigo", colors: ["#2E6BA8", "#F4C84A", "#E25C2A"] },
    { id: "olive", name: "Olive", colors: ["#4D6B3B", "#F4C84A", "#C8412E"] },
  ];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
      {palettes.map((p) => (
        <button
          key={p.id}
          onClick={() => onChange(p.id)}
          style={{
            display: "flex",
            alignItems: "center",
            gap: 8,
            padding: "8px 10px",
            background: value === p.id ? "rgba(0,0,0,0.06)" : "transparent",
            border: value === p.id ? "1px solid rgba(0,0,0,0.4)" : "1px solid rgba(0,0,0,0.1)",
            borderRadius: 8,
            cursor: "pointer",
            fontFamily: "inherit",
            fontSize: 11.5,
            fontWeight: 500,
            color: "inherit",
          }}
        >
          <span style={{ display: "flex", gap: 0 }}>
            {p.colors.map((c, i) => (
              <span key={i} style={{
                display: "inline-block",
                width: 10,
                height: 14,
                background: c,
                borderRadius: i === 0 ? "3px 0 0 3px" : i === p.colors.length - 1 ? "0 3px 3px 0" : 0,
              }} />
            ))}
          </span>
          {p.name}
        </button>
      ))}
    </div>
  );
}

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