// Public app settings: branding + feature toggles + which social providers
// are enabled. Fetched once from the backend on load and applied to the DOM
// (document title, theme CSS variables, favicon).

import { createContext, useContext, useEffect, useState, type ReactNode } from "react";
import { API_BASE_URL } from "./backend-client";

export interface PublicSettings {
  branding: {
    app_title: string;
    app_description: string;
    logo_url: string;
    favicon_url: string;
    primary_color: string;
    accent_color: string;
  };
  features: {
    registration_enabled: boolean;
    auto_approve_trades: boolean;
    google_login_enabled: boolean;
    facebook_login_enabled: boolean;
    x_login_enabled: boolean;
  };
  oauth: {
    google: { client_id: string; configured: boolean };
    facebook: { client_id: string; configured: boolean };
    x: { client_id: string; configured: boolean };
  };
}

const FALLBACK: PublicSettings = {
  branding: {
    app_title: "Delta Terminal",
    app_description: "Production-grade real-time trading terminal.",
    logo_url: "",
    favicon_url: "/favicon.ico",
    primary_color: "#7c3aed",
    accent_color: "#22d3ee",
  },
  features: {
    registration_enabled: true,
    auto_approve_trades: false,
    google_login_enabled: false,
    facebook_login_enabled: false,
    x_login_enabled: false,
  },
  oauth: {
    google: { client_id: "", configured: false },
    facebook: { client_id: "", configured: false },
    x: { client_id: "", configured: false },
  },
};

const Ctx = createContext<PublicSettings>(FALLBACK);

function hexToHsl(hex: string): string | null {
  const m = hex.match(/^#?([0-9a-f]{6})$/i);
  if (!m) return null;
  const n = parseInt(m[1], 16);
  const r = ((n >> 16) & 255) / 255;
  const g = ((n >> 8) & 255) / 255;
  const b = (n & 255) / 255;
  const max = Math.max(r, g, b), min = Math.min(r, g, b);
  const l = (max + min) / 2;
  let h = 0, s = 0;
  if (max !== min) {
    const d = max - min;
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break;
      case g: h = (b - r) / d + 2; break;
      case b: h = (r - g) / d + 4; break;
    }
    h /= 6;
  }
  return `${Math.round(h * 360)} ${Math.round(s * 100)}% ${Math.round(l * 100)}%`;
}

function applyBranding(s: PublicSettings) {
  if (typeof document === "undefined") return;
  document.title = s.branding.app_title;
  const root = document.documentElement;
  const primary = hexToHsl(s.branding.primary_color);
  const accent = hexToHsl(s.branding.accent_color);
  if (primary) root.style.setProperty("--primary", primary);
  if (accent) root.style.setProperty("--accent", accent);
  if (s.branding.favicon_url) {
    let link = document.querySelector("link[rel~='icon']") as HTMLLinkElement | null;
    if (!link) {
      link = document.createElement("link");
      link.rel = "icon";
      document.head.appendChild(link);
    }
    link.href = s.branding.favicon_url;
  }
}

export function AppSettingsProvider({ children }: { children: ReactNode }) {
  const [settings, setSettings] = useState<PublicSettings>(FALLBACK);
  useEffect(() => {
    let alive = true;
    fetch(`${API_BASE_URL}/settings/public`)
      .then((r) => (r.ok ? r.json() : null))
      .then((s) => {
        if (!alive || !s) return;
        setSettings(s as PublicSettings);
        applyBranding(s as PublicSettings);
      })
      .catch(() => {});
    return () => {
      alive = false;
    };
  }, []);
  return <Ctx.Provider value={settings}>{children}</Ctx.Provider>;
}

export function useAppSettings() {
  return useContext(Ctx);
}
