import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

const LanguageSwitcher = ({ inverse = false }) => {
  const { i18n } = useTranslation();
  const [open, setOpen] = useState(false);
  const containerRef = useRef(null);

  const languages = [
    { code: 'en', name: 'EN', sub: 'English' },
    { code: 'zh-CN', name: '简体中文', sub: 'Chinese (Simplified)' }
  ];

  const currentCode = i18n.language === 'zh-TW' ? 'zh-CN' : i18n.language;
  const current = languages.find(l => l.code === currentCode) || languages[0];

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
    setOpen(false);
  };

  useEffect(() => {
    const onClickOutside = (e) => {
      if (containerRef.current && !containerRef.current.contains(e.target)) {
        setOpen(false);
      }
    };
    document.addEventListener('mousedown', onClickOutside);
    return () => document.removeEventListener('mousedown', onClickOutside);
  }, []);

  return (
    <div ref={containerRef} style={{ position: 'relative', display: 'inline-block' }}>
      <button
        type="button"
        className="btn-outline"
        onClick={() => setOpen(v => !v)}
        aria-haspopup="listbox"
        aria-expanded={open}
        style={{
          padding: '0.45rem 0.9rem',
          borderRadius: '9999px',
          display: 'inline-flex',
          alignItems: 'center',
          gap: '0.5rem',
          color: inverse ? '#FFFFFF' : undefined,
          borderColor: inverse ? '#FFFFFF' : undefined,
          background: 'transparent'
        }}
      >
        <span>{current.name}</span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
          <path d="M6 9l6 6 6-6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </button>

      {open && (
        <div
          role="listbox"
          aria-label="Select language"
          style={{
            position: 'absolute',
            right: 0,
            marginTop: '8px',
            minWidth: '180px',
            background: '#FFFFFF',
            border: '1px solid #E2E8F0',
            borderRadius: '10px',
            boxShadow: '0 10px 25px rgba(0,0,0,0.12)',
            overflow: 'hidden',
            zIndex: 20
          }}
        >
          {languages.map(lang => {
            const isActive = lang.code === current.code;
            return (
              <button
                key={lang.code}
                role="option"
                aria-selected={isActive}
                onClick={() => changeLanguage(lang.code)}
                className={isActive ? 'btn-primary' : ''}
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '0.65rem 0.9rem',
                  background: isActive ? undefined : '#FFFFFF',
                  border: 'none',
                  borderBottom: '1px solid #F1F5F9',
                  cursor: 'pointer'
                }}
              >
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <span style={{ fontSize: '0.95rem', color: isActive ? '#FFFFFF' : '#1A202C' }}>{lang.name}</span>
                  <span style={{ fontSize: '0.75rem', color: isActive ? 'rgba(255,255,255,0.9)' : '#64748B' }}>{lang.sub}</span>
                </div>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default LanguageSwitcher;
