/* AICAN MVP — Globe-icon language dropdown.
   Sits in the topbar next to the Upload button. Same shape as the main
   project's language-selector.tsx but using inline SVGs and design tokens. */

const LSIcon = ({ d, size = 16, viewBox = '0 0 24 24' }) => (
  <svg width={size} height={size} viewBox={viewBox} fill="none" stroke="currentColor"
       strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
    {typeof d === 'string' ? <path d={d}/> : d}
  </svg>
);
const IconGlobe    = (p) => <LSIcon {...p} d={<><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20"/></>}/>;
const IconChevron  = (p) => <LSIcon {...p} d="M6 9l6 6 6-6"/>;
const IconCheck    = (p) => <LSIcon {...p} d="M20 6L9 17l-5-5"/>;
const IconCloseLs  = (p) => <LSIcon {...p} d="M6 6l12 12M18 6 6 18"/>;
const IconSearchLs = (p) => <LSIcon {...p} d={<><circle cx="11" cy="11" r="7"/><path d="M21 21l-4.3-4.3"/></>}/>;

const LanguageSelector = () => {
  const lang = useLanguage();
  const [open, setOpen]     = React.useState(false);
  const [search, setSearch] = React.useState('');
  const [busy, setBusy]     = React.useState(false);
  const wrapRef = React.useRef(null);

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

  const filtered = !search
    ? window.SUPPORTED_LANGUAGES
    : window.SUPPORTED_LANGUAGES.filter(l =>
        l.name.toLowerCase().includes(search.toLowerCase()) ||
        l.nativeName.toLowerCase().includes(search.toLowerCase()) ||
        l.code.toLowerCase().includes(search.toLowerCase()));

  const pick = async (l) => {
    setBusy(true);
    setOpen(false);
    setSearch('');
    try { await window.AicanLang.setLanguage(l); } finally { setBusy(false); }
  };

  return (
    <div className="lang-selector" ref={wrapRef}>
      <button type="button" className="lang-trigger" onClick={() => { setOpen(!open); setSearch(''); }} title={lang.t('Language')}>
        <IconGlobe size={14}/>
        <span className="native">{lang.current.nativeName}</span>
        {busy ? <span className="dot-spinner small" style={{ width: 12, height: 12 }}/> : <IconChevron size={12}/>}
      </button>

      {open && (
        <div className="lang-pop">
          <div className="lang-pop-head">
            <span><IconGlobe size={14}/> {lang.t('Language')}</span>
            <button type="button" onClick={() => setOpen(false)}><IconCloseLs size={14}/></button>
          </div>
          <div className="lang-search">
            <IconSearchLs size={14}/>
            <input
              type="text" value={search} autoFocus
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Search languages..."
            />
          </div>
          <div className="lang-list">
            {filtered.map((l) => {
              const active = lang.current.code === l.code;
              return (
                <button key={l.code} type="button" className={'lang-item' + (active ? ' active' : '')} onClick={() => pick(l)}>
                  <span className="native">{l.nativeName}</span>
                  <span className="english">{l.name}</span>
                  {active && <IconCheck size={14}/>}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

window.LanguageSelector = LanguageSelector;
