import { reactive } from "vue";
import axios from "axios";
import { api, ensureCsrf } from "../services/api";
import { layoutConfig } from "../layout/composables/layout";

import faviconPng from "../assets/branding/favicon.png";
import logoCompact from "../assets/branding/logo-compact.png";
import logoHeader from "../assets/branding/logo-header.png";
import logoSidebarWhite from "../assets/branding/logo-sidebar-white.png";
import loginHeroSvg from "../assets/branding/login-hero.svg";

const xsrfCookie = "XSRF-TOKEN";
const xsrfHeader = "X-XSRF-TOKEN";

/** Bundled Build2Connect defaults — always resolveable via Vite (no dependency on public/). */
export const defaultBrandingUrls = {
  sidebar: logoSidebarWhite,
  header: logoHeader,
  compact: logoCompact,
  favicon: faviconPng,
  loginHero: loginHeroSvg,
};

const LOGO_KEYS = ["sidebar", "header", "compact", "favicon", "loginHero"];

export const appBranding = reactive({ ...defaultBrandingUrls });

export function mergeAppSettingsPayload(data) {
  if (data.theme && typeof data.theme === "object") {
    Object.assign(layoutConfig, data.theme);
  }
  if (data.logos && typeof data.logos === "object") {
    for (const key of LOGO_KEYS) {
      const v = data.logos[key];
      appBranding[key] =
        typeof v === "string" && v.length > 0 ? v : defaultBrandingUrls[key];
    }
  }
  applyDocumentFavicon(appBranding.favicon);
}

export async function hydrateAppSettings() {
  try {
    const { data } = await api.get("/api/app-settings");
    mergeAppSettingsPayload(data);
  } catch {
    Object.assign(appBranding, defaultBrandingUrls);
    applyDocumentFavicon(defaultBrandingUrls.favicon);
  }
}

export async function persistAppAppearance() {
  await ensureCsrf();
  const { data } = await api.patch("/api/superadmin/app-settings", {
    theme: {
      preset: layoutConfig.preset,
      primary: layoutConfig.primary,
      surface: layoutConfig.surface,
      darkTheme: layoutConfig.darkTheme,
      menuMode: layoutConfig.menuMode,
      menuTheme: layoutConfig.menuTheme,
      cardStyle: layoutConfig.cardStyle,
    },
  });
  mergeAppSettingsPayload(data);
}

export async function postBrandingUpload(formData) {
  await ensureCsrf();
  return axios.post("/api/superadmin/branding", formData, {
    baseURL: api.defaults.baseURL,
    withCredentials: true,
    xsrfCookieName: xsrfCookie,
    xsrfHeaderName: xsrfHeader,
    headers: {
      Accept: "application/json",
      "X-Requested-With": "XMLHttpRequest",
    },
  });
}

export async function deleteBrandingSlot(slot) {
  await ensureCsrf();
  const { data } = await api.delete(`/api/superadmin/branding/${slot}`);
  mergeAppSettingsPayload(data);
}

function applyDocumentFavicon(href) {
  if (typeof document === "undefined" || !href) {
    return;
  }
  let link = document.querySelector('link[rel="icon"]');
  if (!link) {
    link = document.createElement("link");
    link.rel = "icon";
    link.type = "image/png";
    document.head.appendChild(link);
  }
  link.href = href;
}
