const { useState: useStateMain, useEffect: useEffectMain } = React;

// Tweakable defaults
const PORTFOLIO_TWEAKS = /*EDITMODE-BEGIN*/{
  "surface": "graphite",
  "heroScale": "calm",
  "accent": "#1ED760",
  "columnWidth": 1440
}/*EDITMODE-END*/;

function App() {
  const [lang, setLang] = useStateMain(() => {
    if (typeof localStorage !== "undefined") {
      return localStorage.getItem("leandro.lang") || "en";
    }
    return "en";
  });
  const [route, setRoute] = useStateMain(() => parseHash());

  const tw = window.useTweaks(PORTFOLIO_TWEAKS);

  useEffectMain(() => {
    const root = document.documentElement;
    if (tw.surface === "paper") root.setAttribute("data-surface", "paper");
    else root.removeAttribute("data-surface");

    if (tw.heroScale === "calm") {
      root.style.setProperty("--hero-size", "clamp(38px, 5.5vw, 82px)");
      root.style.setProperty("--hero-weight", "900");
    } else if (tw.heroScale === "editorial") {
      root.style.setProperty("--hero-size", "clamp(56px, 8vw, 112px)");
      root.style.setProperty("--hero-weight", "900");
    } else if (tw.heroScale === "brutal") {
      root.style.setProperty("--hero-size", "clamp(72px, 11vw, 156px)");
      root.style.setProperty("--hero-weight", "900");
    }

    root.style.setProperty("--signal", tw.accent || "#1ED760");
    root.style.setProperty("--col", (tw.columnWidth && tw.columnWidth > 0) ? (tw.columnWidth + "px") : "100%");
  }, [tw.surface, tw.heroScale, tw.accent, tw.columnWidth]);

  useEffectMain(() => {
    try { localStorage.setItem("leandro.lang", lang); } catch (e) {}
    document.documentElement.lang = lang === "pt" ? "pt-BR" : "en";
  }, [lang]);

  useEffectMain(() => {
    function onHash() { setRoute(parseHash()); }
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  useEffectMain(() => {
    if (route.kind === "home") {
      if (route.anchor) {
        const id = route.anchor;
        setTimeout(() => {
          const el = document.getElementById(id);
          if (el) {
            if (id === "home") window.scrollTo({ top: 0, behavior: "smooth" });
            else el.scrollIntoView({ behavior: "smooth", block: "start" });
          }
        }, 60);
      }
    } else {
      window.scrollTo({ top: 0, behavior: "instant" });
    }
  }, [route]);

  const navigate = (next) => {
    if (next.kind === "case") {
      window.location.hash = `#case/${next.slug}`;
    } else {
      if (next.anchor && next.anchor !== "home") {
        window.location.hash = `#${next.anchor}`;
      } else {
        history.replaceState(null, "", " ");
        setRoute({ kind: "home", anchor: "home" });
      }
    }
  };

  const scrollToOnHome = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <React.Fragment>
      <TopBar lang={lang} setLang={setLang} onNavigate={navigate} route={route} />

      {route.kind === "home" && (
        <main>
          <Hero lang={lang} onScrollTo={scrollToOnHome} />
          <Works lang={lang} onOpenCase={(slug) => navigate({ kind: "case", slug })} />
          <About lang={lang} />
          <Contact lang={lang} />
          <PageFooter lang={lang} />
        </main>
      )}

      {route.kind === "case" && (
        <CaseStudy
          slug={route.slug}
          lang={lang}
          onBack={() => navigate({ kind: "home", anchor: "works" })}
          onNext={() => {
            const seq = ["marketing-materials", "regulatory-app", "campaign-management"];
            const idx = seq.indexOf(route.slug);
            const next = seq[(idx + 1) % seq.length];
            navigate({ kind: "case", slug: next });
          }}
        />
      )}

      <PortfolioTweaks tw={tw} />
    </React.Fragment>
  );
}

function parseHash() {
  const h = (window.location.hash || "").replace(/^#/, "");
  if (h.startsWith("case/")) {
    return { kind: "case", slug: h.slice(5) };
  }
  if (["works", "about", "contact", "home"].includes(h)) {
    return { kind: "home", anchor: h };
  }
  return { kind: "home", anchor: null };
}

function PortfolioTweaks({ tw }) {
  const { TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakSlider } = window;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection label="Surface">
        <TweakRadio
          label="Mode"
          value={tw.surface}
          onChange={(v) => tw.setTweak("surface", v)}
          options={[
            { value: "graphite", label: "Graphite" },
            { value: "paper", label: "Paper" },
          ]}
        />
      </TweakSection>

      <TweakSection label="Hero scale">
        <TweakRadio
          label="Headline"
          value={tw.heroScale}
          onChange={(v) => tw.setTweak("heroScale", v)}
          options={[
            { value: "calm", label: "Calm" },
            { value: "editorial", label: "Editorial" },
            { value: "brutal", label: "Brutal" },
          ]}
        />
      </TweakSection>

      <TweakSection label="Signal accent">
        <TweakColor
          label="Color"
          value={tw.accent}
          onChange={(v) => tw.setTweak("accent", v)}
          options={[
            "#1ED760",
            "#E5C547",
            "#F2643D",
            "#7EB7FF",
            "#FBFDFE",
          ]}
        />
      </TweakSection>

      <TweakSection label="Column width">
        <TweakRadio
          label="Mode"
          value={tw.columnWidth === 0 ? "full" : "cap"}
          onChange={(v) => tw.setTweak("columnWidth", v === "full" ? 0 : 1760)}
          options={[
            { value: "full", label: "Full bleed" },
            { value: "cap", label: "Capped" },
          ]}
        />
        {tw.columnWidth > 0 && (
          <TweakSlider
            label="Max width"
            value={tw.columnWidth}
            onChange={(v) => tw.setTweak("columnWidth", v)}
            min={1040}
            max={2400}
            step={40}
            unit="px"
          />
        )}
      </TweakSection>
    </TweaksPanel>
  );
}

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