"use client";

import { useEffect } from "react";
import { useAppLanguage } from "@/contexts/LanguageProvider";
import {
  getPwaLabels,
  PWA_VERSION,
  toPwaLang,
} from "@/lib/pwaConfig";

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

function upsertMeta(name: string, content: string) {
  let meta = document.querySelector<HTMLMetaElement>(`meta[name="${name}"]`);
  if (!meta) {
    meta = document.createElement("meta");
    meta.name = name;
    document.head.appendChild(meta);
  }
  meta.content = content;
}

export default function PwaHead() {
  const { language, ready } = useAppLanguage();

  useEffect(() => {
    if (!ready) return;

    const pwaLang = toPwaLang(language);
    const labels = getPwaLabels(pwaLang);

    upsertLink(
      "manifest",
      `/manifest.webmanifest?lang=${pwaLang}&v=${PWA_VERSION}`
    );
    upsertLink("apple-touch-icon", "/images/icons/apple-touch-icon.png");
    upsertMeta("apple-mobile-web-app-title", labels.short_name);
    upsertMeta("application-name", labels.short_name);
  }, [language, ready]);

  return null;
}
