// Precision Mobile Car Care — main app

const { useState: useStateA, useEffect: useEffectA } = React;

// Map accent hex → ink (dark text color over accent)
function inkForAccent(hex) {
  // simple luminance check
  const c = hex.replace("#", "");
  const r = parseInt(c.slice(0,2), 16), g = parseInt(c.slice(2,4), 16), b = parseInt(c.slice(4,6), 16);
  const lum = (0.299*r + 0.587*g + 0.114*b) / 255;
  return lum > 0.5 ? "#1a1206" : "#f6f4ef";
}

function App() {
  const [t, setTweak] = useTweaks(/*EDITMODE-BEGIN*/{
    "accent": "#FFC300",
    "bgTone": "garage"
  }/*EDITMODE-END*/);

  const [bookOpen, setBookOpen] = useStateA(false);
  const [lbIndex, setLbIndex] = useStateA(null);

  // apply theme via CSS variables
  useEffectA(() => {
    const root = document.documentElement;
    root.style.setProperty("--accent", t.accent);
    root.style.setProperty("--accent-ink", inkForAccent(t.accent));

    const themes = {
      garage: {
        bg: "13% 0.006 60", bg1: "16% 0.008 60", bg2: "20% 0.01 60",
        line: "28% 0.012 60", line2: "35% 0.014 60",
        fg: "96% 0.008 85", fg2: "78% 0.01 85", muted: "58% 0.012 80",
      },
      midnight: {
        bg: "8% 0.012 260", bg1: "11% 0.014 260", bg2: "15% 0.016 260",
        line: "22% 0.018 260", line2: "30% 0.02 260",
        fg: "96% 0.008 240", fg2: "78% 0.012 240", muted: "58% 0.014 240",
      },
      showroom: {
        bg: "96% 0.006 80", bg1: "99% 0.004 80", bg2: "93% 0.008 80",
        line: "85% 0.008 80", line2: "75% 0.01 80",
        fg: "15% 0.008 60", fg2: "35% 0.012 60", muted: "50% 0.012 60",
      },
      carbon: {
        bg: "10% 0.008 250", bg1: "13% 0.01 250", bg2: "17% 0.012 250",
        line: "24% 0.014 250", line2: "32% 0.016 250",
        fg: "97% 0.005 240", fg2: "78% 0.008 240", muted: "55% 0.012 240",
      },
      sunset: {
        bg: "14% 0.02 40", bg1: "17% 0.025 40", bg2: "22% 0.03 35",
        line: "30% 0.035 35", line2: "38% 0.04 35",
        fg: "96% 0.012 70", fg2: "78% 0.018 60", muted: "60% 0.025 50",
      },
      concrete: {
        bg: "28% 0.004 80", bg1: "32% 0.006 80", bg2: "38% 0.008 80",
        line: "45% 0.01 80", line2: "55% 0.012 80",
        fg: "97% 0.005 80", fg2: "85% 0.008 80", muted: "70% 0.01 80",
      },
      blueprint: {
        bg: "22% 0.06 240", bg1: "26% 0.07 240", bg2: "32% 0.08 240",
        line: "40% 0.09 240", line2: "50% 0.1 240",
        fg: "96% 0.015 220", fg2: "82% 0.025 220", muted: "65% 0.04 220",
      },
      bone: {
        bg: "92% 0.012 65", bg1: "96% 0.008 65", bg2: "88% 0.018 60",
        line: "75% 0.022 55", line2: "60% 0.028 50",
        fg: "18% 0.015 40", fg2: "32% 0.02 40", muted: "48% 0.022 45",
      },
    };
    const th = themes[t.bgTone] || themes.garage;
    root.style.setProperty("--bg", `oklch(${th.bg})`);
    root.style.setProperty("--bg-1", `oklch(${th.bg1})`);
    root.style.setProperty("--bg-2", `oklch(${th.bg2})`);
    root.style.setProperty("--line", `oklch(${th.line})`);
    root.style.setProperty("--line-2", `oklch(${th.line2})`);
    root.style.setProperty("--fg", `oklch(${th.fg})`);
    root.style.setProperty("--fg-2", `oklch(${th.fg2})`);
    root.style.setProperty("--muted", `oklch(${th.muted})`);
  }, [t.accent, t.bgTone]);

  // Scroll-driven animation effects.
  // Drives a "polish" CSS variable --p on the hero (0→1 as it scrolls past)
  // and a --r reveal variable on section heads, gallery items, marquee + giant
  // wordmark based on each element's individual visibility. Because both
  // values track scroll POSITION (not one-shot events), scrolling back up
  // automatically reverses the animation.
  useEffectA(() => {
    const hero = document.querySelector(".hero");
    // entry animation: trigger one frame after mount
    if (hero) {
      requestAnimationFrame(() => {
        hero.style.setProperty("--in", "1");
      });
      // belt-and-braces in case the rAF is throttled (backgrounded tab):
      setTimeout(() => hero.style.setProperty("--in", "1"), 80);
    }

    let lastY = -1;
    let scheduled = false;
    const apply = () => {
      scheduled = false;
      const y = window.scrollY;
      if (y === lastY) return;
      lastY = y;
      const vh = window.innerHeight;

      // 1) hero polish progress
      if (hero) {
        const r = hero.getBoundingClientRect();
        const p = Math.max(0, Math.min(1, -r.top / (hero.offsetHeight * 0.7)));
        hero.style.setProperty("--p", p.toFixed(3));
      }

      // (Showcase scroll-zoom removed — cards are now static.)

      // 3) reveal-based progress for sections, gallery, marquee, footer mark
      const targets = document.querySelectorAll(
        ".section-head, .gallery-item, .marquee, .giant-mark, .reveal, .reveal-soft"
      );
      targets.forEach((el) => {
        const r = el.getBoundingClientRect();
        const h = el.offsetHeight || 1;
        const start = vh + h * 0.1;
        const end = -h * 0.4;
        const cur = r.top;
        const prog = Math.max(0, Math.min(1, (start - cur) / (start - end)));
        el.style.setProperty("--r", prog.toFixed(3));
      });
    };
    const schedule = () => {
      if (scheduled) return;
      scheduled = true;
      requestAnimationFrame(apply);
    };
    // Initial pass
    apply();
    // Multiple wake sources — scroll for primary, resize for layout changes,
    // and a low-rate interval as a final fallback if rAF/scroll get throttled.
    window.addEventListener("scroll", schedule, { passive: true });
    window.addEventListener("resize", schedule);
    const onVis = () => { lastY = -1; schedule(); };
    document.addEventListener("visibilitychange", onVis);
    const intervalId = setInterval(schedule, 100);
    return () => {
      window.removeEventListener("scroll", schedule);
      window.removeEventListener("resize", schedule);
      document.removeEventListener("visibilitychange", onVis);
      clearInterval(intervalId);
    };
  }, []);

  // smooth scroll for in-page links
  useEffectA(() => {
    const fn = (e) => {
      const a = e.target.closest("a[href^='#']");
      if (!a) return;
      const id = a.getAttribute("href").slice(1);
      if (!id || id === "top") {
        e.preventDefault();
        window.scrollTo({ top: 0, behavior: "smooth" });
        return;
      }
      const el = document.getElementById(id);
      if (el) {
        e.preventDefault();
        const y = el.getBoundingClientRect().top + window.scrollY - 80;
        window.scrollTo({ top: y, behavior: "smooth" });
      }
    };
    document.addEventListener("click", fn);
    return () => document.removeEventListener("click", fn);
  }, []);

  const navGallery = (delta) => {
    setLbIndex(prev => {
      if (prev === null) return null;
      const n = GALLERY.length;
      return (prev + delta + n) % n;
    });
  };

  return (
    <>
      <Nav onBook={() => setBookOpen(true)} />
      <Hero onBook={() => setBookOpen(true)} />
      <ShowcaseSection />
      <Services onBook={() => setBookOpen(true)} />
      <Process />
      <Gallery onOpen={setLbIndex} />
      <VehiclesSection />
      <Contact onBook={() => setBookOpen(true)} />
      <Footer />

      {bookOpen && <BookingModal onClose={() => setBookOpen(false)} />}
      {lbIndex !== null && (
        <Lightbox index={lbIndex} onClose={() => setLbIndex(null)} onNav={navGallery} />
      )}

      {SITE.showTweaks && (
      <TweaksPanel title="Tweaks">
        <TweakSection label="Accent colour">
          <TweakColor
            label="Pick a swatch"
            value={t.accent}
            options={["#FFC300", "#E63725", "#B6FF2A", "#E8EAF0", "#FF6A1A"]}
            onChange={(v) => setTweak("accent", v)}
          />
        </TweakSection>
        <TweakSection label="Background">
          <TweakSelect
            label="Theme"
            value={t.bgTone}
            options={[
              { label: "Garage Black", value: "garage" },
              { label: "Carbon Fibre", value: "carbon" },
              { label: "Midnight Blue", value: "midnight" },
              { label: "Sunset Amber", value: "sunset" },
              { label: "Blueprint Navy", value: "blueprint" },
              { label: "Workshop Concrete", value: "concrete" },
              { label: "Bone White", value: "bone" },
              { label: "Showroom Light", value: "showroom" },
            ]}
            onChange={(v) => setTweak("bgTone", v)}
          />
        </TweakSection>
      </TweaksPanel>
      )}
    </>
  );
}

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