'use client';

import { useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useEnvStore } from '@/c-store';
import { useShallow } from 'zustand/react/shallow';
import { flushUmamiIdentify, trackPageview } from '@/c-common/tools/tracking';
import { useUserStore } from '@/store';

const SCRIPT_ID = 'umami-analytics-script';
const AUTO_TRACK_ATTRIBUTE_VALUE = 'false';

const ensureUmamiScript = (src: string, websiteId: string) => {
  const existing = document.getElementById(SCRIPT_ID);
  if (existing) {
    existing.setAttribute('data-website-id', websiteId);
    existing.setAttribute('data-auto-track', AUTO_TRACK_ATTRIBUTE_VALUE);
    flushUmamiIdentify();
    return;
  }

  const script = document.createElement('script');
  script.id = SCRIPT_ID;
  script.defer = true;
  script.src = src;
  script.setAttribute('data-website-id', websiteId);
  script.setAttribute('data-auto-track', AUTO_TRACK_ATTRIBUTE_VALUE);
  script.addEventListener('load', () => {
    flushUmamiIdentify();
  });
  document.head.appendChild(script);
};

export const UmamiLoader = () => {
  const { umamiScriptSrc, umamiWebsiteId } = useEnvStore(
    useShallow(state => ({
      umamiScriptSrc: state.umamiScriptSrc,
      umamiWebsiteId: state.umamiWebsiteId,
    })),
  );
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const search = searchParams?.toString();
  const isUserInitialized = useUserStore(state => state.isInitialized);

  useEffect(() => {
    if (!umamiScriptSrc || !umamiWebsiteId) {
      return;
    }
    ensureUmamiScript(umamiScriptSrc, umamiWebsiteId);
  }, [umamiScriptSrc, umamiWebsiteId]);

  useEffect(() => {
    if (!umamiScriptSrc || !umamiWebsiteId) {
      return;
    }

    if (!isUserInitialized) {
      return;
    }

    if (typeof window === 'undefined') {
      trackPageview();
      return;
    }

    const origin = window.location.origin || '';
    const pageUrl = `${origin}${pathname}${search ? `?${search}` : ''}`;
    trackPageview(pageUrl);
  }, [pathname, search, umamiScriptSrc, umamiWebsiteId, isUserInitialized]);

  return null;
};

export default UmamiLoader;
