import { useEffect } from 'react';
import {
  SITE_BACKGROUND_BLUR,
  SITE_DESCRIPTION,
  SITE_GLASS_OPACITY,
  SITE_NAME,
  SITE_RANDOM_BG_API,
  SITE_SHORT_NAME,
} from '../config/site';

/** 随路由更新标题与 meta */
export function useSiteBranding(isAdminRoute: boolean) {
  useEffect(() => {
    const pageTitle = isAdminRoute ? `${SITE_NAME}-管理后台` : SITE_NAME;
    document.title = pageTitle;
    const metaDesc = document.querySelector('meta[name="description"]');
    if (metaDesc) metaDesc.setAttribute('content', SITE_DESCRIPTION);
    const metaApp = document.querySelector('meta[name="apple-mobile-web-app-title"]');
    if (metaApp) metaApp.setAttribute('content', SITE_NAME);
  }, [isAdminRoute]);

  useEffect(() => {
    if (typeof SITE_GLASS_OPACITY === 'number' && SITE_GLASS_OPACITY >= 0 && SITE_GLASS_OPACITY <= 1) {
      document.documentElement.style.setProperty('--site-glass-opacity', String(SITE_GLASS_OPACITY));
    }
    if (SITE_BACKGROUND_BLUR) {
      document.documentElement.style.setProperty('--site-bg-blur', SITE_BACKGROUND_BLUR);
    }

    const manifest = {
      name: SITE_NAME,
      short_name: SITE_SHORT_NAME,
      description: SITE_DESCRIPTION,
      lang: 'zh-CN',
      dir: 'ltr',
      id: '/',
      start_url: '/?source=pwa',
      scope: '/',
      display: 'standalone',
      display_override: ['standalone', 'minimal-ui', 'browser'],
      orientation: 'portrait-primary',
      theme_color: '#ea580c',
      background_color: '#fff7ed',
      categories: ['productivity', 'utilities'],
      prefer_related_applications: false,
      icons: [
        { src: '/logo.png', type: 'image/png', sizes: '2048x2048', purpose: 'any' },
        { src: '/logo.png', type: 'image/png', sizes: '2048x2048', purpose: 'maskable' },
        {
          src: '/favicon.ico',
          type: 'image/x-icon',
          sizes: '16x16 24x24 32x32 48x48 64x64',
          purpose: 'any',
        },
      ],
    };
    const blob = new Blob([JSON.stringify(manifest)], { type: 'application/json' });
    const blobUrl = URL.createObjectURL(blob);
    let link = document.querySelector('link[rel="manifest"]') as HTMLLinkElement | null;
    if (!link) {
      link = document.createElement('link');
      link.rel = 'manifest';
      document.head.appendChild(link);
    }
    link.href = blobUrl;

    const apiBase = SITE_RANDOM_BG_API?.trim();

    let cancelled = false;

    function cleanupBg() {
      document.querySelectorAll('.site-bg').forEach((el) => el.remove());
    }

    if (apiBase) {
      const isMobile = window.matchMedia('(max-width: 767px)').matches;
      const mode = isMobile ? 'mobile' : 'desktop';
      const jsonUrl = `${apiBase.replace(/\/$/, '')}/api/random?format=json&mode=${encodeURIComponent(mode)}`;

      fetch(jsonUrl)
        .then((r) => {
          if (!r.ok) throw new Error('bg api ' + r.status);
          return r.json();
        })
        .then((data: { url?: string; src?: string }) => {
          if (cancelled || !data) return;
          const imgUrl = data.url || data.src;
          if (!imgUrl || typeof imgUrl !== 'string') return;
          const applyBg = () => {
            cleanupBg();
            const bgEl = document.createElement('div');
            bgEl.className = 'site-bg';
            bgEl.setAttribute('aria-hidden', 'true');
            bgEl.style.backgroundImage = `url("${imgUrl.replace(/"/g, '\\"')}")`;
            document.body.insertBefore(bgEl, document.body.firstChild);
          };
          if (document.body) applyBg();
          else document.addEventListener('DOMContentLoaded', applyBg);
        })
        .catch(() => {});
    }

    return () => {
      cancelled = true;
      URL.revokeObjectURL(blobUrl);
      cleanupBg();
    };
  }, []);
}
