/* =============================================================
   Section 02 (the service explorer, "Supersøk") — the small part
   that is always loaded. The explorer itself (supersok.jsx and the
   demos in teknisk-design.jsx) is the heaviest code on the page, so
   it is fetched and compiled only when the visitor presses
   «Utforsk», or when Jens or the system catalogue asks for it.
   Until then a splash shows a blurred glimpse of the window behind
   glass, in the soft blue/beige of the hero.
   ============================================================= */

/* Section heading, shared with supersok.jsx so the text never changes when the explorer swaps in */
const SUPERSOK_HEAD = {
  slash: "/ 02 — tjenester",
  title: "Hva kan vi hjelpe dere med?",
  intro: "Vi er systemuavhengige. Søk i over 100+ systemer, teknologier og integrasjoner vi kan jobbe med, og utforsk hvordan vi kan bygge, koble eller optimalisere den digitale hverdagen til din organisasjon eller bedrift.",
};

const SUPERSOK_SPLASH = {
  kicker: "Tjenesteutforskeren",
  title: "Klikk deg rundt i det vi leverer",
  text: "Se tjenestespekteret vårt som levende demoer – webapplikasjoner, booking, kundeportaler, KI-agenter og mer – i flere designvarianter. Du kan også søke blant integrasjoner, automasjoner, moduler og flere andre systemer vi leverer.",
  points: ["Levende demoer", "Flere designvarianter", "Søk i 100+ systemer"],
  cta: "Utforsk",
  opening: "Åpner utforskeren …",
  retry: "Fikk ikke åpnet – prøv igjen",
  /* The blurred window behind the glass */
  folders: ["Alle tjenester", "Nettsider og apper", "Netthandel og salg", "Data og drift", "Sikkerhet", "Kunstig intelligens", "Opplæring"],
  blocks: ["Integrasjoner", "Automasjoner", "Moduler", "Systemer"],
  panes: ["Tjenester", "Byggeklosser"],
  tiles: [["Webapplikasjon", "#DCE3E6"], ["Integrasjoner", "#F0E5DC"], ["Online booking", "#E3E8E2"], ["Kundeportal", "#EADBCF"], ["Landingsside", "#DDE2E9"], ["Dashboard", "#EFE8DA"]],
};

/* In the order they must run: supersok.jsx builds on the catalogue and demos in teknisk-design.jsx */
const SUPERSOK_FILES = ["teknisk-design.jsx", "supersok.jsx"];

/* The window behind the glass: the real explorer's frame classes (same size and look), simple content */
function SuperSokGhost() {
  const T = SUPERSOK_SPLASH;
  return (
    <div className="sl-ws sl-sss__win">
      <div className="sl-ws__bar">
        <span className="sl-ws__dots"><i></i><i></i><i></i></span>
        <span className="sl-sss__pill"></span>
        <span className="sl-sss__search"></span>
      </div>
      <div className="sl-ws__body sl-lib">
        <nav className="sl-lib__side">
          <span className="sl-ws__paneltitle">{T.panes[0]}</span>
          {T.folders.map((f, i) => <span key={f} className={"sl-lib__folder" + (i === 0 ? " is-on" : "")}>{f}</span>)}
          <span className="sl-ws__paneltitle sl-ss__sidetitle">{T.panes[1]}</span>
          {T.blocks.map(f => <span key={f} className="sl-lib__folder">{f}</span>)}
        </nav>
        <div className="sl-lib__main">
          <div className="sl-lib__head"><b>{T.folders[0]}</b></div>
          <div className="sl-sss__grid">
            {T.tiles.map(([name, tint]) => (
              <span key={name} className="sl-sss__tile">
                <span className="sl-sss__thumb" style={{ background: tint }}><i></i><i></i><i></i></span>
                <b>{name}</b><em></em><em></em>
              </span>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function SuperSokGate() {
  const T = SUPERSOK_SPLASH;
  /* idle -> loading -> revealing -> open (or failed, which lets the visitor try again) */
  const [phase, setPhase] = useState(() => (typeof SuperSok === "function" ? "open" : "idle"));
  const phaseRef = useRef(phase); phaseRef.current = phase;
  const queued = useRef([]);
  /* waitMs: let a scroll to the section finish first, so compiling does not make it stutter */
  const open = (waitMs = 0) => {
    if (phaseRef.current !== "idle" && phaseRef.current !== "failed") return;
    const t0 = performance.now();
    setPhase("loading");
    new Promise(res => setTimeout(res, waitMs)).then(() => slLoad(SUPERSOK_FILES))
      .then(() => setTimeout(() => setPhase("revealing"), Math.max(0, 500 - (performance.now() - t0))))
      .catch((e) => { console.error("[lazy-load]", e); setPhase("failed"); });
  };
  /* Go to the explorer right away (it may be far down the page), and show it loading there */
  const goThere = () => {
    const stage = document.querySelector("#design .sl-td__stage");
    if (!stage) return 0;
    const r = stage.getBoundingClientRect();
    if (r.top >= 0 && r.bottom <= window.innerHeight) return 0;
    if (window.scrollToCenter) window.scrollToCenter(stage); else stage.scrollIntoView({ behavior: "smooth", block: "center" });
    return 650;
  };
  const warm = () => slPrefetch(SUPERSOK_FILES);

  /* Jens, the system catalogue and deep links (#integrasjoner) open services, systems and folders with events. Before the explorer exists,
     catch them, open it, and pass them on once it listens. */
  useEffect(() => {
    if (phase === "open") return;
    const hold = (e) => {
      queued.current.push([e.type, e.detail]);
      if (phaseRef.current === "idle" || phaseRef.current === "failed") open(goThere());
    };
    window.addEventListener("sl:open-service", hold);
    window.addEventListener("sl:open-tool", hold);
    window.addEventListener("sl:open-folder", hold);
    return () => { window.removeEventListener("sl:open-service", hold); window.removeEventListener("sl:open-tool", hold); window.removeEventListener("sl:open-folder", hold); };
  }, [phase]);
  useEffect(() => {
    if (phase === "revealing") { const t = setTimeout(() => setPhase("open"), 420); return () => clearTimeout(t); }
    if (phase !== "open") return;
    /* The window fades in where the splash was (styles under .sl-sss in no.css) */
    document.documentElement.classList.add("sl-sss-opened");
    const t = setTimeout(() => document.documentElement.classList.remove("sl-sss-opened"), 1200);
    const q = queued.current.splice(0);
    if (q.length) setTimeout(() => q.forEach(([type, detail]) => window.dispatchEvent(new CustomEvent(type, { detail }))), 60);
    return () => clearTimeout(t);
  }, [phase]);

  /* On phones the service list and the library folders are rows you swipe (no.css). Keep the chosen one in
     view, also when Jens or the catalogue picks it, by following the .is-on class. */
  useEffect(() => {
    if (phase !== "open") return;
    const root = document.getElementById("design");
    if (!root) return;
    let queuedFrame = 0;
    const follow = () => {
      queuedFrame = 0;
      root.querySelectorAll(".sl-ws__pages, .sl-lib__side").forEach((row) => {
        if (row.scrollWidth <= row.clientWidth + 4) return;
        const on = row.querySelector(".is-on");
        if (!on) return;
        const r = row.getBoundingClientRect(), c = on.getBoundingClientRect();
        if (c.left >= r.left && c.right <= r.right) return;
        row.scrollTo({ left: row.scrollLeft + (c.left - r.left) - (r.width - c.width) / 2, behavior: "smooth" });
      });
    };
    const mo = new MutationObserver(() => { if (!queuedFrame) queuedFrame = requestAnimationFrame(follow); });
    mo.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: ["class"] });
    follow();
    return () => { mo.disconnect(); cancelAnimationFrame(queuedFrame); };
  }, [phase]);

  if (phase === "open") return <SuperSok/>;
  const busy = phase === "loading" || phase === "revealing";
  return (
    <section className={"sl-section sl-td sl-sss is-" + phase} id="design">
      <div className="shell">
        <div className="sl-slash" style={{ marginBottom: 24 }}>{SUPERSOK_HEAD.slash}</div>
        <div className="sl-section__head">
          <h2 className="sl-section__title">{SUPERSOK_HEAD.title}</h2>
          <p className="sl-section__intro">{SUPERSOK_HEAD.intro}</p>
        </div>
        <div className="sl-td__stage">
          <div className="sl-sss__ghost" aria-hidden="true" onClick={() => open()}><SuperSokGhost/></div>
          <div className="sl-sss__mesh" aria-hidden="true"></div>
          <div className="sl-sss__glass">
            <span className="sl-sss__kicker">{T.kicker}</span>
            <h3 className="sl-sss__title">{T.title}</h3>
            <p className="sl-sss__text">{T.text}</p>
            <ul className="sl-sss__points">{T.points.map(p => <li key={p}>{p}</li>)}</ul>
            <button className="sl-btn sl-btn--primary sl-sss__go" onClick={() => open()} onPointerEnter={warm} onFocus={warm} disabled={busy} aria-busy={busy}>
              {busy ? T.opening : phase === "failed" ? T.retry : T.cta}
              {!busy && <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
            </button>
            <span className="sl-sss__line" aria-hidden="true"><i></i></span>
          </div>
        </div>
      </div>
    </section>
  );
}
