// Root app — routes between Page1, Quiz, Page2, ThankYou.
// Bilingual: detects language from URL path (/nl or /). Re-renders on switch.
// Dev tools (route switcher + tweaks panel) hidden unless ?dev=1 in URL.

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "showBanner": true,
  "showMascot": true,
  "accent": "mint",
  "accentCustom": "#3DDC97",
  "surface": "dark",
  "headlineVariant": "A",
  "page1Layout": "keep-rest"
}/*EDITMODE-END*/;

const ACCENT_PRESETS = {
  mint:   { accent: "#3DDC97", hover: "#45E8A3", press: "#33C589", ink: "#06281A", soft: "rgba(61,220,151,0.12)", ring: "rgba(61,220,151,0.35)" },
  purple: { accent: "#A78BFA", hover: "#B49CFB", press: "#8E6FE0", ink: "#1E1033", soft: "rgba(167,139,250,0.14)", ring: "rgba(167,139,250,0.35)" },
  cyan:   { accent: "#38BDF8", hover: "#5CC9FB", press: "#2FA6DB", ink: "#062638", soft: "rgba(56,189,248,0.14)", ring: "rgba(56,189,248,0.35)" },
  pink:   { accent: "#F472B6", hover: "#F487C0", press: "#DB5FA0", ink: "#330B24", soft: "rgba(244,114,182,0.14)", ring: "rgba(244,114,182,0.35)" }
};

function hexToRgb(hex) {
  const h = hex.replace("#","");
  const v = h.length === 3 ? h.split("").map(c => c+c).join("") : h;
  const n = parseInt(v, 16);
  return [(n>>16)&255, (n>>8)&255, n&255];
}
function mixHex(hex, white, amount) {
  const [r,g,b] = hexToRgb(hex);
  const t = amount;
  const mr = Math.round(r + (white?255:0 - r)*t);
  const mg = Math.round(g + (white?255:0 - g)*t);
  const mb = Math.round(b + (white?255:0 - b)*t);
  const to = (x) => x.toString(16).padStart(2,"0");
  return `#${to(Math.max(0,Math.min(255,mr)))}${to(Math.max(0,Math.min(255,mg)))}${to(Math.max(0,Math.min(255,mb)))}`;
}
function resolveAccent(key, custom) {
  if (key === "custom") {
    const c = custom || "#3DDC97";
    const [r,g,b] = hexToRgb(c);
    const lum = (0.299*r + 0.587*g + 0.114*b) / 255;
    const ink = lum > 0.6 ? "#0a0a0a" : "#ffffff";
    return {
      accent: c,
      hover: mixHex(c, true, 0.12),
      press: mixHex(c, false, 0.15),
      ink,
      soft: `rgba(${r},${g},${b},0.14)`,
      ring: `rgba(${r},${g},${b},0.35)`
    };
  }
  return ACCENT_PRESETS[key] || ACCENT_PRESETS.mint;
}

function applyAccentToRoot(pal) {
  const r = document.documentElement;
  r.style.setProperty("--accent", pal.accent);
  r.style.setProperty("--accent-hover", pal.hover);
  r.style.setProperty("--accent-press", pal.press);
  r.style.setProperty("--accent-ink", pal.ink);
  r.style.setProperty("--accent-soft", pal.soft);
  r.style.setProperty("--accent-ring", pal.ring);
  r.style.setProperty("--cta-glow", `0 8px 28px ${pal.soft}`);
  r.style.setProperty("--hero-glow", `radial-gradient(600px 420px at 18% 14%, ${pal.soft} 0%, ${pal.soft} 30%, rgba(10,10,10,0) 70%)`);
}

function applySurfaceToRoot(surface) {
  const r = document.documentElement;
  if (surface === "lifted") {
    r.style.setProperty("--bg", "#111111");
    r.style.setProperty("--bg-elev", "#141414");
    r.style.setProperty("--surface", "#1A1A1A");
    r.style.setProperty("--surface-2", "#222222");
    r.style.setProperty("--border", "#2A2A2A");
  } else {
    r.style.setProperty("--bg", "#0A0A0A");
    r.style.setProperty("--bg-elev", "#0D0D0D");
    r.style.setProperty("--surface", "#161616");
    r.style.setProperty("--surface-2", "#1C1C1C");
    r.style.setProperty("--border", "#222222");
  }
}

// Meta Pixel helper — safely calls fbq if available, otherwise no-op.
function trackPixel(event, params) {
  try {
    if (typeof window.fbq === "function") {
      if (params) window.fbq("track", event, params);
      else window.fbq("track", event);
    }
  } catch (_) {}
}
window.trackPixel = trackPixel;

function App() {
  const [tweaks, setTweak] = window.useTweaks(DEFAULTS);
  const setTweaks = (obj) => {
    Object.entries(obj).forEach(([k, v]) => setTweak(k, v));
  };
  const [lang] = React.useState(() => window.detectLang());
  const [route, setRoute] = React.useState(() => {
    return (window.location.hash || "").replace("#","") || "optin";
  });

  // Sync <html lang> and document.title with current language.
  React.useEffect(() => {
    document.documentElement.setAttribute("lang", lang);
    const titles = {
      en: "Cashy — AI setter for coaches",
      nl: "Cashy — AI-setter voor coaches"
    };
    document.title = titles[lang] || titles.en;
  }, [lang]);

  React.useEffect(() => {
    window.__vslNavigate = (to) => {
      const allowed = ["optin","quiz","watch","thanks"];
      const next = allowed.includes(to) ? to : "optin";
      window.location.hash = next;
      setRoute(next);
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    const onHash = () => {
      const r = (window.location.hash || "").replace("#","") || "optin";
      setRoute(r);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Fire ViewContent on every route change, tagged with content_name + language.
  React.useEffect(() => {
    const names = {
      optin:  "VSL Landing",
      quiz:   "VSL Quiz",
      watch:  "VSL Watch",
      thanks: "VSL Thank You (Disqualified)"
    };
    trackPixel("ViewContent", {
      content_name: names[route] || "VSL Page",
      content_category: "VSL Funnel",
      content_language: lang
    });
  }, [route, lang]);

  React.useEffect(() => {
    applyAccentToRoot(resolveAccent(tweaks.accent, tweaks.accentCustom));
  }, [tweaks.accent, tweaks.accentCustom]);

  React.useEffect(() => {
    applySurfaceToRoot(tweaks.surface);
  }, [tweaks.surface]);

  const copy = window.COPY[lang] || window.COPY.en;
  const banner = copy.banner;

  // Dev tools are hidden in production. Append ?dev=1 to URL to show them.
  const isDev = (() => {
    try { return new URLSearchParams(window.location.search).has("dev"); }
    catch (_) { return false; }
  })();

  const switchLang = (target) => {
    if (target === lang) return;
    window.location.href = window.buildLangUrl(target);
  };

  return (
    <React.Fragment>
      {tweaks.showBanner && (
        <div className="urgency-banner">
          <span className="urgency-text">
            <svg viewBox="0 0 24 24" style={{width:14,height:14,stroke:"currentColor",strokeWidth:2,fill:"none",strokeLinecap:"round",strokeLinejoin:"round"}}><path d="M12 9v4M12 17h.01"/><path d="M10.3 3.86L1.82 18a2 2 0 001.72 3h16.92a2 2 0 001.72-3L13.71 3.86a2 2 0 00-3.42 0z"/></svg>
            <span>{banner.tag}</span>
            <span className="banner-sep" aria-hidden="true">·</span>
            <span>{banner.mid}</span>
            <span className="banner-sep" aria-hidden="true">·</span>
            <span className="spot">{banner.spot}</span>
            <span>{banner.rest}</span>
          </span>
        </div>
      )}

      {/* Language switcher — top-right pill */}
      <div className="lang-switcher" role="group" aria-label="Language">
        <button
          type="button"
          className={`lang-pill ${lang === "en" ? "is-active" : ""}`}
          onClick={() => switchLang("en")}
          aria-pressed={lang === "en"}
        >EN</button>
        <button
          type="button"
          className={`lang-pill ${lang === "nl" ? "is-active" : ""}`}
          onClick={() => switchLang("nl")}
          aria-pressed={lang === "nl"}
        >NL</button>
      </div>

      {route === "watch" && <window.Page2 tweaks={tweaks} lang={lang} />}
      {route === "thanks" && <window.ThankYou lang={lang} />}
      {route === "quiz" && (
        <window.Quiz
          lang={lang}
          onComplete={() => window.__vslNavigate("watch")}
          onDQ={() => window.__vslNavigate("thanks")}
        />
      )}
      {(route !== "watch" && route !== "thanks" && route !== "quiz") && <window.Page1 tweaks={tweaks} lang={lang} />}

      <window.CookieBanner />

      {/* Dev-only: route switcher + tweaks panel. Append ?dev=1 to URL to show. */}
      {isDev && (
        <React.Fragment>
          <div style={{
            position: "fixed", bottom: 16, left: 16, zIndex: 40,
            display: "flex", gap: 6,
            background: "rgba(22,22,22,0.92)",
            border: "1px solid #2A2A2A",
            borderRadius: 999, padding: 4,
            backdropFilter: "blur(6px)"
          }}>
            {[["optin", copy.routeSwitcher[0]], ["quiz", copy.routeSwitcher[1]], ["watch", copy.routeSwitcher[2]], ["thanks", copy.routeSwitcher[3]]].map(([r,l]) => (
              <button key={r}
                onClick={() => { window.location.hash = r; setRoute(r); window.scrollTo({top:0}); }}
                style={{
                  background: route === r ? "var(--accent)" : "transparent",
                  color: route === r ? "var(--accent-ink)" : "#9B9B9B",
                  border: "none",
                  padding: "7px 14px",
                  borderRadius: 999,
                  fontFamily: "var(--font-body)",
                  fontSize: 12,
                  fontWeight: 600,
                  cursor: "pointer"
                }}>
                {l}
              </button>
            ))}
          </div>

          <window.TweaksPanel>
            <window.TweakSection label="Accent" />
            <window.TweakRadio
              label="Color"
              value={tweaks.accent}
              onChange={(v) => setTweak("accent", v)}
              options={["mint", "purple", "cyan", "pink", "custom"]}
            />
            {tweaks.accent === "custom" && (
              <window.TweakColor
                label="Custom"
                value={tweaks.accentCustom}
                onChange={(v) => setTweak("accentCustom", v)}
              />
            )}

            <window.TweakSection label="Surface" />
            <window.TweakRadio
              label="Background"
              value={tweaks.surface}
              onChange={(v) => setTweak("surface", v)}
              options={["dark", "lifted"]}
            />

            <window.TweakSection label="Headline variant (Page 1)" />
            <window.TweakRadio
              label="Variant"
              value={tweaks.headlineVariant}
              onChange={(v) => setTweak("headlineVariant", v)}
              options={["A", "B", "C"]}
            />

            <window.TweakSection label="Landing layout" />
            <window.TweakSelect
              label="Variant"
              value={tweaks.page1Layout}
              onChange={(v) => setTweak("page1Layout", v)}
              options={[
                { value: "keep-rest", label: "Keep rest (default)" },
                { value: "lite",      label: "Lite (no bullets)" },
                { value: "minimal",   label: "Minimal (headline + offer)" }
              ]}
            />

            <window.TweakSection label="Layout" />
            <window.TweakToggle
              label="Urgency banner"
              value={tweaks.showBanner}
              onChange={(v) => setTweak("showBanner", v)}
            />
            <window.TweakToggle
              label="Mascot"
              value={tweaks.showMascot}
              onChange={(v) => setTweak("showMascot", v)}
            />
          </window.TweaksPanel>
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

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