// app.jsx — PRODUCTION build for alsakkah.app
// Locked-in design choices; Supabase remote config; ?tweaks=1 reveals panel.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "vibe": "sport",
  "heroVariant": "device",
  "accent": "#e5a82c",
  "bg": "#0d1611",
  "pendingLine": "#6b6b6b",
  "motion": 5,
  "showSuitDeco": true
}/*EDITMODE-END*/;

// ─── Supabase remote config ───────────────────────────────────────
// Pulls dynamic values (App Store ID, social handles, etc) from the
// app_config table so they can be updated without a redeploy.
const SUPABASE_URL = "https://jjterwogbnlkvrwmpzxp.supabase.co";
const SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpqdGVyd29nYm5sa3Zyd21wenhwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzcwMjM2NzAsImV4cCI6MjA5MjU5OTY3MH0.HmgaM3e2HfW6tAtxn76tAsvSNviSM3a2Ndr3-pJrnG4";

// Fallbacks used until Supabase data loads (or if fetch fails).
const CONFIG_FALLBACK = {
  ios_app_id: "",          // e.g. "6712345678" → https://apps.apple.com/app/id6712345678
  android_app_id: "",      // e.g. "com.alsakkah.app" → https://play.google.com/store/apps/details?id=...
  x_account_id: "",        // e.g. "AlSakkah" → https://x.com/AlSakkah
  tiktok_account_id: "",   // e.g. "alsakkah" → https://www.tiktok.com/@alsakkah
};

// Build the user-facing URLs from raw IDs.
function buildLinks(cfg) {
  const c = { ...CONFIG_FALLBACK, ...cfg };
  return {
    ios: c.ios_app_id
      ? `https://apps.apple.com/app/id${c.ios_app_id}`
      : "#",
    android: c.android_app_id
      ? `https://play.google.com/store/apps/details?id=${c.android_app_id}`
      : "#",
    x: c.x_account_id
      ? `https://x.com/${c.x_account_id}`
      : "#",
    tiktok: c.tiktok_account_id
      ? `https://www.tiktok.com/@${c.tiktok_account_id}`
      : "#",
    legal: "https://alsakkah.app/legal",
    email: "mailto:support@alsakkah.app",
    xHandle: c.x_account_id ? `@${c.x_account_id}` : "@AlSakkah",
    tiktokHandle: c.tiktok_account_id ? `@${c.tiktok_account_id}` : "@AlSakkah",
  };
}

// React hook: fetch remote config once on mount; expose merged values.
function useAppConfig() {
  const [cfg, setCfg] = React.useState(CONFIG_FALLBACK);
  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        // Direct REST call — no need to bundle the supabase-js library.
        const res = await fetch(
          `${SUPABASE_URL}/rest/v1/app_config?select=key,value`,
          {
            headers: {
              apikey: SUPABASE_KEY,
              Authorization: `Bearer ${SUPABASE_KEY}`,
            },
          }
        );
        if (!res.ok) throw new Error("HTTP " + res.status);
        const rows = await res.json();
        if (cancelled || !Array.isArray(rows)) return;
        const next = { ...CONFIG_FALLBACK };
        rows.forEach((r) => { if (r && r.key) next[r.key] = r.value; });
        setCfg(next);
      } catch (err) {
        // Silent fail — fallbacks remain. Surface in console for debugging.
        console.warn("[appConfig] fetch failed:", err);
      }
    })();
    return () => { cancelled = true; };
  }, []);
  return React.useMemo(() => buildLinks(cfg), [cfg]);
}

// ─── Theme presets (vibe + bg + accent) ───────────────────────────
const VIBE_PRESETS = {
  luxe: {
    "--display": '"Reem Kufi", "IBM Plex Sans Arabic", system-ui, sans-serif',
    "--accent-font": '"Rakkas", "Reem Kufi", serif',
  },
  sport: {
    "--display": '"IBM Plex Sans Arabic", "Reem Kufi", system-ui, sans-serif',
    "--accent-font": '"IBM Plex Sans Arabic", system-ui, sans-serif',
  },
  card: {
    "--display": '"Marhey", "Reem Kufi", system-ui, sans-serif',
    "--accent-font": '"Marhey", "Reem Kufi", system-ui, sans-serif',
  },
};

const BG_PRESETS = {
  "#0d1611": {
    "--bg": "#0d1611", "--bg-2": "#121d17",
    "--surface": "#16231c", "--surface-2": "#1d2c24", "--surface-3": "#253630",
  },
  "#0a0a0a": {
    "--bg": "#0a0a0a", "--bg-2": "#141414",
    "--surface": "#1c1c1c", "--surface-2": "#242424", "--surface-3": "#2e2e2e",
  },
  "#0b1426": {
    "--bg": "#0b1426", "--bg-2": "#101d33",
    "--surface": "#16273f", "--surface-2": "#1e324e", "--surface-3": "#283f5d",
  },
  "#1a0e12": {
    "--bg": "#1a0e12", "--bg-2": "#25151b",
    "--surface": "#301c25", "--surface-2": "#3a2530", "--surface-3": "#452f3c",
  },
  "#18120a": {
    "--bg": "#18120a", "--bg-2": "#241a10",
    "--surface": "#2e2218", "--surface-2": "#392c1f", "--surface-3": "#443628",
  },
  "#141414": {
    "--bg": "#141414", "--bg-2": "#1d1d1d",
    "--surface": "#252525", "--surface-2": "#2e2e2e", "--surface-3": "#383838",
  },
};

const ACCENT_PRESETS = {
  "#e5a82c": {
    "--gold": "#e5a82c", "--gold-2": "#f2c75a",
    "--gold-deep": "#b8841e", "--gold-glow": "rgba(229, 168, 44, 0.4)",
  },
  "#3fa572": {
    "--gold": "#3fa572", "--gold-2": "#5cc890",
    "--gold-deep": "#287a52", "--gold-glow": "rgba(63, 165, 114, 0.4)",
  },
  "#f5a623": {
    "--gold": "#f5a623", "--gold-2": "#ffc966",
    "--gold-deep": "#c47e10", "--gold-glow": "rgba(245, 166, 35, 0.45)",
  },
  "#d97757": {
    "--gold": "#d97757", "--gold-2": "#f29978",
    "--gold-deep": "#a85638", "--gold-glow": "rgba(217, 119, 87, 0.4)",
  },
};

// ─── Persistent tweaks (production-only) ──────────────────────────
// useTweaks() from the starter only persists via the design-tool host
// (postMessage). In production there's no host — wrap it with
// localStorage so visitors who flip tweaks via ?tweaks=1 don't lose
// their changes on reload.
const TWEAKS_STORAGE_KEY = "alsakkah_tweaks_v2";

// Only the maintainer's ?tweaks=1 sessions read/write localStorage. Normal
// visitors ALWAYS get TWEAK_DEFAULTS — guaranteeing the published design is
// identical for everyone, and that no leftover experiment can ever leak into
// what a visitor sees.
const TWEAKS_MODE =
  new URLSearchParams(location.search).get("tweaks") === "1";

function usePersistedTweaks(defaults) {
  const initialValues = React.useMemo(() => {
    if (!TWEAKS_MODE) return defaults;
    try {
      const raw = localStorage.getItem(TWEAKS_STORAGE_KEY);
      if (raw) return { ...defaults, ...JSON.parse(raw) };
    } catch (e) { /* malformed or storage blocked → fall through */ }
    return defaults;
  }, []);
  const [t, setTweak] = useTweaks(initialValues);
  React.useEffect(() => {
    if (!TWEAKS_MODE) return;
    try { localStorage.setItem(TWEAKS_STORAGE_KEY, JSON.stringify(t)); }
    catch (e) { /* storage blocked → silently skip */ }
  }, [t]);
  return [t, setTweak];
}

function App() {
  const [t, setTweak] = usePersistedTweaks(TWEAK_DEFAULTS);
  const links = useAppConfig();

  // Make links available globally for components that don't accept props
  // (Footer, Socials, etc) via window without prop-drilling everywhere.
  React.useEffect(() => { window.__alSakkahLinks = links; }, [links]);

  // Apply theme variables.
  React.useEffect(() => {
    const root = document.documentElement;
    root.setAttribute("data-vibe", t.vibe);
    root.setAttribute("data-motion", String(t.motion));
    const vibe = VIBE_PRESETS[t.vibe] || VIBE_PRESETS.luxe;
    const acc = ACCENT_PRESETS[t.accent] || ACCENT_PRESETS["#e5a82c"];
    const bg = BG_PRESETS[t.bg] || BG_PRESETS["#0d1611"];
    Object.entries({ ...vibe, ...acc, ...bg }).forEach(([k, v]) =>
      root.style.setProperty(k, v)
    );
    root.style.setProperty("--bracket-line-pending", t.pendingLine || "#6b6b6b");
  }, [t.vibe, t.accent, t.bg, t.motion, t.pendingLine]);

  // Reveal-on-scroll.
  React.useEffect(() => {
    if (t.motion <= 1) {
      document.querySelectorAll(".reveal").forEach((el) => el.classList.add("in"));
      return;
    }
    let raf = 0;
    const check = () => {
      const vh = window.innerHeight;
      const triggerLine = vh * 0.88;
      document.querySelectorAll(".reveal:not(.in)").forEach((el) => {
        const r = el.getBoundingClientRect();
        if (r.top < triggerLine && r.bottom > 0) el.classList.add("in");
      });
    };
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => { raf = 0; check(); });
    };
    const t1 = setTimeout(check, 80);
    const t2 = setTimeout(check, 400);
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      clearTimeout(t1); clearTimeout(t2);
      cancelAnimationFrame(raf);
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, [t.motion, t.heroVariant, t.vibe]);

  // ?tweaks=1 → reveal the Tweaks panel on the live site (maintainer only).
  React.useEffect(() => {
    if (TWEAKS_MODE) {
      // The panel listens to '__activate_edit_mode' from window.parent —
      // post it to ourselves to flip its `open` state.
      setTimeout(() => {
        window.postMessage({ type: "__activate_edit_mode" }, "*");
      }, 300);
    }
  }, []);

  return (
    <>
      <Nav links={links} />
      <main>
        <Hero variant={t.heroVariant} links={links} />
        <Features />
        <Showcase />
        <Download links={links} />
        <FAQ />
        <Socials links={links} />
      </main>
      <Footer links={links} />

      {TWEAKS_MODE && (
      <TweaksPanel title="Tweaks">
        <TweakSection label="الأسلوب البصري" />
        <TweakRadio
          label="Vibe"
          value={t.vibe}
          options={["luxe", "sport", "card"]}
          onChange={(v) => setTweak("vibe", v)}
        />
        <TweakColor
          label="Accent"
          value={t.accent}
          options={["#e5a82c", "#3fa572", "#f5a623", "#d97757"]}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakColor
          label="Background"
          value={t.bg}
          options={["#0d1611", "#0a0a0a", "#0b1426", "#1a0e12", "#18120a", "#141414"]}
          onChange={(v) => setTweak("bg", v)}
        />
        <TweakColor
          label="Pending lines"
          value={t.pendingLine}
          options={["#6b6b6b", "#3a4a44", "#8a7a52", "#5a6b8a", "#a8927a"]}
          onChange={(v) => setTweak("pendingLine", v)}
        />
        <TweakSection label="الهيرو" />
        <TweakRadio
          label="Layout"
          value={t.heroVariant}
          options={[
            { value: "type", label: "نص" },
            { value: "bracket", label: "شجرة" },
            { value: "device", label: "جهاز" },
          ]}
          onChange={(v) => setTweak("heroVariant", v)}
        />
        <TweakSection label="الحركة" />
        <TweakSlider
          label="Motion"
          value={t.motion}
          min={1}
          max={5}
          step={1}
          onChange={(v) => setTweak("motion", v)}
        />
        <div style={{ fontSize: 10.5, color: "rgba(41,38,27,.5)", lineHeight: 1.5, padding: "2px 0" }}>
          1 = ساكن · 5 = ديناميكي
        </div>
      </TweaksPanel>
      )}
    </>
  );
}

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