/**
 * useAdsPolicy — single source of truth for the global Users-vs-Guests
 * ads toggles configured by the admin in the dashboard.
 *
 * Fetches `/api/public/ad-config` once on app boot and exposes three
 * derived booleans:
 *
 *   - globalEnabled    : master kill-switch (legacy `ads_enabled`)
 *   - enabledForUsers  : show ads to logged-in registered users
 *   - enabledForGuests : show ads to guests / not-logged-in visitors
 *
 * Backward-compatible defaults: if the backend has not been upgraded
 * with the new fields yet, we fall back to "guests=on, users=off",
 * which matches the previous behaviour of the entitlement hook.
 *
 * BUG-2 FIX (2026-05): wired so the admin's "ads for Users" switch
 * actually shows up in the React layer. Previously the only knob was
 * the master toggle + per-user override, and registered users were
 * forced ad-free regardless of admin intent.
 */
import { useEffect, useState } from "react";

interface AdConfigResponse {
  enabled?: boolean;
  /** New 2026-05 field — defaults to true (preserve legacy behaviour) */
  ads_enabled_for_guests?: boolean;
  /** New 2026-05 field — defaults to false (preserve legacy behaviour) */
  ads_enabled_for_users?: boolean;
}

export interface AdsPolicy {
  globalEnabled: boolean;
  enabledForUsers: boolean;
  enabledForGuests: boolean;
  loaded: boolean;
}

const DEFAULT_POLICY: AdsPolicy = {
  globalEnabled: false,
  enabledForUsers: false,
  enabledForGuests: false,
  loaded: false,
};

let cached: AdsPolicy | null = null;
let inflight: Promise<AdsPolicy> | null = null;

function apiBase(): string {
  // @ts-expect-error Vite inlines import.meta.env at build time
  return import.meta.env.VITE_BACKEND_URL
    // @ts-expect-error
    || import.meta.env.REACT_APP_BACKEND_URL
    || (globalThis as { REACT_APP_BACKEND_URL?: string }).REACT_APP_BACKEND_URL
    || "";
}

async function fetchPolicy(): Promise<AdsPolicy> {
  if (cached) return cached;
  if (inflight) return inflight;
  inflight = (async () => {
    try {
      const r = await fetch(`${apiBase()}/api/public/ad-config`, { cache: "no-cache" });
      if (!r.ok) throw new Error(`ad-config HTTP ${r.status}`);
      const j = (await r.json()) as AdConfigResponse;
      const globalEnabled = !!j.enabled;
      // Backward-compatible defaults — see file header.
      const enabledForGuests =
        typeof j.ads_enabled_for_guests === "boolean"
          ? j.ads_enabled_for_guests
          : globalEnabled;
      const enabledForUsers =
        typeof j.ads_enabled_for_users === "boolean"
          ? j.ads_enabled_for_users
          : false;
      cached = {
        globalEnabled,
        enabledForUsers,
        enabledForGuests,
        loaded: true,
      };
      return cached;
    } catch (e) {
      console.warn("[useAdsPolicy] /api/public/ad-config failed:", e);
      cached = { ...DEFAULT_POLICY, loaded: true };
      return cached;
    } finally {
      inflight = null;
    }
  })();
  return inflight;
}

export function useAdsPolicy(): AdsPolicy {
  const [policy, setPolicy] = useState<AdsPolicy>(cached ?? DEFAULT_POLICY);
  useEffect(() => {
    let cancelled = false;
    void fetchPolicy().then((p) => {
      if (!cancelled) setPolicy(p);
    });
    return () => {
      cancelled = true;
    };
  }, []);
  return policy;
}

/** Reset the in-memory cache (used after the admin saves settings). */
export function resetAdsPolicyCache(): void {
  cached = null;
}
