"use client";

/**
 * DynamicMeta — Sets the browser tab title and favicon dynamically
 * based on the current page and the company name/logo fetched from the API.
 *
 * Works for both authenticated (full API fetch) and public pages
 * (falls back to localStorage cache set during a previous auth session).
 */

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { API_BASE_URL, getAuthHeaders } from "@/lib/api";

// Map route prefixes → human-readable page label
const PAGE_LABELS: Record<string, string> = {
    "/": "Dashboard",
    "/map": "Interactive Map",
    "/assets": "Properties & Assets",
    "/clients": "Clients",
    "/contracts": "Contracts",
    "/payments": "Payments & Ledger",
    "/settings": "System Settings",
    "/contact": "Help & Contact",
    "/login": "Sign In",
};

const COMPANY_NAME_CACHE = "company_name_cache";
const COMPANY_LOGO_CACHE = "company_logo_cache";

function getPageLabel(pathname: string): string {
    // Exact match first
    if (PAGE_LABELS[pathname]) return PAGE_LABELS[pathname];
    // Prefix match (e.g. /clients/42 → Clients)
    const match = Object.entries(PAGE_LABELS)
        .filter(([k]) => k !== "/")
        .find(([k]) => pathname.startsWith(k + "/"));
    return match ? match[1] : "CRM";
}

function applyFavicon(src: string) {
    if (!src) return;
    // Remove any previously injected dynamic favicon
    document.querySelectorAll('link[rel="icon"][data-dyn]').forEach(el => el.remove());

    const link = document.createElement("link");
    link.rel = "icon";
    link.setAttribute("data-dyn", "1");
    link.setAttribute("sizes", "any");

    // Detect MIME type from the source
    if (src.startsWith("data:image/webp") || src.endsWith(".webp")) link.type = "image/webp";
    else if (src.startsWith("data:image/png") || src.endsWith(".png")) link.type = "image/png";
    else if (src.startsWith("data:image/jpeg") || src.endsWith(".jpg") || src.endsWith(".jpeg")) link.type = "image/jpeg";
    else if (src.startsWith("data:image/gif") || src.endsWith(".gif")) link.type = "image/gif";
    else if (src.endsWith(".svg")) link.type = "image/svg+xml";

    link.href = src;
    document.head.appendChild(link);
}

export function DynamicMeta() {
    const pathname = usePathname();

    useEffect(() => {
        const pageLabel = getPageLabel(pathname);

        /* ── 1. Apply cached values INSTANTLY (no API round-trip lag) ── */
        const cachedName = localStorage.getItem(COMPANY_NAME_CACHE) || "";
        const cachedLogo = localStorage.getItem(COMPANY_LOGO_CACHE) || "";

        document.title = cachedName
            ? `${pageLabel} | ${cachedName}`
            : pageLabel;

        if (cachedLogo) applyFavicon(cachedLogo);

        /* ── 2. Refresh from API in the background ── */
        const headers = getAuthHeaders();
        const hasToken = !!(headers as Record<string, string>)["Authorization"];
        if (!hasToken) return; // public page, cached values are enough

        (async () => {
            try {
                const res = await fetch(`${API_BASE_URL}/companies/`, { headers });
                if (!res.ok) return;
                const data = await res.json();
                const company = (data.results || data)[0];
                if (!company) return;

                if (company.name) {
                    localStorage.setItem(COMPANY_NAME_CACHE, company.name);
                    document.title = `${pageLabel} | ${company.name}`;
                }
                if (company.logo) {
                    localStorage.setItem(COMPANY_LOGO_CACHE, company.logo);
                    applyFavicon(company.logo);
                } else {
                    // Logo was removed in settings — clear favicon back to default
                    localStorage.removeItem(COMPANY_LOGO_CACHE);
                    document.querySelectorAll('link[rel="icon"][data-dyn]').forEach(el => el.remove());
                }
            } catch { /* silent — cached values are shown */ }
        })();
    }, [pathname]);

    return null; // No DOM output — side-effects only
}
