// Main app — UCreativeMedia portfolio site
const { useState: useStateApp, useEffect: useEffectApp } = React;

// Brands shown in the moving strip under the hero.
const CLIENTS = [
  "Alpha Clinic", "Aluste", "AndreiCBR", "Elgis", "Emirai",
  "House of Ads", "Imatrend", "Kinetolin", "Kuryna",
  "MeaVana", "Milla Milla", "Nick-ice",
  "Nota Maxima", "PastryShop", "PadelShop", "Pure Clinique", "SarandiMob",
  "Stemata",
];

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#00bf7a",
  "density": "regular",
  "scrollProgress": true
}/*EDITMODE-END*/;

// Temporarily disabled: site runs English-only, dark-only. Flip to true to restore the toggles.
const ENABLE_THEME_SWITCH = false;
const ENABLE_LANG_SWITCH = false;
// Temporarily hidden: the Contact section, its nav link and the hero "contact" button.
const SHOW_CONTACT = false;
const DEFAULT_THEME = "dark";
const DEFAULT_LANG = "en";

// ─── Sun / Moon icon ───────────────────────────────────────────────────────
function ThemeIcon({ dark }) {
  return dark ? (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
    </svg>
  ) : (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="4" />
      <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
    </svg>
  );
}

function Nav({ lang, setLang, theme, setTheme, t, accent }) {
  const [scrolled, setScrolled] = useStateApp(false);
  const [active, setActive] = useStateApp("top");

  useEffectApp(() => {
    const SECTIONS = ["top", "services", "portfolio", "universe", "contact"];
    const onScroll = () => {
      setScrolled(window.scrollY > 40);
      // Determine which section is currently most in view
      const probe = window.scrollY + window.innerHeight * 0.35;
      let current = SECTIONS[0];
      for (const id of SECTIONS) {
        const el = document.getElementById(id);
        if (!el) continue;
        if (el.offsetTop <= probe) current = id;
      }
      setActive(current);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    { href: "#services", id: "services", label: t.nav.services },
    { href: "#portfolio", id: "portfolio", label: t.nav.portfolio },
    { href: "#universe", id: "universe", label: t.nav.universe },
    { href: "#contact", id: "contact", label: t.nav.contact },
  ].filter((l) => SHOW_CONTACT || l.id !== "contact");

  return (
    <nav style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 100,
      padding: scrolled ? "12px 6vw" : "20px 6vw",
      background: scrolled ? "var(--nav-bg)" : "transparent",
      backdropFilter: scrolled ? "blur(16px) saturate(140%)" : "none",
      WebkitBackdropFilter: scrolled ? "blur(16px) saturate(140%)" : "none",
      borderBottom: scrolled ? "1px solid var(--border-soft-1)" : "1px solid transparent",
      display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24,
      transition: "padding 300ms, background 300ms, border-color 300ms",
    }}>
      <a href="#top" style={{ display: "flex", alignItems: "center", textDecoration: "none" }}>
        <UCreativeLogoImg theme={theme} height={scrolled ? 40 : 48} />
      </a>

      <div className="nav-links" style={{ display: "flex", alignItems: "center", gap: 4 }}>
        {links.map((l, i) => {
          const isActive = active === l.id;
          return (
            <a key={i} href={l.href} style={{
              fontFamily: "Quicksand, sans-serif", fontWeight: 600, fontSize: 13,
              color: isActive ? accent : "var(--ink-1)",
              textDecoration: "none", padding: "8px 14px",
              borderRadius: 999, letterSpacing: ".01em",
              opacity: isActive ? 1 : 0.7,
              position: "relative",
              transition: "color 220ms, opacity 220ms, background 200ms",
            }}
              onMouseEnter={(e) => { if (!isActive) { e.currentTarget.style.opacity = 1; e.currentTarget.style.background = "var(--border-soft-1)"; } }}
              onMouseLeave={(e) => { if (!isActive) { e.currentTarget.style.opacity = 0.7; e.currentTarget.style.background = "transparent"; } }}
            >
              {l.label}
              <span aria-hidden style={{
                position: "absolute", left: 14, right: 14, bottom: 2, height: 2,
                background: accent, borderRadius: 2,
                transform: isActive ? "scaleX(1)" : "scaleX(0)",
                transformOrigin: "center",
                transition: "transform 360ms cubic-bezier(.2,.7,.2,1)",
              }} />
            </a>
          );
        })}
      </div>

      {/* Right cluster: theme + lang */}
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        {/* Theme toggle */}
        {ENABLE_THEME_SWITCH && <button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
          aria-label={theme === "dark" ? "Switch to light" : "Switch to dark"}
          style={{
            appearance: "none", border: "1px solid var(--border-1)", cursor: "pointer",
            background: "var(--pill-bg)", color: "var(--ink-1)",
            width: 36, height: 36, borderRadius: 999, padding: 0,
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            transition: "background 200ms",
          }}
          onMouseEnter={(e) => e.currentTarget.style.background = "var(--border-soft-1)"}
          onMouseLeave={(e) => e.currentTarget.style.background = "var(--pill-bg)"}
        >
          <ThemeIcon dark={theme === "dark"} />
        </button>}

        {/* Lang switch */}
        {ENABLE_LANG_SWITCH && <div style={{
          display: "flex", alignItems: "center", gap: 0, padding: 3,
          border: "1px solid var(--border-1)", borderRadius: 999,
          background: "var(--pill-bg)",
        }}>
          {["en", "ro"].map((l) => {
            const active = l === lang;
            return (
              <button key={l} onClick={() => setLang(l)} aria-pressed={active}
                style={{
                  appearance: "none", border: 0, cursor: "pointer",
                  background: active ? "var(--ink-1)" : "transparent",
                  color: active ? "var(--bg-1)" : "var(--ink-1)",
                  fontFamily: "Quicksand, sans-serif", fontWeight: 700, fontSize: 11,
                  letterSpacing: ".14em", textTransform: "uppercase",
                  padding: "8px 14px", borderRadius: 999,
                  transition: "background 250ms, color 250ms",
                }}>
                {l}
              </button>
            );
          })}
        </div>}
      </div>
    </nav>
  );
}

function ScrollProgress({ accent, enabled }) {
  const [p, setP] = useStateApp(0);
  useEffectApp(() => {
    if (!enabled) return;
    const onScroll = () => {
      const h = document.documentElement;
      const max = h.scrollHeight - h.clientHeight;
      setP(max > 0 ? window.scrollY / max : 0);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [enabled]);
  if (!enabled) return null;
  return (
    <div aria-hidden style={{
      position: "fixed", top: 0, left: 0, right: 0, height: 2, zIndex: 101,
      background: "transparent", pointerEvents: "none",
    }}>
      <div style={{
        height: "100%", width: `${p * 100}%`, background: accent,
        transition: "width 80ms linear",
      }} />
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useStateApp(DEFAULT_LANG);
  const [theme, setTheme] = useStateApp(() => {
    if (!ENABLE_THEME_SWITCH) return DEFAULT_THEME;
    try { return localStorage.getItem("ucm-theme") || DEFAULT_THEME; } catch(e) { return DEFAULT_THEME; }
  });
  const copy = COPY[lang];
  const accent = t.accent;

  // Apply theme to body (persist via localStorage, NOT setTweak to avoid host reload)
  useEffectApp(() => {
    document.body.setAttribute("data-theme", theme);
    try { localStorage.setItem("ucm-theme", theme); } catch(e) {}
  }, [theme]);

  // Smooth scrolling for anchor links
  useEffectApp(() => {
    const onClick = (e) => {
      const a = e.target.closest('a[href^="#"]');
      if (!a) return;
      const id = a.getAttribute("href").slice(1);
      if (!id) return;
      const el = document.getElementById(id);
      if (!el) return;
      e.preventDefault();
      window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  return (
    <div style={{ background: "var(--bg-1)", color: "var(--ink-1)", minHeight: "100vh" }}>
      <ScrollProgress accent={accent} enabled={t.scrollProgress} />
      <Nav lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} t={copy} accent={accent} />
      <Hero t={copy} accent={accent} theme={theme} showContact={SHOW_CONTACT} />
      <ClientMarquee accent={accent} names={CLIENTS} />
      <Services t={copy} accent={accent} />
      <Portfolio t={copy} accent={accent} density={t.density} lang={lang} />
      <UniverseSection t={copy} accent={accent} theme={theme} />
      {SHOW_CONTACT && <Contact t={copy} accent={accent} />}
      <Footer t={copy} accent={accent} theme={theme} />

      <TweaksPanel title="Tweaks">
        {ENABLE_THEME_SWITCH && <>
          <TweakSection label="Theme" />
          <TweakRadio label="Mode" value={theme}
            options={["light", "dark"]}
            onChange={(v) => setTheme(v)} />
        </>}
        <TweakSection label="Accent" />
        <TweakColor label="Color" value={t.accent}
          options={["#00bf7a", "#ff6b35", "#3b82f6", "#e0b34a", "#a855f7"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakSection label="UI" />
        <TweakToggle label="Scroll progress bar" value={t.scrollProgress}
          onChange={(v) => setTweak("scrollProgress", v)} />
      </TweaksPanel>
    </div>
  );
}

// Set initial theme attribute before React mounts (avoids flicker)
try {
  const saved = ENABLE_THEME_SWITCH ? localStorage.getItem("ucm-theme") : null;
  document.body.setAttribute("data-theme", saved === "light" || saved === "dark" ? saved : DEFAULT_THEME);
} catch(e) {
  document.body.setAttribute("data-theme", DEFAULT_THEME);
}

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