// App shell — hash router + data subscription. Waits for content/*.json to
// load via initArtifexData() before the first render; a small loader fills
// the viewport while the fetch is in flight so nothing flickers.

// Yandex.Metrika counter id (kept in sync with the snippet in index.html).
const YM_COUNTER_ID = 105446592;

function App() {
  const route = useRoute();
  useLang();
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);

  React.useEffect(() => {
    const handler = () => forceUpdate();
    window.addEventListener("artifex:data", handler);
    return () => window.removeEventListener("artifex:data", handler);
  }, []);

  // Hash-router → Yandex.Metrika virtual page-views. The `init` call in
  // index.html already counts the first page; on every subsequent route
  // change we fire `hit` with the new URL + title + previous URL as referrer.
  React.useEffect(() => {
    if (typeof window === "undefined" || typeof window.ym !== "function") return;
    if (!window.__artifexYmReady) { window.__artifexYmReady = true; return; }
    try {
      window.ym(YM_COUNTER_ID, "hit", window.location.href, {
        title: document.title,
        referer: window.__artifexLastUrl || document.referrer || ""
      });
    } catch (e) { /* never let metrika break the app */ }
    window.__artifexLastUrl = window.location.href;
  }, [route]);

  let page;
  if (route === "/" || route === "") page = <HomePage/>;
  else if (route === "/catalog") page = <CatalogPage/>;
  else if (route.startsWith("/product/")) page = <ProductPage slug={route.replace("/product/", "")}/>;
  else if (route === "/applications") page = <ApplicationsPage/>;
  else if (route === "/objects") page = <ObjectsPage/>;
  else if (route.startsWith("/object/")) page = <ObjectDetailPage slug={route.replace("/object/", "")}/>;
  else if (route === "/insights" || route.startsWith("/insights?")) page = <InsightsPage/>;
  else if (route.startsWith("/insights/")) page = <InsightDetailPage slug={route.replace("/insights/", "").split("?")[0]}/>;
  else if (route === "/about") page = <AboutPage/>;
  else if (route === "/advantages") page = <AdvantagesPage/>;
  else if (route === "/production") page = <ProductionPage/>;
  else if (route === "/partnership") page = <PartnershipPage/>;
  else if (route === "/contacts") page = <ContactsPage/>;
  else if (route === "/quote") page = <QuotePage/>;
  else page = (
    <main className="page-404">
      <h1>{t("notFound.title")}</h1>
      <Link to="/" className="btn btn-primary">{t("notFound.home")}</Link>
    </main>
  );

  return (
    <>
      <Nav current={route}/>
      {page}
      <Footer/>
      <FloatingQuoteBtn route={route}/>
    </>
  );
}

function BootError({ error }) {
  return (
    <main style={{
      minHeight: "80vh", display: "flex", alignItems: "center",
      justifyContent: "center", padding: "40px", textAlign: "center"
    }}>
      <div style={{ maxWidth: 560 }}>
        <h1 style={{ fontFamily: "'DM Serif Display', serif", fontSize: 32, marginBottom: 12 }}>
          Не удалось загрузить контент
        </h1>
        <p style={{ color: "var(--ink-2)", marginBottom: 20 }}>
          Файлы в <code>/content/</code> недоступны. Проверьте деплой и обновите страницу.
        </p>
        <pre style={{
          textAlign: "left", background: "var(--cream)", padding: 12,
          borderRadius: 8, fontSize: 12, color: "var(--ink-2)",
          overflow: "auto", maxHeight: 160
        }}>{String(error && error.message || error)}</pre>
      </div>
    </main>
  );
}

const _root = ReactDOM.createRoot(document.getElementById("root"));
_root.render(
  <div className="artifex-preloader" role="status" aria-live="polite" aria-label="Загрузка">
    <div className="artifex-preloader-bg" aria-hidden="true">
      <span className="ap-blob ap-blob-1"/>
      <span className="ap-blob ap-blob-2"/>
      <span className="ap-blob ap-blob-3"/>
    </div>
    <div className="artifex-preloader-content">
      <svg
        className="ap-orb"
        viewBox="0 0 160 160"
        width="180" height="180"
        aria-hidden="true"
      >
        <defs>
          <radialGradient id="apOrbGold" cx="38%" cy="32%" r="70%">
            <stop offset="0%" stopColor="#f7e8c2"/>
            <stop offset="35%" stopColor="#e6c17a"/>
            <stop offset="70%" stopColor="#c89a4a"/>
            <stop offset="100%" stopColor="#5a3f15"/>
          </radialGradient>
          <linearGradient id="apOrbRing" x1="0" y1="0" x2="1" y2="1">
            <stop offset="0%" stopColor="#c89a4a" stopOpacity="0"/>
            <stop offset="40%" stopColor="#f4d489" stopOpacity="1"/>
            <stop offset="60%" stopColor="#ffffff" stopOpacity="1"/>
            <stop offset="100%" stopColor="#8a6420" stopOpacity="0"/>
          </linearGradient>
          <radialGradient id="apOrbHalo" cx="50%" cy="50%" r="50%">
            <stop offset="55%" stopColor="#c89a4a" stopOpacity="0"/>
            <stop offset="80%" stopColor="#c89a4a" stopOpacity="0.18"/>
            <stop offset="100%" stopColor="#c89a4a" stopOpacity="0"/>
          </radialGradient>
        </defs>

        {/* outer halo */}
        <circle className="ap-halo" cx="80" cy="80" r="78" fill="url(#apOrbHalo)"/>

        {/* tracing arc — rotates around the orb */}
        <g className="ap-orb-ring">
          <circle
            cx="80" cy="80" r="72"
            fill="none"
            stroke="url(#apOrbRing)"
            strokeWidth="2"
            strokeLinecap="round"
            strokeDasharray="120 320"
          />
        </g>

        {/* breathing sphere */}
        <g className="ap-orb-sphere">
          <circle cx="80" cy="80" r="60" fill="url(#apOrbGold)"/>
          {/* dome dots — pulse in sequence */}
          <circle className="ap-dot ap-dot-1" cx="55" cy="55" r="7"  fill="#1a1612"/>
          <circle className="ap-dot ap-dot-2" cx="105" cy="50" r="6" fill="#1a1612"/>
          <circle className="ap-dot ap-dot-3" cx="113" cy="92" r="7" fill="#1a1612"/>
          <circle className="ap-dot ap-dot-4" cx="62" cy="108" r="6" fill="#1a1612"/>
          <circle className="ap-dot ap-dot-5" cx="86" cy="80" r="5"  fill="#1a1612"/>
        </g>
      </svg>

      <div className="ap-bar" aria-hidden="true">
        <div className="ap-bar-fill"/>
      </div>
    </div>
  </div>
);

initArtifexData()
  .then(() => { _root.render(<App/>); })
  .catch(err => {
    console.error("[artifex] content load failed:", err);
    _root.render(<BootError error={err}/>);
  });
