"use client";

import { useGetAbout } from "@/app/[name]/(Main)/about/hooks/useAboutData";
import { PWA_ICON_192 } from "@/lib/helpers/pwaIcons";
import { useParams } from "next/navigation";
import { useEffect } from "react";

function upsertMeta(name: string, content: string, attribute: "name" | "property" = "name") {
  let element = document.querySelector(`meta[${attribute}="${name}"]`);
  if (!element) {
    element = document.createElement("meta");
    element.setAttribute(attribute, name);
    document.head.appendChild(element);
  }
  element.setAttribute("content", content);
}

function upsertLink(rel: string, href: string) {
  let element = document.querySelector(`link[rel="${rel}"]`) as HTMLLinkElement | null;
  if (!element) {
    element = document.createElement("link");
    element.rel = rel;
    document.head.appendChild(element);
  }
  element.href = href;
}

export default function RestaurantHeadManager() {
  const { name } = useParams<{ name: string }>();
  const { data } = useGetAbout();

  useEffect(() => {
    if (!name || !data?.data) return;

    const restaurant = data.data;
    document.title = restaurant.seoTitle || restaurant.name;

    upsertMeta(
      "description",
      restaurant.seoDescription ||
        restaurant.description ||
        `منوی ${restaurant.name}`,
    );

    const themeColor = restaurant.menuColor || "#F4F5F9";
    upsertMeta("theme-color", themeColor);

    upsertLink("manifest", `/${name}/manifest.webmanifest`);

    // Restaurant logo disabled – using static PWA icons (logo192.png / logo512.png)
    // const logo = restaurant.logo?.trim();
    // const iconUrl =
    //   logo && logo !== ""
    //     ? `/${name}/api/logo?url=${encodeURIComponent(logo)}&size=192`
    //     : PWA_ICON_192;
    const iconUrl = PWA_ICON_192;

    upsertLink("icon", iconUrl);
    upsertLink("apple-touch-icon", iconUrl);
  }, [data, name]);

  return null;
}
