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

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#C7411E",
  "background": "#F2EEE5",
  "ink": "#0F0E0C",
  "theme": "dark",
  "headlineFont": "fraunces",
  "density": "tight",
  "cursor": "dot",
  "heroVariant": "split",
  "marqueeSpeed": 60,
  "showCursor": true
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  { label: "Burnt orange", value: "#C7411E" },
  { label: "Tomato", value: "#D85A2A" },
  { label: "Ochre", value: "#C28A2C" },
  { label: "Forest", value: "#3F5B3A" },
  { label: "Slate blue", value: "#3A4A5C" },
  { label: "Plum", value: "#6B3D52" },
];

const BG_OPTIONS = [
  { label: "Cream", value: "#F2EEE5", ink: "#0F0E0C" },
  { label: "Bone", value: "#E8E2D2", ink: "#0F0E0C" },
  { label: "Paper", value: "#FAF8F2", ink: "#0F0E0C" },
  { label: "Ink", value: "#0F0E0C", ink: "#E8DCC8" },
];

const FONT_OPTIONS = [
  { label: "Fraunces (serif)", value: "fraunces" },
  { label: "Cormorant (serif)", value: "cormorant" },
  { label: "PP Editorial (serif)", value: "editorial" },
  { label: "Söhne-style (sans)", value: "sans" },
];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [openProject, setOpenProject] = useStateA(null);
  const [activeIdx, setActiveIdx] = useStateA(0);
  const { PROJECTS, INDEX_ROWS, JOURNAL, CLIENTS } = window.PORTFOLIO_DATA;

  // Apply CSS vars + theme
  useEffectA(() => {
    const root = document.documentElement;
    root.setAttribute("data-theme", t.theme || "light");
    root.style.setProperty("--accent", t.accent);
    root.style.setProperty("--marquee-dur", `${t.marqueeSpeed}s`);
    const fontMap = {
      fraunces: "'Fraunces', 'Times New Roman', serif",
      cormorant: "'Cormorant Garamond', 'Times New Roman', serif",
      editorial: "'Instrument Serif', 'Fraunces', serif",
      sans: "'Inter Tight', 'Helvetica Neue', sans-serif",
    };
    root.style.setProperty("--font-display", fontMap[t.headlineFont] || fontMap.fraunces);
  }, [t.accent, t.theme, t.headlineFont, t.marqueeSpeed]);

  // Smooth scroll for #anchors
  useEffectA(() => {
    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) {
        e.preventDefault();
        el.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  // Reveal-on-scroll
  useEffectA(() => {
    const els = document.querySelectorAll("[data-reveal]");
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) {
          en.target.classList.add("revealed");
          io.unobserve(en.target);
        }
      });
    }, { threshold: 0.12 });
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <div className="page">
      {t.showCursor && <CustomCursor style={t.cursor} accent={t.accent} />}

      <Nav theme={t.theme || "light"} onToggleTheme={() => setTweak("theme", (t.theme === "dark" ? "light" : "dark"))} />

      <main>
        <Hero projects={PROJECTS} activeIdx={activeIdx} setActiveIdx={setActiveIdx} />
        <div className="scroll-cover">
          <div data-reveal><WorkList projects={PROJECTS} density={t.density} onOpen={setOpenProject} activeIdx={activeIdx} setActiveIdx={setActiveIdx} /></div>
          <div data-reveal><About /></div>
          <div data-reveal><Index rows={INDEX_ROWS} projects={PROJECTS} clients={CLIENTS} onOpen={setOpenProject} /></div>
          <Footer />
        </div>
      </main>

      <ProjectOverlay project={openProject} onClose={() => setOpenProject(null)} />

      <TweaksPanel title="Tweaks" defaultPosition={{ right: 24, bottom: 24 }}>
        <TweakSection label="Identity">
          <TweakColorRow label="Accent" value={t.accent} options={ACCENT_OPTIONS}
            onChange={(v) => setTweak("accent", v)} />
          <TweakColorRow label="Background" value={t.background} options={BG_OPTIONS}
            onChange={(v) => {
              const opt = BG_OPTIONS.find(o => o.value === v);
              setTweak({ background: v, ink: opt ? opt.ink : t.ink });
            }} />
        </TweakSection>

        <TweakSection label="Typography">
          <TweakSelect label="Headline font" value={t.headlineFont} options={FONT_OPTIONS}
            onChange={(v) => setTweak("headlineFont", v)} />
        </TweakSection>

        <TweakSection label="Layout & motion">
          <TweakRadio label="Project list density" value={t.density}
            options={[
              { label: "Comfortable", value: "comfortable" },
              { label: "Tight", value: "tight" },
              { label: "Roomy", value: "roomy" },
            ]}
            onChange={(v) => setTweak("density", v)} />
          <TweakRadio label="Cursor" value={t.cursor}
            options={[
              { label: "Dot", value: "dot" },
              { label: "Ring", value: "ring" },
            ]}
            onChange={(v) => setTweak("cursor", v)} />
          <TweakToggle label="Custom cursor on" value={t.showCursor}
            onChange={(v) => setTweak("showCursor", v)} />
          <TweakSlider label="Marquee speed (s)" value={t.marqueeSpeed} min={20} max={140} step={5}
            onChange={(v) => setTweak("marqueeSpeed", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function TweakColorRow({ label, value, options, onChange }) {
  return (
    <div className="tw-color-row">
      <div className="tw-color-label">{label}</div>
      <div className="tw-color-swatches">
        {options.map((o) => (
          <button
            key={o.value}
            className={`tw-swatch ${value === o.value ? "is-on" : ""}`}
            style={{ background: o.value }}
            onClick={() => onChange(o.value)}
            title={o.label}
          />
        ))}
      </div>
    </div>
  );
}

function Nav({ theme, onToggleTheme }) {
  const isDark = theme === "dark";
  return (
    <nav className="nav">
      <a className="nav-mark" href="#" data-cursor="link">
        <span className="mark-dot" />
        <span className="mark-text">Bernd&nbsp;Mantz</span>
      </a>
      <ul className="nav-list mono">
        <li><a href="#work" data-cursor="link">Work</a></li>
        <li><a href="#index" data-cursor="link">Index</a></li>
        <li><a href="/about" data-cursor="link">About</a></li>
        <li><a href="/journal" data-cursor="link">Journal</a></li>
      </ul>
      <div className="nav-right">
        <button
          className="theme-toggle"
          onClick={onToggleTheme}
          data-cursor="link"
          data-cursor-label={isDark ? "DAY" : "NIGHT"}
          aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}
          title={isDark ? "Switch to light" : "Switch to dark"}
        >
          {/* Aperture / iris icon — film-related, dezent */}
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden>
            <circle cx="12" cy="12" r="9.2" stroke="currentColor" strokeWidth="1.2" />
            {isDark ? (
              // Open aperture (light blades)
              <g stroke="currentColor" strokeWidth="1.2" strokeLinecap="round">
                <path d="M12 3 L12 12 L20 7" />
                <path d="M21 12 L12 12 L20 17" />
                <path d="M16 21 L12 12 L4 17" />
                <path d="M3 12 L12 12 L4 7" />
              </g>
            ) : (
              // Closed aperture (dark blades, half filled)
              <g>
                <path d="M12 3 L20 7 L12 12 Z" fill="currentColor" opacity="0.85" />
                <path d="M20 17 L12 12 L21 12 Z" fill="currentColor" opacity="0.55" />
                <path d="M4 17 L12 12 L16 21 Z" fill="currentColor" opacity="0.85" />
                <path d="M4 7 L12 12 L3 12 Z" fill="currentColor" opacity="0.55" />
              </g>
            )}
          </svg>
        </button>
        <a className="nav-cta mono" href="mailto:mail@berndmantz.com" data-cursor="link" data-cursor-label="EMAIL">
          <span className="dot-pulse" />
          Get in touch
        </a>
      </div>
    </nav>
  );
}

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