'use client';

import { useEffect, useRef, useState } from 'react';
import { useSalesChannel } from '@/lib/sales-channel-context';

export default function CurrencySwitcher() {
  const { currencies, currentCurrencyId, setCurrency, isReady } = useSalesChannel();
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const onClick = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };
    window.addEventListener('mousedown', onClick);
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('mousedown', onClick);
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  if (!isReady || currencies.length < 2) return null;

  const current = currencies.find((c) => c.id === currentCurrencyId) || currencies[0];
  const label = current?.translated?.shortName || current?.shortName || current?.isoCode || '';

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-1 px-2 py-1.5 text-sm text-surface-600 hover:text-surface-900 transition-colors"
        aria-label="Change currency"
      >
        <span className="font-medium">
          {current?.symbol} {label}
        </span>
        <svg className={`w-3 h-3 transition-transform ${open ? 'rotate-180' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {open && (
        <div className="absolute right-0 mt-1 w-44 bg-white border border-surface-200 rounded-lg shadow-lg py-1 z-[60]">
          {currencies.map((c) => (
            <button
              key={c.id}
              type="button"
              onClick={() => {
                setOpen(false);
                if (c.id !== currentCurrencyId) setCurrency(c.id);
              }}
              className={`w-full text-left px-3 py-2 text-sm transition-colors flex items-center justify-between ${
                c.id === currentCurrencyId
                  ? 'bg-brand-50 text-brand-700 font-medium'
                  : 'text-surface-700 hover:bg-surface-50'
              }`}
            >
              <span>
                {c.symbol} {c.translated?.shortName || c.shortName}
              </span>
              <span className="text-xs text-surface-400">{c.isoCode}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
