/* Global app state: router, theme, hero variant, motion, accent */
const TWEAKS_DEFAULT = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "heroVariant": "assembly",
  "motion": "full",
  "accent": "acid",
  "cursorLabels": true
}/*EDITMODE-END*/;

const ACCENTS = {
  acid:     "#F6C445",   /* taxi yellow */
  electric: "oklch(0.68 0.22 260)",
  blood:    "oklch(0.58 0.22 25)",
  chrome:   "oklch(0.90 0.01 240)",
  none:     "transparent"
};

const HERO_VARIANTS = [
  { id: "reel",      label: "Showreel" },
  { id: "editorial", label: "Editorial" },
  { id: "assembly",  label: "Grid assembly" },
  { id: "manifesto", label: "Manifesto" },
  { id: "nyc",       label: "NYC live" }
];

const ROUTES = ["home", "social", "talent", "contact"];

function normalizeRoute(raw) {
  const cleaned = String(raw || "").replace(/^#/, "").replace(/^\/+/, "");
  if (!cleaned) return "home";
  return ({
    home: "home",
    social: "social",
    capabilities: "social",
    agency: "social",
    talent: "talent",
    contact: "contact",
    join: "contact"
  })[cleaned] || "home";
}

function scrollToRoute(route, behavior = "smooth") {
  const next = normalizeRoute(route);
  if (next === "home") {
    window.scrollTo({ top: 0, behavior });
    return;
  }
  const el = document.getElementById(next);
  if (el) el.scrollIntoView({ behavior, block: "start" });
}

function useRoute() {
  const [path, setPath] = React.useState("home");

  const navigate = React.useCallback((next, behavior = "smooth") => {
    const section = normalizeRoute(next);
    setPath(section);
    requestAnimationFrame(() => scrollToRoute(section, behavior));
  }, []);

  React.useEffect(() => {
    if (window.location.hash) {
      window.history.replaceState({}, "", window.location.pathname + window.location.search);
    }
  }, []);

  React.useEffect(() => {
    const sections = ROUTES
      .map((id) => document.getElementById(id))
      .filter(Boolean);
    if (!sections.length) return;

    const observer = new IntersectionObserver((entries) => {
      const visible = entries
        .filter((entry) => entry.isIntersecting)
        .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
      if (!visible) return;
      const next = visible.target.id;
      if (!next || next === path) return;
      setPath(next);
    }, {
      rootMargin: "-30% 0px -45% 0px",
      threshold: [0.15, 0.4, 0.7]
    });

    sections.forEach((section) => observer.observe(section));
    return () => observer.disconnect();
  }, [path]);

  return [path, navigate];
}

function useTweaks() {
  const [tweaks, setTweaks] = React.useState(() => {
    try {
      const saved = localStorage.getItem("212-tweaks-v2");
      if (saved) return { ...TWEAKS_DEFAULT, ...JSON.parse(saved) };
    } catch(_){}
    return TWEAKS_DEFAULT;
  });

  const setTweak = React.useCallback((key, val) => {
    setTweaks(prev => {
      const next = { ...prev, [key]: val };
      try { localStorage.setItem("212-tweaks-v2", JSON.stringify(next)); } catch(_){}
      try {
        window.parent?.postMessage({ type: "__edit_mode_set_keys", edits: { [key]: val } }, "*");
      } catch(_){}
      return next;
    });
  }, []);

  // Apply theme + accent to :root
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme);
    document.documentElement.style.setProperty("--accent", ACCENTS[tweaks.accent] || ACCENTS.acid);
    document.documentElement.setAttribute("data-motion", tweaks.motion);
  }, [tweaks.theme, tweaks.accent, tweaks.motion]);

  return [tweaks, setTweak];
}

Object.assign(window, { TWEAKS_DEFAULT, ACCENTS, HERO_VARIANTS, ROUTES, normalizeRoute, useRoute, useTweaks });
