// AI Solutions v2 — main app
const { useState: useStateA, useEffect: useEffectA } = React;

// IntersectionObserver reveal.
// Idempotent: only observes `.reveal` elements that haven't fired yet
// (no `in` class). Re-running on lang/variant change must NOT strip `in`
// from already-revealed sections — otherwise blocks outside the viewport
// would stay invisible because IntersectionObserver only fires on crossings.
function useReveal(deps) {
  useEffectA(() => {
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -40px 0px" }
    );
    document.querySelectorAll(".reveal:not(.in)").forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, deps);
}

// Subtle vertical depth indicator on the right edge — same vibe as the
// .process-track playhead, but spans the whole page. Hidden on small screens
// and when the user prefers reduced motion.
function ScrollIndicator() {
  const [pct, setPct] = useStateA(0);
  const [activeIdx, setActiveIdx] = useStateA(0);
  // Sections in their on-page order (must match render order in <App>)
  const sections = ["top", "services", "process", "cases", "faq", "contacts"];

  useEffectA(() => {
    let raf = 0;
    const compute = () => {
      raf = 0;
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const docH = (document.documentElement.scrollHeight || 0) - window.innerHeight;
      const p = docH > 0 ? Math.min(100, Math.max(0, (scrollTop / docH) * 100)) : 0;
      setPct(p);
      const mid = scrollTop + window.innerHeight * 0.4;
      let idx = 0;
      for (let i = 0; i < sections.length; i++) {
        const el = document.getElementById(sections[i]);
        if (el && el.offsetTop <= mid) idx = i;
      }
      setActiveIdx(idx);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(compute); };
    compute();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  const n = sections.length;
  return (
    <div className="scroll-indicator" aria-hidden="true">
      <div className="scroll-indicator-track">
        <div className="scroll-indicator-fill" style={{ height: pct + "%" }} />
        {sections.map((_, i) => (
          <div
            key={i}
            className={"scroll-indicator-tick" + (i <= activeIdx ? " lit" : "")}
            style={{ top: ((i / (n - 1)) * 100) + "%" }}
          />
        ))}
        <div className="scroll-indicator-head" style={{ top: pct + "%" }} />
      </div>
    </div>
  );
}

// Easter-egg overlay — a slow warm-light surge plus a field of ✦ sparks that
// drift up and fade. Positions are index-derived (deterministic, no random).
function EggFX({ type, x, y }) {
  const ox = (x != null ? x : window.innerWidth / 2) + "px";
  const oy = (y != null ? y : window.innerHeight / 2) + "px";
  const N = 18;
  const sparks = [];
  for (let i = 0; i < N; i++) {
    sparks.push({
      i,
      left: 4 + (i * 92) / (N - 1) + ((i % 3) - 1) * 3,
      size: 9 + (i % 4) * 5,
      dur: 2800 + (i % 5) * 420,
      delay: (i % 5) * 110,
      dx: ((i % 2) ? 1 : -1) * (18 + (i % 4) * 16),
      rot: ((i % 2) ? 1 : -1) * (40 + (i % 3) * 50),
    });
  }
  const toast =
    type === "konami" ? "Konami unlocked ✦"
    : type === "word" ? "You typed it ✦ Simplify.ai"
    : "✦ Simplify.ai — crafted with care";
  return (
    <div className="egg-fx" aria-hidden="true" style={{ "--ex": ox, "--ey": oy }}>
      <div className="egg-glow"></div>
      {sparks.map((s) => (
        <span
          key={s.i}
          className="egg-spark"
          style={{
            left: s.left + "%",
            "--sz": s.size + "px",
            "--dur": s.dur + "ms",
            "--dl": s.delay + "ms",
            "--dx": s.dx + "px",
            "--rot": s.rot + "deg",
          }}
        >✦</span>
      ))}
      <div className="egg-toast"><span className="egg-dot"></span>{toast}</div>
    </div>
  );
}

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "b",
  "theme": "dark"
}/*EDITMODE-END*/;

function App() {
  const [lang, setLang] = useStateA("ru");
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  // Easter-egg state: bumping `id` re-mounts EggFX so the animation replays.
  const [egg, setEgg] = useStateA({ type: null, id: 0, x: null, y: null });

  const t = window.CONTENT[lang];

  const fireEgg = (type, x, y) => setEgg((e) => ({ type, id: e.id + 1, x, y }));

  // Auto-dismiss the egg overlay after the sparks have finished drifting.
  useEffectA(() => {
    if (!egg.type) return;
    const tm = setTimeout(() => setEgg((e) => ({ ...e, type: null })), 5200);
    return () => clearTimeout(tm);
  }, [egg.id]);

  // Egg #1 — the Konami code.
  useEffectA(() => {
    const seq = ["arrowup", "arrowup", "arrowdown", "arrowdown", "arrowleft", "arrowright", "arrowleft", "arrowright", "b", "a"];
    let pos = 0;
    const onKey = (e) => {
      const k = (e.key || "").toLowerCase();
      if (k === seq[pos]) {
        pos += 1;
        if (pos === seq.length) { pos = 0; fireEgg("konami"); }
      } else {
        pos = k === seq[0] ? 1 : 0;
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Egg #2 — dispatched by the logo dot after 5 quick clicks (see Nav).
  useEffectA(() => {
    const onEgg = (e) => {
      const d = e.detail || {};
      fireEgg("logo", d.x, d.y);
    };
    window.addEventListener("simplify:egg", onEgg);
    return () => window.removeEventListener("simplify:egg", onEgg);
  }, []);

  // Egg #3 — type the brand name "simplify" anywhere on the page.
  useEffectA(() => {
    let buf = "";
    const onKey = (e) => {
      if (!e.key || e.key.length !== 1) return;
      buf = (buf + e.key.toLowerCase()).slice(-12);
      if (buf.endsWith("simplify")) { buf = ""; fireEgg("word"); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Developer signature in the console — hints at egg #1.
  useEffectA(() => {
    try {
      console.log(
        "%c✦ Simplify.ai",
        "color:#e8d6b3;font-size:14px;font-weight:600;letter-spacing:.04em"
      );
      console.log(
        "%cНравится, как сделано? Секреты: ↑↑↓↓←→←→BA · 5 кликов по точке логотипа · набери «simplify». Потом напиши нам в Telegram.",
        "color:#9a917f;font-size:11px"
      );
    } catch (e) {}
  }, []);

  // Cursor glow — odbo.dev style spotlight that follows cursor
  useEffectA(() => {
    let raf = 0;
    let tx = 0, ty = 0, cx = 0, cy = 0;
    const root = document.documentElement;
    const onMove = (e) => {
      tx = e.clientX;
      ty = e.clientY;
      if (!raf) raf = requestAnimationFrame(tick);
    };
    const tick = () => {
      cx += (tx - cx) * 0.18;
      cy += (ty - cy) * 0.18;
      root.style.setProperty("--mx", cx + "px");
      root.style.setProperty("--my", cy + "px");
      if (Math.abs(tx - cx) > 0.5 || Math.abs(ty - cy) > 0.5) {
        raf = requestAnimationFrame(tick);
      } else { raf = 0; }
    };
    window.addEventListener("pointermove", onMove);
    return () => { window.removeEventListener("pointermove", onMove); if (raf) cancelAnimationFrame(raf); };
  }, []);

  // Apply theme attribute on documentElement
  useEffectA(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme);
  }, [tweaks.theme]);

  // Hero aurora parallax — container drifts with cursor + scroll (lerped).
  // Children keep their own drift keyframes; this only moves the wrapper.
  useEffectA(() => {
    if (window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf = 0;
    let mx = 0, my = 0;           // target offset from mouse (-1..1)
    let cx = 0, cy = 0;           // current (lerped) mouse offset
    const onMove = (e) => {
      mx = (e.clientX / window.innerWidth - 0.5);
      my = (e.clientY / window.innerHeight - 0.5);
      if (!raf) raf = requestAnimationFrame(tick);
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(tick); };
    const tick = () => {
      raf = 0;
      const aurora = document.querySelector(".hero-aurora");
      if (!aurora) return;
      cx += (mx - cx) * 0.08;
      cy += (my - cy) * 0.08;
      const sc = window.scrollY || 0;
      aurora.style.setProperty("--par-x", (cx * 26).toFixed(1) + "px");
      aurora.style.setProperty("--par-y", (cy * 20 - sc * 0.06).toFixed(1) + "px");
      if (Math.abs(mx - cx) > 0.001 || Math.abs(my - cy) > 0.001) {
        raf = requestAnimationFrame(tick);
      }
    };
    window.addEventListener("pointermove", onMove, { passive: true });
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => {
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("scroll", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, []);

  useEffectA(() => {
    document.documentElement.lang = lang;
  }, [lang]);

  useReveal([lang, tweaks.heroVariant]);

  // Theme switch with a circular reveal that emanates from the toggle button.
  // origin = {x, y} click point. Falls back to the plain CSS color cross-fade
  // when View Transitions aren't supported or reduced-motion is requested.
  const setTheme = (next, origin) => {
    // Set the attribute synchronously so the View Transition snapshot captures
    // the new theme (React's setState is async and would miss the frame).
    const apply = () => {
      document.documentElement.setAttribute("data-theme", next);
      setTweak("theme", next);
    };
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (document.startViewTransition && !reduce) {
      const root = document.documentElement;
      const x = origin && origin.x != null ? origin.x : window.innerWidth - 56;
      const y = origin && origin.y != null ? origin.y : 30;
      root.style.setProperty("--vt-x", x + "px");
      root.style.setProperty("--vt-y", y + "px");
      // Suspend the body's 0.4s color transition so the VT snapshot captures
      // the final theme instantly — the circular wipe is the transition now.
      root.classList.add("theme-switching");
      const vt = document.startViewTransition(apply);
      vt.finished.finally(() => root.classList.remove("theme-switching"));
    } else {
      apply();
    }
  };

  return (
    <>
      <div className="cursor-glow" aria-hidden="true"></div>
      {egg.type && <EggFX key={egg.id} type={egg.type} x={egg.x} y={egg.y} />}
      <Nav lang={lang} setLang={setLang} theme={tweaks.theme} setTheme={setTheme} t={t} />
      <ScrollIndicator />
      <Hero t={t} variant={tweaks.heroVariant} />
      <Services t={t} />
      <Process t={t} />
      <Cases t={t} lang={lang} />
      <FAQ t={t} />
      <Contacts t={t} lang={lang} />
      <Footer t={t} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Тема" />
        <TweakRadio
          label="Цветовая схема"
          value={tweaks.theme}
          onChange={(v) => setTweak("theme", v)}
          options={[
            { value: "dark",  label: "Dark" },
            { value: "light", label: "Light" },
          ]}
        />
        <TweakSection label="Hero" />
        <TweakRadio
          label="Вариант hero"
          value={tweaks.heroVariant}
          onChange={(v) => setTweak("heroVariant", v)}
          options={[
            { value: "a", label: "A · Центр" },
            { value: "b", label: "B · Слева" },
          ]}
        />
        <TweakButton
          label="↻ Replay hero animation"
          onClick={() => {
            const cur = tweaks.heroVariant;
            const other = cur === "a" ? "b" : "a";
            setTweak("heroVariant", other);
            setTimeout(() => setTweak("heroVariant", cur), 30);
          }}
        />
      </TweaksPanel>
    </>
  );
}

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