'use client';

import { persistTheme, themePreferenceEvent } from '@/lib/theme/client';
import { type ThemePreference } from '@/lib/theme/config';
import { modeSwitchUrl, routeIdFromPathname } from '@/lib/localization/config';
import { usePathname, useRouter } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import styles from './ThemePill.module.css';

interface Props {
  initialPreference: ThemePreference;
}

const labels: Record<ThemePreference, string> = {
  light: 'Light',
  dark: 'Dark',
  system: 'System',
};

export function ThemePill({ initialPreference }: Props) {
  const [pref, setPref] = useState<ThemePreference>(initialPreference);
  const pathname = usePathname();
  const router = useRouter();
  const menuRef = useRef<HTMLDivElement | null>(null);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const handler = (event: Event) => {
      const next = (event as CustomEvent<ThemePreference>).detail;
      if (next === 'light' || next === 'dark' || next === 'system') setPref(next);
    };
    window.addEventListener(themePreferenceEvent, handler);
    return () => window.removeEventListener(themePreferenceEvent, handler);
  }, []);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (!menuRef.current?.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const selectTheme = (next: ThemePreference) => {
    setOpen(false);
    persistTheme(next);
    setPref(next);
    const routeId = routeIdFromPathname(pathname) ?? 'home';
    const target = modeSwitchUrl(new URL(window.location.href), next, routeId);
    router.push(`${target.pathname}${target.search}${target.hash}`);
  };

  const options: ThemePreference[] = ['light', 'dark', 'system'];
  const otherOptions = options.filter((o) => o !== pref);

  const displayLabel = pref === 'dark' ? 'Dark' : 'Light';

  return (
    <div ref={menuRef} className={styles.wrap}>
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        className={styles.button}
        aria-expanded={open}
        aria-haspopup="menu"
        aria-label={displayLabel}
      >
        <span className={styles.label}>{displayLabel}</span>
        <svg
          xmlns="http://www.w3.org/2000/svg"
          className={`${styles.chevron} ${open ? styles.chevronOpen : ''}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
        </svg>
      </button>
      {open && (
        <div className={styles.menu}>
          {otherOptions.map((o) => (
            <button
              key={o}
              type="button"
              onClick={() => selectTheme(o)}
              className={styles.option}
            >
              <span>{labels[o]}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
