// =========================================
// 태황 — App root
// =========================================

const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "navy",
  "heroLayout": "split",
  "showHanjaSeal": true,
  "accent": "#1fa3da"
}/*EDITMODE-END*/;

function App() {
  const [active, setActive] = useStateApp("top");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply theme + accent to root
  useEffectApp(() => {
    const root = document.documentElement;
    if (tweaks.theme === "navy" || tweaks.theme === "sky") root.removeAttribute("data-theme");
    else root.setAttribute("data-theme", tweaks.theme);
    // Drive only the primary accent; keep --accent-2 (lime) from CSS for the duo.
    if (tweaks.accent && tweaks.accent !== "#1fa3da") {
      root.style.setProperty("--accent", tweaks.accent);
    } else {
      root.style.removeProperty("--accent");
    }
  }, [tweaks.theme, tweaks.accent]);

  // Hero seal visibility
  useEffectApp(() => {
    const seal = document.querySelector(".hero-seal");
    if (seal) seal.style.display = tweaks.showHanjaSeal ? "" : "none";
  }, [tweaks.showHanjaSeal]);

  // Hero layout variant
  useEffectApp(() => {
    const grid = document.querySelector(".hero-grid");
    if (!grid) return;
    if (tweaks.heroLayout === "centered") {
      grid.style.gridTemplateColumns = "1fr";
      grid.style.textAlign = "center";
      grid.style.maxWidth = "880px";
      grid.style.margin = "0 auto";
      const copy = grid.querySelector(".hero-copy");
      if (copy) copy.style.margin = "0 auto";
    } else {
      grid.style.gridTemplateColumns = "";
      grid.style.textAlign = "";
      grid.style.maxWidth = "";
      grid.style.margin = "";
      const copy = grid.querySelector(".hero-copy");
      if (copy) copy.style.margin = "";
    }
  }, [tweaks.heroLayout]);

  // Smooth scroll
  const onNav = (id) => {
    if (id === "top") {
      window.scrollTo({ top: 0, behavior: "smooth" });
      return;
    }
    const el = document.getElementById(id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 70;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
  };

  // Handle inbound hash (e.g. arriving from projects.html#contact)
  useEffectApp(() => {
    const id = (window.location.hash || "").replace("#", "");
    if (!id) return;
    let tries = 0;
    const tryScroll = () => {
      const el = document.getElementById(id);
      if (el) {
        const y = el.getBoundingClientRect().top + window.scrollY - 70;
        window.scrollTo({ top: y, behavior: "smooth" });
      } else if (tries++ < 20) {
        setTimeout(tryScroll, 100);
      }
    };
    setTimeout(tryScroll, 300);
  }, []);

  // Active section tracking
  useEffectApp(() => {
    let ticking = false;
    let lastActive = null;
    const compute = () => {
      ticking = false;
      const sh = document.documentElement.scrollHeight;
      const atBottom = window.innerHeight + window.scrollY >= sh - 4;
      let next;
      if (atBottom) {
        // Near the bottom, force-activate the last in-page nav section
        // (footer-anchored sections like 협력사 never reach the top threshold).
        for (let i = NAV.length - 1; i >= 0; i--) {
          if (document.getElementById(NAV[i].id)) { next = NAV[i].id; break; }
        }
      } else {
        next = "top";
        for (const n of NAV) {
          const el = document.getElementById(n.id);
          if (el && el.getBoundingClientRect().top <= 200) next = n.id;
        }
      }
      if (next !== lastActive) {
        lastActive = next;
        setActive(next);
      }
    };
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(compute);
    };
    const onVisible = () => { ticking = false; compute(); };
    window.addEventListener("scroll", onScroll, { passive: true });
    document.addEventListener("visibilitychange", onVisible);
    compute();
    return () => {
      window.removeEventListener("scroll", onScroll);
      document.removeEventListener("visibilitychange", onVisible);
    };
  }, []);

  return (
    <>
      <Nav active={active} onNav={onNav} />
      <Hero onNav={onNav} />
      <Services />
      <SloganBand />
      <Process />
      <ProjectTeaser />
      <Contact />
      <Footer onNav={onNav} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="컬러 테마">
          <TweakRadio
            label="배경 톤"
            value={tweaks.theme}
            onChange={(v) => setTweak("theme", v)}
            options={[
              { value: "navy", label: "네이비" },
              { value: "ink", label: "잉크" },
              { value: "forest", label: "숲" },
            ]}
          />
          <TweakColor
            label="액센트 색"
            value={tweaks.accent}
            onChange={(v) => setTweak("accent", v)}
            options={["#1fa3da", "#84c33d", "#2f74e0", "#14a596"]}
          />
        </TweakSection>
        <TweakSection label="히어로">
          <TweakRadio
            label="레이아웃"
            value={tweaks.heroLayout}
            onChange={(v) => setTweak("heroLayout", v)}
            options={[
              { value: "split", label: "스플릿" },
              { value: "centered", label: "센터" },
            ]}
          />
          <TweakToggle
            label="한자 워터마크"
            value={tweaks.showHanjaSeal}
            onChange={(v) => setTweak("showHanjaSeal", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

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