// ff-app.jsx — App shell, header, theme, strings, and Tweaks wiring

const { useState: __a_useState, useEffect: __a_useEffect, useMemo: __a_useMemo } = React;

function Header({ accent, s, lang, onLang }) {
  const [scrolled, setScrolled] = __a_useState(false);
  const [open, setOpen] = __a_useState(false);
  __a_useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const NAV = [
    { id: "services",     label: s.nav.services },
    { id: "subscription", label: s.nav.subscription },
    { id: "cases",        label: s.nav.cases },
    { id: "process",      label: s.nav.process },
    { id: "blog",         label: s.nav.blog },
    { id: "faq",          label: s.nav.faq },
  ];
  return (
    <header className={`header ${scrolled ? "scrolled" : ""}`}>
      <div className="header-inner">
        <a href="#top" className="logo">
          <BrandLogo height={16} />
        </a>
        <nav className="nav" aria-label="Primary">
          {NAV.map((n) => (
            <a key={n.id} href={`#${n.id}`}>{n.label}</a>
          ))}
        </nav>
        <div className="nav-cluster">
          <div className="lang-switch" role="group" aria-label="Language">
            <button type="button"
              className={`lang-btn ${lang === "en" ? "on" : ""}`}
              onClick={() => onLang("en")}
              aria-pressed={lang === "en"}>EN</button>
            <button type="button"
              className={`lang-btn ${lang === "pl" ? "on" : ""}`}
              onClick={() => onLang("pl")}
              aria-pressed={lang === "pl"}>PL</button>
          </div>
          <a href="#contact" className="btn btn-primary btn-sm">
            {s.nav.discuss} <span className="arrow">→</span>
          </a>
          <button type="button" className="burger" aria-label="Menu" aria-expanded={open} onClick={() => setOpen(true)}>
            <span /><span /><span />
          </button>
        </div>
      </div>
      {open && (
        <div className="mobile-menu" onClick={(e) => e.target === e.currentTarget && setOpen(false)}>
          <div className="mobile-menu-inner">
            <button type="button" className="mobile-close" onClick={() => setOpen(false)} aria-label="Close">×</button>
            <div className="lang-switch mobile-lang" role="group" aria-label="Language">
              <button type="button" className={`lang-btn ${lang === "en" ? "on" : ""}`} onClick={() => onLang("en")}>EN</button>
              <button type="button" className={`lang-btn ${lang === "pl" ? "on" : ""}`} onClick={() => onLang("pl")}>PL</button>
            </div>
            {NAV.map((n) => (
              <a key={n.id} href={`#${n.id}`} onClick={() => setOpen(false)}>{n.label}</a>
            ))}
            <a href="#contact" className="btn btn-primary btn-lg" onClick={() => setOpen(false)}>
              {s.nav.discuss} <span className="arrow">→</span>
            </a>
          </div>
        </div>
      )}
    </header>
  );
}

function StickyMobileCTA({ s }) {
  return (
    <a href="#contact" className="sticky-cta btn btn-primary btn-lg">
      {s.hero.ctaPrimary} <span className="arrow">→</span>
    </a>
  );
}

function Loader({ done }) {
  return (
    <div className={`loader ${done ? "hidden" : ""}`}>
      <div className="loader-mark">
        <LogoMark size={36} />
      </div>
    </div>
  );
}

// Solar Bold Duotone icons used in the welcome modal — picked to be distinct
// from icons used elsewhere on the page. Returned bare <svg> so they style via
// currentColor and the layout owns sizing.
const WELCOME_ICONS = {
  // Slide 1 — Transmission (what we do: wire the back office)
  transmission: (
    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path fill="currentColor" d="M2 4a2 2 0 1 1 2.75 1.855v5.395h6.5V5.855a2 2 0 1 1 1.5 0v5.395H16c.964 0 1.612-.002 2.095-.066c.461-.063.659-.17.789-.3s.237-.328.3-.79c.064-.482.066-1.13.066-2.094V5.855a2 2 0 1 1 1.5 0v2.197c0 .898 0 1.648-.08 2.242c-.084.628-.27 1.195-.726 1.65c-.455.456-1.022.642-1.65.726c-.594.08-1.343.08-2.242.08H12.75v5.395a2 2 0 1 1-1.5 0V12.75h-6.5v5.395a2 2 0 1 1-1.5 0V5.855A2 2 0 0 1 2 4" />
      <path fill="currentColor" fillRule="evenodd" d="M17.25 15a.75.75 0 0 1 .75-.75h2.286c1.375 0 2.464 1.134 2.464 2.5a2.5 2.5 0 0 1-1.641 2.358l1.53 2.5a.75.75 0 1 1-1.279.784l-1.923-3.142h-.687V22a.75.75 0 0 1-1.5 0zm1.5 2.75h1.536c.518 0 .964-.433.964-1s-.446-1-.964-1H18.75z" clipRule="evenodd" opacity=".5" />
    </svg>
  ),
  // Slide 2 — Box (how it lands: shipped in slices)
  box: (
    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <path fill="currentColor" d="M8.422 20.618C10.178 21.54 11.056 22 12 22V12L2.638 7.073l-.04.067C2 8.154 2 9.417 2 11.942v.117c0 2.524 0 3.787.597 4.801c.598 1.015 1.674 1.58 3.825 2.709z" />
      <path fill="currentColor" d="m17.577 4.432l-2-1.05C13.822 2.461 12.944 2 12 2c-.945 0-1.822.46-3.578 1.382l-2 1.05C4.318 5.536 3.242 6.1 2.638 7.072L12 12l9.362-4.927c-.606-.973-1.68-1.537-3.785-2.641" opacity=".7" />
      <path fill="currentColor" d="m21.403 7.14l-.041-.067L12 12v10c.944 0 1.822-.46 3.578-1.382l2-1.05c2.151-1.129 3.227-1.693 3.825-2.708c.597-1.014.597-2.277.597-4.8v-.117c0-2.525 0-3.788-.597-4.802" opacity=".5" />
      <path fill="currentColor" d="m6.323 4.484l.1-.052l1.493-.784l9.1 5.005l4.025-2.011q.205.232.362.498c.15.254.262.524.346.825L17.75 9.964V13a.75.75 0 0 1-1.5 0v-2.286l-3.5 1.75v9.44A3 3 0 0 1 12 22c-.248 0-.493-.032-.75-.096v-9.44l-8.998-4.5c.084-.3.196-.57.346-.824q.156-.266.362-.498l9.04 4.52l3.387-1.693z" />
    </svg>
  ),
  // Slide 3 — Hand Shake (how we work: retainer, direct chat)
  handshake: (
    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
      <g fill="currentColor" fillRule="evenodd" clipRule="evenodd">
        <path d="M11.19 3.308c-.213-.367-.837-.59-1.47-.227c-.632.36-.743.997-.533 1.357l2.526 4.331a.75.75 0 0 1-1.296.756L7.049 3.75c-.214-.367-.838-.59-1.471-.227c-.632.36-.743.997-.532 1.357l3.788 6.497a.75.75 0 0 1-1.296.756L5.855 9.245c-.214-.367-.838-.59-1.472-.227c-.631.36-.742.996-.532 1.357l3.789 6.497c1.608 2.759 5.579 3.654 8.946 1.73c3.365-1.923 4.56-5.764 2.955-8.517l-2.525-4.331c-.214-.367-.838-.59-1.472-.228c-.631.361-.742.997-.532 1.358l1.684 2.887a.75.75 0 0 1-.276 1.03c-1.542.88-2.015 2.585-1.34 3.743a.75.75 0 1 1-1.296.756c-.912-1.565-.543-3.45.635-4.782c.33-.372.443-.914.192-1.344z" />
        <path d="M4.413 17.859a.75.75 0 0 1 1.026.27c.827 1.418 2.091 2.49 3.65 3.186a.75.75 0 0 1-.611 1.37c-1.812-.809-3.332-2.08-4.335-3.8a.75.75 0 0 1 .27-1.026M18.905 3.922c-1.014-1.036-2.46-1.417-3.875-1.015a.75.75 0 1 1-.41-1.442c1.938-.552 3.954-.025 5.357 1.408a.75.75 0 1 1-1.072 1.049" opacity=".5" />
      </g>
    </svg>
  ),
};

function WelcomeModal({ s, lang, onLang }) {
  const w = s.welcome || {};
  const slides = Array.isArray(w.slides) ? w.slides : [];
  const total = slides.length;
  const [open, setOpen] = __a_useState(false);
  const [idx, setIdx] = __a_useState(0);
  // -1 = entering from left (prev), 1 = entering from right (next), 0 = first
  const [dir, setDir] = __a_useState(0);
  // Auto-advance until user interacts (any nav action stops it).
  const [auto, setAuto] = __a_useState(true);

  // DEV: open on every reload — localStorage gate disabled.
  __a_useEffect(() => {
    if (!total) return;
    const id = setTimeout(() => setOpen(true), 700);
    return () => clearTimeout(id);
  }, [total]);

  // Auto-advance every 5s while open + auto && not on the last slide.
  __a_useEffect(() => {
    if (!open || !auto || total < 2) return;
    if (idx >= total - 1) return;
    const id = setTimeout(() => {
      setDir(1);
      setIdx((v) => v + 1);
    }, 5000);
    return () => clearTimeout(id);
  }, [open, auto, idx, total]);

  const dismiss = () => {
    setOpen(false);
  };

  const goNext = () => {
    setAuto(false);
    if (idx < total - 1) { setDir(1); setIdx(idx + 1); }
  };
  const goPrev = () => {
    setAuto(false);
    if (idx > 0) { setDir(-1); setIdx(idx - 1); }
  };
  const goTo = (i) => {
    setAuto(false);
    if (i === idx) return;
    setDir(i > idx ? 1 : -1);
    setIdx(i);
  };

  const isLast = idx === total - 1;

  // CTA path: dismiss + scroll to #contact.
  const onCta = () => {
    dismiss();
    // Defer to next tick so the modal exit doesn't fight the scroll.
    setTimeout(() => {
      const el = document.getElementById("contact");
      if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      else window.location.hash = "#contact";
    }, 0);
  };

  // Body scroll lock while open.
  __a_useEffect(() => {
    if (!open) return;
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => { document.body.style.overflow = prev; };
  }, [open]);

  // Esc + arrow keys.
  __a_useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === "Escape") { e.preventDefault(); dismiss(); }
      else if (e.key === "ArrowRight") { e.preventDefault(); goNext(); }
      else if (e.key === "ArrowLeft")  { e.preventDefault(); goPrev(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, idx, total]);

  // Move focus into the modal on open so keyboard users get the right context.
  const cardRef = React.useRef(null);
  __a_useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => {
      const node = cardRef.current;
      if (!node) return;
      const focusable = node.querySelector("[data-welcome-focus]") || node;
      try { focusable.focus({ preventScroll: true }); } catch (e) { focusable.focus(); }
    }, 30);
    return () => clearTimeout(t);
  }, [open]);

  if (!open || !total) return null;

  const slide = slides[idx] || {};
  const ctaLabel = (w.cta && w.cta.length) ? w.cta : (s.hero && s.hero.ctaPrimary) || "Get a free audit";

  return (
    <div
      className="welcome-overlay"
      onClick={(e) => { if (e.target === e.currentTarget) dismiss(); }}
      aria-hidden="false"
    >
      <div
        className="welcome-card"
        role="dialog"
        aria-modal="true"
        aria-labelledby="welcome-title"
        aria-describedby="welcome-desc"
        ref={cardRef}
        tabIndex={-1}
      >
        <button type="button" className="welcome-close" onClick={dismiss} aria-label={w.skip || "Close"}>
          <svg viewBox="0 0 14 14" aria-hidden="true">
            <path d="M3 3 L11 11 M11 3 L3 11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" fill="none" />
          </svg>
        </button>

        <div className="welcome-stage" aria-live="polite">
          <div
            key={idx}
            className={`welcome-slide welcome-slide-dir-${dir > 0 ? "next" : dir < 0 ? "prev" : "none"}`}
          >
            <div className="welcome-visual" aria-hidden="true">
              <img
                className="welcome-visual-img"
                src={slide.image}
                alt=""
                loading="eager"
                onError={(e) => { e.currentTarget.style.opacity = "0"; }}
              />
            </div>
            <div className="welcome-text">
              <div className="welcome-text-head">
                <div className="welcome-brand"><BrandLogo height={18} /></div>
                {onLang && (
                  <div className="welcome-lang" role="group" aria-label="Language">
                    <button type="button"
                      className={`welcome-lang-btn ${lang === "en" ? "on" : ""}`}
                      onClick={() => onLang("en")}
                      aria-pressed={lang === "en"}>EN</button>
                    <button type="button"
                      className={`welcome-lang-btn ${lang === "pl" ? "on" : ""}`}
                      onClick={() => onLang("pl")}
                      aria-pressed={lang === "pl"}>PL</button>
                  </div>
                )}
              </div>
              <h2 id="welcome-title" className="welcome-h">{slide.title}</h2>
              <p id="welcome-desc" className="welcome-desc">{slide.desc}</p>

              <div className="welcome-foot">
                <div className="welcome-dots" role="tablist" aria-label="Slide">
                  {slides.map((_, i) => (
                    <button
                      key={i}
                      type="button"
                      role="tab"
                      aria-selected={i === idx}
                      aria-label={`Slide ${i + 1}`}
                      className={`welcome-dot ${i === idx ? "on" : ""}`}
                      onClick={() => goTo(i)}
                    />
                  ))}
                </div>
                <div className="welcome-actions">
                  <button
                    type="button"
                    className="welcome-arrow"
                    onClick={goPrev}
                    disabled={idx === 0}
                    aria-label={w.prev || "Previous"}
                  >
                    <svg viewBox="0 0 14 14" aria-hidden="true">
                      <path d="M9 2 L4 7 L9 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" fill="none" />
                    </svg>
                  </button>
                  {isLast ? (
                    <button
                      type="button"
                      className="btn btn-primary btn-sm welcome-cta"
                      onClick={onCta}
                      data-welcome-focus
                    >
                      {ctaLabel}
                      <svg className="welcome-btn-arrow" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                        <path fill="currentColor" opacity=".5" fillRule="evenodd" clipRule="evenodd" d="M3.25 12a.75.75 0 0 1 .75-.75h9.25v1.5H4a.75.75 0 0 1-.75-.75" />
                        <path fill="currentColor" d="M13.25 12.75V18a.75.75 0 0 0 1.28.53l6-6a.75.75 0 0 0 0-1.06l-6-6a.75.75 0 0 0-1.28.53z" />
                      </svg>
                    </button>
                  ) : (
                    <button
                      type="button"
                      className="btn btn-ghost btn-sm welcome-next"
                      onClick={goNext}
                      data-welcome-focus
                    >
                      {w.next || "Next"}
                      <svg className="welcome-btn-arrow" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                        <path fill="currentColor" opacity=".5" fillRule="evenodd" clipRule="evenodd" d="M3.25 12a.75.75 0 0 1 .75-.75h9.25v1.5H4a.75.75 0 0 1-.75-.75" />
                        <path fill="currentColor" d="M13.25 12.75V18a.75.75 0 0 0 1.28.53l6-6a.75.75 0 0 0 0-1.06l-6-6a.75.75 0 0 0-1.28.53z" />
                      </svg>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const [ready, setReady] = __a_useState(false);
  const s = useStrings(t.lang);

  __a_useEffect(() => {
    const id = setTimeout(() => setReady(true), 500);
    return () => clearTimeout(id);
  }, []);

  __a_useEffect(() => {
    const root = document.documentElement;
    root.setAttribute("data-theme", t.dark ? "dark" : "light");
    root.setAttribute("lang", t.lang);
    const pair = FONT_PAIRS[t.fontPair] || FONT_PAIRS.geist;
    root.style.setProperty("--font-sans", `${pair.sans}, ui-sans-serif, system-ui, sans-serif`);
    root.style.setProperty("--font-mono", `${pair.sans}, ui-sans-serif, system-ui, sans-serif`);
    root.style.setProperty("--accent", t.accent);
  }, [t.dark, t.fontPair, t.accent, t.lang]);

  return (
    <>
      <Loader done={ready} />
      <Header accent={t.accent} s={s} lang={t.lang} onLang={(v) => setTweak("lang", v)} />
      <main>
        <Hero variant={t.heroVariant} accent={t.accent} s={s} />
        <Services variant={t.servicesVariant} s={s} />
        <Subscription variant={t.subscriptionVariant} s={s} />
        <Cases s={s} />
        <Process variant={t.processVariant} s={s} />
        <Blog s={s} />
        <Testimonials s={s} />
        <FAQ s={s} />
        <Contact s={s} />
      </main>
      <Footer s={s} />
      <StickyMobileCTA s={s} />
      <WelcomeModal s={s} lang={t.lang} onLang={(v) => setTweak("lang", v)} />

      <TweaksPanel>
        <TweakSection label="Theme" />
        <TweakToggle label="Dark mode" value={t.dark}
          onChange={(v) => setTweak("dark", v)} />
        <TweakColor label="Accent"
          value={t.accent}
          options={["#3b82f6", "#a3e635", "#f97316", "#e11d48", "#22d3ee", "#a78bfa"]}
          onChange={(v) => setTweak("accent", v)} />
        <TweakSelect label="Font"
          value={t.fontPair}
          options={[
            { value: "geist", label: "Geist" },
            { value: "manrope", label: "Manrope" },
            { value: "inter", label: "Inter Tight" },
            { value: "space", label: "Space Grotesk" },
          ]}
          onChange={(v) => setTweak("fontPair", v)}
        />

        <TweakSection label="Section variants" />
        <TweakRadio label="Hero"
          value={t.heroVariant}
          options={[
            { value: "flow",  label: "Centered" },
            { value: "split", label: "Split + diagram" },
          ]}
          onChange={(v) => setTweak("heroVariant", v)} />
        <TweakRadio label="Services"
          value={t.servicesVariant}
          options={[
            { value: "cards", label: "Cards" },
            { value: "list",  label: "List rows" },
          ]}
          onChange={(v) => setTweak("servicesVariant", v)} />
        <TweakRadio label="Subscription"
          value={t.subscriptionVariant}
          options={[
            { value: "anchor",    label: "Anchor plate" },
            { value: "editorial", label: "Editorial" },
          ]}
          onChange={(v) => setTweak("subscriptionVariant", v)} />
        <TweakRadio label="Process"
          value={t.processVariant}
          options={[
            { value: "diagonal", label: "Diagonal" },
            { value: "timeline", label: "Timeline" },
          ]}
          onChange={(v) => setTweak("processVariant", v)} />
      </TweaksPanel>
    </>
  );
}

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