import { useEffect, useState } from "react";
import { apiPublicPlaybackMode } from "@/lib/nadiAuth";

const CACHE_KEY = "nadiplay.inlinePreview.enabledCache.v1";

/**
 * Returns whether the admin has enabled the inline preview player on
 * Live TV. Uses the same pattern as the other feature flags: a
 * synchronous localStorage cache for instant decisions + a background
 * refresh against /api/public/playback-mode.
 *
 * Default is TRUE (opt-out) to match the feature being "on by default".
 */
export const useInlinePreviewEnabled = (): boolean => {
  const [enabled, setEnabled] = useState<boolean>(() => {
    try {
      const raw = localStorage.getItem(CACHE_KEY);
      if (raw === "0") return false;
      if (raw === "1") return true;
    } catch {
      /* noop */
    }
    return true;
  });

  useEffect(() => {
    let cancelled = false;
    void apiPublicPlaybackMode()
      .then((cfg) => {
        if (cancelled) return;
        // Treat undefined (older backend) as enabled → backwards compat.
        const next = cfg.inline_preview_enabled !== false;
        setEnabled(next);
        try {
          localStorage.setItem(CACHE_KEY, next ? "1" : "0");
        } catch {
          /* noop */
        }
      })
      .catch(() => {
        /* offline — keep cached */
      });
    return () => {
      cancelled = true;
    };
  }, []);

  return enabled;
};
