/* global React, ReactDOM, GroupHome, ConsultingHub, WebsitesPage, TechConsultingPage, CapitalPage, ContactPage, ReviewFlowPage, SinuxModPage, SwitchboardPage, PrivacyPage, TermsPage, applySEO */
const { useState, useEffect } = React;

const ROUTES = [
  "/",
  "/consulting",
  "/consulting/digital-growth/websites",
  "/consulting/tech-consulting",
  "/consulting/contact",
  "/capital",
  "/capital/contact",
  "/contact",
  "/reviewflow",
  "/sinuxmod",
  "/switchboard",
  "/privacy",
  "/terms",
];

function normalize(path) {
  let p = (path || "/").split("?")[0].split("#")[0];
  if (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
  return ROUTES.includes(p) ? p : "/";
}

// Tweaks defaults
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentIntensity": 1.0,
  "showMesh": true,
  "ribbonGlow": true
}/*EDITMODE-END*/;

// ============================================================
// Router
// ============================================================
function App() {
  // Initial route — handle both clean paths and legacy /#/path links
  const [route, setRoute] = useState(() => {
    const hash = window.location.hash;
    if (hash.startsWith("#/")) {
      const target = hash.replace(/^#/, "");
      window.history.replaceState({}, "", target);
      return normalize(target);
    }
    return normalize(window.location.pathname);
  });
  const [tweaks, setTweaks] = useState(TWEAK_DEFAULTS);
  const [tweakOpen, setTweakOpen] = useState(false);

  // Apply SEO meta tags + JSON-LD on every route change
  useEffect(() => {
    if (typeof applySEO === "function") applySEO(route);
  }, [route]);

  // Back/forward navigation
  useEffect(() => {
    const onPop = () => setRoute(normalize(window.location.pathname));
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  // Intercept internal <a> clicks → use pushState instead of full page load
  useEffect(() => {
    const handler = (e) => {
      if (e.defaultPrevented || e.button !== 0) return;
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      const a = e.target.closest("a[href]");
      if (!a) return;
      if (a.target === "_blank" || a.hasAttribute("download")) return;
      const href = a.getAttribute("href");
      if (!href) return;
      if (href.startsWith("mailto:") || href.startsWith("tel:") || href.startsWith("javascript:")) return;
      let url;
      try { url = new URL(href, window.location.href); } catch (_) { return; }
      if (url.origin !== window.location.origin) return;
      // In-page anchor (#how, #faq, etc.) — let browser handle
      if (url.pathname === window.location.pathname && url.hash && !url.hash.startsWith("#/")) return;

      e.preventDefault();
      // Legacy hash routes — strip the leading #
      let target = url.pathname + url.search + url.hash;
      if (url.hash.startsWith("#/")) target = url.hash.replace(/^#/, "");
      window.history.pushState({}, "", target);
      const next = normalize(target.split("#")[0]);
      setRoute(next);

      // Scroll behavior
      const finalHash = target.split("#")[1];
      if (finalHash && !finalHash.startsWith("/")) {
        setTimeout(() => {
          const el = document.getElementById(finalHash);
          if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
        }, 80);
      } else {
        window.scrollTo({ top: 0, behavior: "instant" });
      }
    };
    document.addEventListener("click", handler);
    return () => document.removeEventListener("click", handler);
  }, []);

  // tweaks listener (parent host)
  useEffect(() => {
    const onMsg = (e) => {
      if (e.data?.type === "__activate_edit_mode") setTweakOpen(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweakOpen(false);
    };
    window.addEventListener("message", onMsg);
    window.parent?.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // apply tweaks via CSS vars on root
  useEffect(() => {
    document.documentElement.style.setProperty("--accent-intensity", tweaks.accentIntensity);
    if (!tweaks.showMesh) {
      document.documentElement.classList.add("no-mesh");
    } else {
      document.documentElement.classList.remove("no-mesh");
    }
    if (tweaks.ribbonGlow) {
      document.documentElement.classList.add("ribbon-glow");
    } else {
      document.documentElement.classList.remove("ribbon-glow");
    }
  }, [tweaks]);

  const updateTweak = (key, value) => {
    const next = { ...tweaks, [key]: value };
    setTweaks(next);
    window.parent?.postMessage({ type: "__edit_mode_set_keys", edits: { [key]: value } }, "*");
  };

  let page;
  switch (route) {
    case "/consulting":
      page = <ConsultingHub />; break;
    case "/consulting/digital-growth/websites":
      page = <WebsitesPage />; break;
    case "/consulting/tech-consulting":
      page = <TechConsultingPage />; break;
    case "/capital":
      page = <CapitalPage />; break;
    case "/contact":
      page = <ContactPage variant="group" />; break;
    case "/consulting/contact":
      page = <ContactPage variant="consult" />; break;
    case "/capital/contact":
      page = <ContactPage variant="capital" />; break;
    case "/reviewflow":
      page = <ReviewFlowPage />; break;
    case "/sinuxmod":
      page = <SinuxModPage />; break;
    case "/switchboard":
      page = <SwitchboardPage />; break;
    case "/privacy":
      page = <PrivacyPage />; break;
    case "/terms":
      page = <TermsPage />; break;
    case "/":
    default:
      page = <GroupHome />; break;
  }

  return (
    <>
      <div key={route}>{page}</div>
      {tweakOpen && (
        <TweakPanel
          tweaks={tweaks}
          onChange={updateTweak}
          onClose={() => {
            setTweakOpen(false);
            window.parent?.postMessage({ type: "__edit_mode_dismissed" }, "*");
          }}
        />
      )}
    </>
  );
}



// ============================================================
// Tweak Panel
// ============================================================
function TweakPanel({ tweaks, onChange, onClose }) {
  return (
    <div style={{
      position: "fixed", bottom: 24, right: 24, zIndex: 9000,
      width: 320,
      background: "rgba(17,24,39,0.96)",
      backdropFilter: "blur(20px)",
      border: "1px solid rgba(255,255,255,0.12)",
      borderRadius: 16,
      padding: 20,
      color: "var(--ink)",
      fontFamily: "'Poppins',sans-serif",
      boxShadow: "0 24px 60px -20px rgba(0,0,0,0.6)",
    }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 16 }}>
        <div style={{ fontFamily: "'Michroma',sans-serif", fontSize: 12, letterSpacing: "0.18em" }}>TWEAKS</div>
        <button onClick={onClose} style={{ background: "transparent", border: "none", color: "var(--ink-2)", cursor: "pointer", fontSize: 18 }}>×</button>
      </div>

      <Section title="Accent Intensity">
        <input
          type="range"
          min="0.4" max="1.5" step="0.05"
          value={tweaks.accentIntensity}
          onChange={(e) => onChange("accentIntensity", parseFloat(e.target.value))}
          style={{ width: "100%", accentColor: "var(--accent)" }}
        />
        <div style={{ color: "var(--ink-3)", fontSize: 12, marginTop: 4 }}>{tweaks.accentIntensity.toFixed(2)}×</div>
      </Section>

      <Section title="Hero Mesh">
        <Toggle on={tweaks.showMesh} onClick={() => onChange("showMesh", !tweaks.showMesh)} />
      </Section>

      <Section title="S-Ribbon Glow">
        <Toggle on={tweaks.ribbonGlow} onClick={() => onChange("ribbonGlow", !tweaks.ribbonGlow)} />
      </Section>

      <div style={{ marginTop: 16, fontSize: 11, color: "var(--ink-4)", lineHeight: 1.5 }}>
        Tweaks affect color intensity & background fx. Choices persist in this prototype.
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 8 }}>{title}</div>
      {children}
    </div>
  );
}

function Toggle({ on, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        width: 44, height: 26, borderRadius: 999,
        background: on ? "var(--consult)" : "rgba(255,255,255,0.1)",
        border: "1px solid var(--line)", cursor: "pointer", position: "relative", padding: 0,
        transition: "background .2s",
      }}
      aria-pressed={on}
    >
      <span style={{
        position: "absolute", top: 2, left: on ? 20 : 2,
        width: 20, height: 20, borderRadius: "50%",
        background: "#0a0d14",
        transition: "left .2s",
      }} />
    </button>
  );
}

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