import { createRoot } from "react-dom/client";
import { supabase } from "@/integrations/supabase/client";
import App from "./App.tsx";
// THE THEME LAYER (FILE 48 · «ДУ РӮШНОӢ» · Block A). Wrapped here rather than
// inside App so the app root keeps its shape and stays free of the import —
// App.tsx is the entry chunk and is allowlisted in scripts/audit/palette.mjs
// precisely because what it imports is measured in first-paint bytes. The
// provider renders no markup and reads no colour; it holds the current theme
// and keeps `data-theme` on <html> equal to it. index.html has already stamped
// that attribute before this file was fetched, so this mounts into a document
// that is already in the right theme.
import { ThemeProvider } from "@/lib/theme/ThemeProvider";
import "./index.css";

// ── Third-party analytics (web + Telegram only) ───────────
// GA4 / Meta Pixel / Clarity used to be inline <script> tags in index.html,
// which meant they also ran inside the packaged iOS and Android WebViews that
// load the very same document. They now live in a platform-gated module which
// decides, at runtime, whether this surface may have them at all — on iOS and
// Android it injects nothing.
//
// The import is DYNAMIC because marketing tags are not on the learner's
// critical path: this keeps them out of the entry chunk and off the first
// paint. The gate deliberately stays INSIDE the module rather than wrapping
// this call — the packaged app carries every chunk on disk regardless, so
// skipping the import would buy nothing on native while splitting one guard
// across two files.
//
// Never throws; a failed chunk load costs a funnel data point and nothing else.
void import("@/lib/analytics/webAnalytics")
  .then(({ initWebAnalytics }) => initWebAnalytics())
  .catch(() => { /* analytics is the least important thing on the page */ });

// ── Навомӯз phone-video gesture enhancer (lazy, non-blocking) ───────────────
// The shared player already exposes visible ±10 buttons on every surface. A
// tiny course-scoped enhancer adds the familiar double-tap ±10 gesture on
// Android/iOS/plain web while deliberately leaving Telegram on visible buttons
// only, where WebView gesture arbitration varies. Keeping this dynamic means a
// player convenience never delays the app's first paint.
void import("@/lib/media/navomuzVideoGestures")
  .then(({ installNavomuzVideoGestures }) => installNavomuzVideoGestures())
  .catch(() => { /* visible transport remains the complete fallback */ });

// ── /welcome conversion attribution (lazy, route-gated) ─────────────────────
// The public acquisition page needs more than a PageView: it needs to know
// which source produced a platform choice, APK/add-to-home intent, Telegram/Web
// launch, and ultimately an app entry. The heavier first-party telemetry stays
// out of the entry chunk and is loaded only on /welcome, or on an app entry that
// already carries stored /welcome attribution from the same browser.
try {
  const path = window.location.pathname;
  const isWelcome = /^\/welcome\/?$/.test(path);
  const isAppEntry = path === "/" || path === "/app" || path.startsWith("/app/");
  const hasAttribution = isAppEntry && Boolean(localStorage.getItem("cs_marketing_attribution_v1"));
  if (isWelcome || hasAttribution) {
    void import("@/lib/analytics/welcomeFunnel")
      .then(({ initWelcomeFunnel, initAttributedAppEntry }) => {
        if (isWelcome) initWelcomeFunnel();
        else initAttributedAppEntry();
      })
      .catch(() => { /* attribution must never delay or break the product */ });
  }
} catch {
  // Storage can be unavailable in hardened browsers. The site still works.
}

// ── Official public identity / SEO (lazy, non-blocking) ──────────────────────
// The Vite SPA serves one HTML shell for /welcome, the app and the public legal
// pages. Give each route its own canonical/title/description/indexing policy and
// structured identity after the bundle arrives, while keeping it off first
// paint. The static OG card in index.html remains the no-JS/social fallback.
void import("@/lib/seo/officialIdentity")
  .then(({ installOfficialSeoIdentity }) => installOfficialSeoIdentity())
  .catch(() => { /* metadata can never be allowed to break the product */ });

// ── Startup diagnostics (development only) ───────────────
// Production must never print authentication material (Telegram initData),
// tokens, or personal identifiers to the console. All startup diagnostics are
// therefore gated behind import.meta.env.DEV and never echo initData.
if (import.meta.env.DEV) {
  const log = (tag: string, msg: string, ok = true) =>
    console.log(`%c[${tag}] ${ok ? "✓" : "✗"} ${msg}`, `color: ${ok ? "#4ade80" : "#f87171"}; font-weight: bold;`);

  console.log("%c═══ CHAIKA SPEAK — Mini App Starting ═══", "color: #60a5fa; font-weight: bold; font-size: 14px;");

  const sbUrl = import.meta.env.VITE_SUPABASE_URL || "(local fallback)";
  log("SUPABASE", `URL: ${sbUrl}`);
  // Probe a public content table — users/subscriptions are service-role-only now.
  supabase.from("all-topic-photos").select("*", { count: "exact", head: true }).then(({ count, error }) => {
    if (error) log("SUPABASE", `Connection FAILED: ${error.message}`, false);
    else log("SUPABASE", `Connected — vocab topics: ${count ?? 0} rows`);
  });

  const tg = (window as any).Telegram?.WebApp;
  if (tg) {
    // initDataUnsafe is not trusted for auth and initData is never logged.
    log("TELEGRAM", `WebApp detected (present: ${tg.initData ? "yes" : "no"})`);
  } else {
    log("TELEGRAM", "Not inside Telegram — running in browser mode", false);
  }

  log("ENV", `VITE_SUPABASE_URL: ${import.meta.env.VITE_SUPABASE_URL ? "set" : "MISSING (using fallback)"}`);
  log("ENV", `VITE_SUPABASE_PUBLISHABLE_KEY: ${import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY ? "set" : "MISSING (using fallback)"}`);
}

// ── Render ────────────────────────────────────────────────
createRoot(document.getElementById("root")!).render(
  <ThemeProvider>
    <App />
  </ThemeProvider>,
);