import { useMemo, useEffect, type ReactNode } from "react";

export interface FooterData {
  address: string;
  phone: string;
  email: string;
}

export interface Socials {
  facebook?: string;
  twitter?: string;
  linkedin?: string;
  instagram?: string;
  youtube?: string;
  telegram?: string;
  tiktok?: string;
  website?: string;
}
export type fileInfo = {
  size?: number;
  bucket?: string;
  fileName?: string;
  contentType?: string;
  originalname?: string;
};
export interface ModuleConfig {
  recordManagement: boolean;
  siteManagement: boolean;
  dms: boolean;
  performance: boolean;
  objective: boolean;
  complaint: boolean;
}

export interface TenantConfig {
  appName: string;
  organizationName: string;
  canUseAttachmentFromDMS?: boolean;
  logo: string;
  primaryColor: string;
  secondaryColor?: string;
  footerText: string;
  footerData: FooterData;
  socials: Socials;
  welcomeMessage: string;
  moduleConfig?: Partial<ModuleConfig>;
  dashboardPreviewImage?: string;
}
export interface brandingDTO {
  organizationName: {
    am: string;
    en: string;
  };
  logo: {
    presigned: string;
    fileInfo: fileInfo;
  };
  primaryColor: string;
  secondaryColor?: string;
  footerText: string;
  footerData: FooterData;
  socials: Socials;
  welcomeMessage: string;
  loginImage?: {
    presigned: string;
    fileInfo: fileInfo;
  };
  favicon?: {
    presigned: string;
    fileInfo: fileInfo;
  };
  moduleConfig?: Partial<ModuleConfig>;
}

/**
 * Resolve effective module visibility for a tenant.
 * Record Management and Site Management default to enabled.
 * Complaint controls public landing-page complaint entry points only (not module navigation).
 * Other optional modules default to disabled unless enabled by the tenant.
 */
export const resolveModuleConfig = (config: TenantConfig): ModuleConfig => ({
  recordManagement: config.moduleConfig?.recordManagement ?? true,
  siteManagement: true,
  dms: config.moduleConfig?.dms ?? false,
  performance: config.moduleConfig?.performance ?? false,
  objective: config.moduleConfig?.objective ?? false,
  complaint: config.moduleConfig?.complaint ?? false,
});

const defaultConfig: TenantConfig = {
  appName: "EDR Freight",
  organizationName: "Ethio-Djibouti Railways",
  canUseAttachmentFromDMS: false,
  logo: "/assets/TriaTradinglogo.png",
  primaryColor: "#1b354d",
  secondaryColor: "#0f5a3a",
  footerText: "COMMITED TO EXCELLENCE",
  footerData: {
    address: "Addis Ababa, Ethiopia",
    phone: "+251955232323",
    email: "info@triaplc.com",
  },
  socials: {
    facebook: "",
    twitter: "",
    linkedin: "",
    instagram: "",
    youtube: "",
    telegram: "",
    tiktok: "",
    website: "https://triaplc.com/",
  },
  welcomeMessage:
    "At Tria Trading PLC, we empower organizations with innovative software solutions and expert consulting services. Our commitment to excellence, innovation, and customer success enables us to deliver technology that drives growth, efficiency, and lasting impact.",
};

const tenantConfigs: Record<string, TenantConfig> = {
  localhost: {
    appName: "EDR Freight",
    organizationName: "Ethio-Djibouti Railways",
    logo: "",
    primaryColor: "#0EA371",
    moduleConfig: {
      dms: true,
      performance: true,
      objective: true,
      complaint: true,
    },
    canUseAttachmentFromDMS: true,
    secondaryColor: "#dad9db",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "Welcome to the Smart Office of the Addis Ababa City Administration. Addis Ababa is Ethiopia’s capital and a center of public service, innovation, culture, and opportunity. Through this platform, we aim to strengthen efficient service delivery, modernize administrative workflows, improve transparency, and support responsive governance for residents, institutions, and stakeholders across the city.",
  },
  "127.0.0.1": {
    appName: "Smart Office EDR",
    organizationName: "Ethio-Djibouti Railways",
    canUseAttachmentFromDMS: true,
    logo: "/assets/edrlogo.png",
    primaryColor: "#DC143C",
    moduleConfig: {
      dms: true,
      performance: true,
      objective: true,
      complaint: true,
    },
    secondaryColor: "#0f5a3a",
    dashboardPreviewImage: "/edrheadoffice.jpg",
    footerText:
      "The Ethio-Djibouti Railway was established in April 2017 following a bilateral agreement signed on December 16, 2016, between Ethiopia and Djibouti.",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "9546",
      email: "edr_@edrsc.com",
    },
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://edrsc.com/",
    },
    welcomeMessage:
      "The Ethio-Djibouti Railway was established in April 2017 following a bilateral agreement signed on December 16, 2016, between Ethiopia and Djibouti. A Shareholders Agreement was signed on January 11, 2017, among public bodies and state enterprises from both nations, governed by Ethiopian commercial law.\n\nThe shareholders formed a Share Company with an initial capital of USD 500 million, dedicated to operating and maintaining the Addis Ababa–Djibouti Railway and providing freight and passenger transport services.",
  },
  "smartoffice.edrsc.com": {
    appName: "Smart Office EDR",
    organizationName: "Ethio-Djibouti Railways",
    canUseAttachmentFromDMS: true,
    logo: "/assets/edrlogo.png",
    primaryColor: "#13724D",
    moduleConfig: {
      dms: true,
      performance: false,
      objective: false,
      complaint: true,
    },
    secondaryColor: "#0f5a3a",
    dashboardPreviewImage: "/edrheadoffice.jpg",
    footerText:
      "The Ethio-Djibouti Railway was established in April 2017 following a bilateral agreement signed on December 16, 2016, between Ethiopia and Djibouti.",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "9546",
      email: "edr_@edrsc.com",
    },
    socials: {
      facebook: "https://web.facebook.com/ethiodjiboutirailwaysc",
      twitter: "https://edrsc.com/",
      linkedin: "https://edrsc.com/",
      instagram: "https://edrsc.com/",
      youtube: "https://edrsc.com/",
      telegram: "",
      tiktok: "",
      website: "https://edrsc.com/",
    },
    welcomeMessage:
      "The Ethio-Djibouti Railway was established in April 2017 following a bilateral agreement signed on December 16, 2016, between Ethiopia and Djibouti. A Shareholders Agreement was signed on January 11, 2017, among public bodies and state enterprises from both nations, governed by Ethiopian commercial law.\n\nThe shareholders formed a Share Company with an initial capital of USD 500 million, dedicated to operating and maintaining the Addis Ababa–Djibouti Railway and providing freight and passenger transport services.",
  },
  "smartoffice.eiar.gov.et": {
    appName: "Smart Office EIAR",
    organizationName: "Ethiopian Institute of Agricultural Research",
    logo: "/assets/eiarLogo.jpg",
    primaryColor: "#388e4b",
    moduleConfig: { dms: false, performance: false, objective: false },
    secondaryColor: "#fff",
    footerText:
      "The Ethiopian Institute of Agricultural Research (EIAR) is one of the oldest and largest agricultural research institutes in Africa. EIAR has evolved through several stages since its first initiation during the late 1940s, following the establishment of agricultural and technical schools at Ambo and Jimma. In 1955, a full-fledged agricultural experiment station was established at Debre Zeit (now named Debre Zeit Agricultural Research Center) under the then Imperial College of Agricultural and mechanical Arts (now called Haramaya University) and had been continued as the major research entity until the mid-1960s. In 1966, Institute of Agricultural Research (IAR) was established as the first nationally coordinated agricultural research institute in Ethiopia. IAR was established with a mission to formulate national agricultural research guidelines, coordinate national agricultural research system, and undertake research in its centers and sub-centers located in various agro-ecological zones of Ethiopia.",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251-116-454441",
      email: "eiar.gov.et",
    },
    canUseAttachmentFromDMS: false,
    socials: {
      facebook: "https://web.facebook.com/EIARPR",
      website: "http://www.eiar.gov.et",
      twitter: "http://www.eiar.gov.et",
      linkedin: "http://www.eiar.gov.et",
      instagram: "http://www.eiar.gov.et",
      youtube: "http://www.eiar.gov.et",
    },

    welcomeMessage:
      "welcome you to the SmartOffice of the Ethiopian Institute of Agricultural Research. The Institute, since its establishment in 1966, has released over more 3000 agricultural technologies and improved farming practices by undertaking scientific research activities on various areas in crop, livestock, land and water, biotechnology, climate, farm machinery and agricultural economics. Of these technologies, 1190 are crop varieties and the rest include livestock breeds, pest and disease control methods, crop production and livestock husbandry methods, pre- and post-harvest technologies and recommendations. EIAR, in the five decades of its existence, has reached a large number of beneficiaries with its technologies and information found in different agro-ecologies throughout the country. The Institute has engaged itself in multiplication of initial technologies based on the demand created by the beneficiaries and supply to public and private technology multiplication actors for their wider reproduction and distribution.",
  },
  "smartoffice.ebi.gov.et": {
    appName: "EBI Smart Office",
    organizationName: "Ethiopian Biodiversity Institute - EBI",
    logo: "/assets/ebiLogoWhite.png",
    primaryColor: "#2a741d",
    moduleConfig: { dms: false, performance: false, objective: false },
    secondaryColor: "#2c246d",
    footerText: "Welcome to the Center of Origin & Diversity, Ethiopia",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251-116-615607",
      email: " info@ebi.gov.et",
    },
    canUseAttachmentFromDMS: false,
    socials: {
      facebook: "https://www.facebook.com/EthiopiaEBI",
      twitter: "https://x.com/EthiopiaEBI",
      linkedin: "https://www.linkedin.com/company/EthiopiaEBI",
      youtube: "https://www.youtube.com/@EthiopiaEBI",
      instagram: "https://www.youtube.com/@EthiopiaEBI",
      website: "https://ebi.gov.et",
      telegram: "https://t.me/EthiopiaEBI",
      tiktok: "https://www.tiktok.com/@ethiopiaebi",
    },
    welcomeMessage:
      "Ethiopia is recognized as one of the world’s most biodiverse nations.  Our rugged highlands, vast lowlands, and the rift valley lakes hold the genetic codes of the wild relatives of our staple food, and the endemic wildlife that defines our national identity. The Ethiopian Biodiversity Institute - EBI bears the profound responsibility of being the steward of these natural assets since its establishment in the 1970s.",
  },
  "smartoffice.aaca.gov.et": {
    appName: "Smart Office",
    organizationName: "Addis Ababa City Administration",
    logo: "",
    primaryColor: "#115005",
    moduleConfig: { dms: false, performance: false, objective: false },
    secondaryColor: "#dad9db",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    canUseAttachmentFromDMS: false,
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "Welcome to the Smart Office of the Addis Ababa City Administration. Addis Ababa is Ethiopia’s capital and a center of public service, innovation, culture, and opportunity. Through this platform, we aim to strengthen efficient service delivery, modernize administrative workflows, improve transparency, and support responsive governance for residents, institutions, and stakeholders across the city.",
  },
  "smartoffice.efd.moa.gov.et": {
    appName: "Smart Office EFD",
    organizationName: "Ethiopian Forest Development",
    logo: "/assets/efdlogo.jpg",
    primaryColor: "#006400",
    moduleConfig: { dms: false, performance: false, objective: false },
    secondaryColor: "#a52a2a",
    footerText:
      "Ethiopian Forestry Development (EFD) is an autonomous federal institution, established by Proclamation No. 1263/2021 on 25th January, as referred on article 81-No. 8 and by the federal government of Ethiopia council of ministers regulation No. 505/2022. EFD was resulted by merging the former research institute (The Ethiopian Environment and Forest Research Institute (EEFRI) together with the forestry sector from the then (Environment, Forest and climate change commission) having the following powers and duties.",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "9546",
      email: "dg-office@efd.gov.et",
    },
    canUseAttachmentFromDMS: false,
    socials: {
      facebook:
        "https://web.facebook.com/Ethiopian-Forestry-Development-EFD-100064767336706/?_rdc=1&_rdr#",
      twitter: "Ethiopian Forestry Development@EthiopianFores1",
      youtube: "https://www.youtube.com/@infoefd",
      website: "https://www.efd.gov.et",
    },
    welcomeMessage:
      "Organized forestry research in Ethiopia was started by the establishment of Forestry Research Centre (FRC) and the then Wood Utilization Research Centre (WUARC) in 1975 and 1979, respectively under the Forestry and Wildlife Conservation Development Authority (FaWCDA). The centres were incorporated to the then Ministry of Natural Resources Development and Environmental Protection in 1992 and again re-transferred to the Ministry of Agriculture in 1995. The Federal Government of Ethiopia reorganized the National Agricultural Research System and established the then Ethiopian Agricultural Research Organization (EARO) in 1997 (Negarit Gazeta, 1997). As a result, FRC and WUARC were transferred to EARO as one research centre (FRC) and one of the research sectors of EARO (now Ethiopian Institute of Agricultural Research (EIAR)). Then, the Government of Ethiopia found it necessary to give due attention to activities of environmental protection and forest development, protection and utilization by linking forestry research with environmental protection research at an institutional level for the attainment of the objectives of the Government that resulted in the establishment of the Ministry of Environment, Forest and Climate Change.",
  },
  "smartoffice.moa.gov.et": {
    appName: "Smart Office MOA",
    organizationName: "Ministry of Agriculture",
    logo: "/assets/ministryOfAgriculture.jpg",
    primaryColor: "#006400",
    moduleConfig: {
      dms: false,
      performance: false,
      objective: true,
      recordManagement: false,
    },
    secondaryColor: "#a52a2a",
    footerText:
      "The Ministry of Agriculture (MoA) is a federal government institution of Ethiopia responsible for leading and coordinating the country's agricultural development. The Ministry is mandated to formulate policies, strategies, and programs that enhance agricultural productivity, ensure food security, promote sustainable natural resource management, and support rural transformation. Through its various sectors and agencies, the Ministry oversees crop and livestock development, agricultural extension services, research coordination, and the implementation of national agricultural initiatives aimed at improving the livelihoods of farmers and contributing to the country's economic growth.",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "9546",
      email: "dg-office@efd.gov.et",
    },
    canUseAttachmentFromDMS: false,
    socials: {
      facebook: "https://web.facebook.com/MoAEthiopia/?_rdc=1&_rdr#",
      twitter: "https://x.com/MoA_Ethiopia",
      youtube: "https://www.youtube.com/@publicrelationmoa",
      website: "https://www.moa.gov.et",
    },
    welcomeMessage:
      "The Ministry of Agriculture (MoA) has played a central role in Ethiopia’s agricultural development and transformation efforts. Over the years, the Ministry has undergone various reforms and restructuring initiatives to strengthen the country's agricultural sector and improve food security. The Ministry is responsible for guiding agricultural research, extension services, livestock and crop development, natural resource management, and rural development programs. It works closely with research institutions, regional bureaus, development partners, and stakeholders to promote sustainable agricultural practices, increase productivity, and support the livelihoods of farmers and pastoral communities. Through its ongoing efforts, the Ministry continues to contribute significantly to Ethiopia’s economic growth, environmental sustainability, and national development objectives.",
  },
  "smartofficedev.moa.gov.et": {
    appName: "Smart Office MOA",
    organizationName: "Ministry of Agriculture",
    logo: "/assets/ministryOfAgriculture.jpg",
    primaryColor: "#006400",
    moduleConfig: {
      dms: false,
      performance: false,
      objective: true,
      recordManagement: true,
    },
    secondaryColor: "#a52a2a",
    footerText:
      "The Ministry of Agriculture (MoA) is a federal government institution of Ethiopia responsible for leading and coordinating the country's agricultural development. The Ministry is mandated to formulate policies, strategies, and programs that enhance agricultural productivity, ensure food security, promote sustainable natural resource management, and support rural transformation. Through its various sectors and agencies, the Ministry oversees crop and livestock development, agricultural extension services, research coordination, and the implementation of national agricultural initiatives aimed at improving the livelihoods of farmers and contributing to the country's economic growth.",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "9546",
      email: "dg-office@efd.gov.et",
    },
    canUseAttachmentFromDMS: false,
    socials: {
      facebook: "https://web.facebook.com/MoAEthiopia/?_rdc=1&_rdr#",
      twitter: "https://x.com/MoA_Ethiopia",
      youtube: "https://www.youtube.com/@publicrelationmoa",
      website: "https://www.moa.gov.et",
    },
    welcomeMessage:
      "The Ministry of Agriculture (MoA) has played a central role in Ethiopia’s agricultural development and transformation efforts. Over the years, the Ministry has undergone various reforms and restructuring initiatives to strengthen the country's agricultural sector and improve food security. The Ministry is responsible for guiding agricultural research, extension services, livestock and crop development, natural resource management, and rural development programs. It works closely with research institutions, regional bureaus, development partners, and stakeholders to promote sustainable agricultural practices, increase productivity, and support the livelihoods of farmers and pastoral communities. Through its ongoing efforts, the Ministry continues to contribute significantly to Ethiopia’s economic growth, environmental sustainability, and national development objectives.",
  },
  "triadms-dev.smartoffice.aaca.gov.et": {
    appName: "Smart Office Tria",
    organizationName: "Tria Trading PLC",
    logo: "/assets/TriaTradinglogo.png",
    primaryColor: "#1b354d",
    moduleConfig: { dms: true, performance: true, objective: true },
    secondaryColor: "#0f5a3a",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    canUseAttachmentFromDMS: true,
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "At Tria Trading PLC, we empower organizations with innovative software solutions and expert consulting services. Our commitment to excellence, innovation, and customer success enables us to deliver technology that drives growth, efficiency, and lasting impact.",
  },
  "triadms.smartoffice.aaca.gov.et": {
    appName: "Smart Office Tria",
    organizationName: "Tria Trading PLC",
    logo: "/assets/TriaTradinglogo.png",
    primaryColor: "#1b354d",
    moduleConfig: { dms: true, performance: true, objective: true },
    secondaryColor: "#0f5a3a",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "At Tria Trading PLC, we empower organizations with innovative software solutions and expert consulting services. Our commitment to excellence, innovation, and customer success enables us to deliver technology that drives growth, efficiency, and lasting impact.",
  },
  "smart-dev.smart.aaca.gov.et": {
    appName: "Smart Office Tria",
    organizationName: "Tria Trading PLC",
    logo: "/assets/TriaTradinglogo.png",
    primaryColor: "#1b354d",
    moduleConfig: { dms: true, performance: true, objective: true },
    secondaryColor: "#0f5a3a",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "At Tria Trading PLC, we empower organizations with innovative software solutions and expert consulting services. Our commitment to excellence, innovation, and customer success enables us to deliver technology that drives growth, efficiency, and lasting impact.",
  },
  "performance-dev.smart.aaca.gov.et": {
    appName: "Smart Office Tria",
    organizationName: "Tria Trading PLC",
    logo: "/assets/TriaTradinglogo.png",
    primaryColor: "#1b354d",
    moduleConfig: { dms: true, performance: true, objective: true },
    secondaryColor: "#0f5a3a",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "At Tria Trading PLC, we empower organizations with innovative software solutions and expert consulting services. Our commitment to excellence, innovation, and customer success enables us to deliver technology that drives growth, efficiency, and lasting impact.",
  },
  "performance.smart.aaca.gov.et": {
    appName: "Smart Office Tria",
    organizationName: "Tria Trading PLC",
    logo: "/assets/TriaTradinglogo.png",
    primaryColor: "#1b354d",
    moduleConfig: { dms: true, performance: true, objective: true },
    secondaryColor: "#0f5a3a",
    footerText: "COMMITED TO EXCELLENCE",
    footerData: {
      address: "Addis Ababa, Ethiopia",
      phone: "+251955232323",
      email: "info@triaplc.com",
    },
    socials: {
      facebook: "",
      twitter: "",
      linkedin: "",
      instagram: "",
      youtube: "",
      telegram: "",
      tiktok: "",
      website: "https://triaplc.com/",
    },
    welcomeMessage:
      "At Tria Trading PLC, we empower organizations with innovative software solutions and expert consulting services. Our commitment to excellence, innovation, and customer success enables us to deliver technology that drives growth, efficiency, and lasting impact.",
  },
};

/** Resolve tenant config from hostname (defaults to localhost config). */
export const resolveTenantConfig = (
  hostname: string = typeof window !== "undefined"
    ? window.location.hostname
    : "localhost",
): TenantConfig => {
  // Normalize host input so callers can pass full URLs or mixed-case values safely.
  const normalizedHost = hostname
    ?.trim()
    .toLowerCase()
    .replace(/^https?:\/\//, "")
    .replace(/\/.*$/, "")
    .replace(/:\d+$/, "");

  return tenantConfigs[normalizedHost] || defaultConfig;
};

/** Apply tenant theme tokens to the document root (CSS variables, title, favicon). */
export const applyTenantTheme = (config: TenantConfig) => {
  if (typeof document === "undefined") {
    return;
  }

  const root = document.documentElement;

  const primary =
    config.primaryColor?.trim() || "var(--primary-default, #18aa9d)";

  root.style.setProperty("--primary", primary);
  root.style.setProperty("--ring", primary);
  root.style.setProperty("--sidebar-primary", primary);
  // Accent is a subtle hover/highlight background (dropdown items, menus) that
  // must stay readable under --accent-foreground text in BOTH color schemes.
  // Full-strength brand color here produced dark-pill-with-dark-text hovers,
  // so use a translucent tint of the brand color instead.
  root.style.setProperty(
    "--accent",
    `color-mix(in oklab, ${primary} 15%, transparent)`,
  );
  root.style.setProperty("--chart-1", primary);

  if (config.organizationName) {
    document.title = config.organizationName;
  }

  if (config.logo) {
    let link = document.querySelector<HTMLLinkElement>('link[rel="icon"]');

    if (!link) {
      link = document.createElement("link");
      link.rel = "icon";
      document.head.appendChild(link);
    }

    link.href = config.logo;
  }
};

// Apply tenant theme before React mounts so deep-linked routes (e.g. record-management)
// keep branding on hard refresh without relying on login/landing page components.
if (typeof window !== "undefined") {
  applyTenantTheme(resolveTenantConfig());
}

export const useTenantConfig = () => {
  const hostname = useMemo(() => window.location.hostname, []);

  const config = useMemo(() => resolveTenantConfig(hostname), [hostname]);

  useEffect(() => {
    applyTenantTheme(config);
  }, [config]);

  return {
    config,
    hostname,
  };
};

/** Ensures tenant theme is applied on every route, including lazy-loaded modules. */
export const TenantConfigProvider = ({ children }: { children: ReactNode }) => {
  useTenantConfig();
  return children;
};
