// country-cascade.jsx — Componentă reutilizabilă pentru câmpurile Țară / Județ / Oraș.
// Toate cele 3 dropdown-uri folosesc același <CustomDropdown> intern → comportament 100% identic.
// Expune window.CountryCascade.

const { useState: useStateCC, useEffect: useEffectCC, useMemo: useMemoCC, useRef: useRefCC } = React;

function _ccNormalize(s) {
  return (s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
}

// ─── CustomDropdown — dropdown identic peste tot ─────────────────
// Tastatura: sus/jos mută opțiunea evidențiată, Enter alege, Escape închide,
// Home/End sar la capete. Ramura fără căutare (Județ, Oraș) era un <div> simplu,
// fără tabIndex și fără rol — Tab sărea tăcut peste două câmpuri obligatorii.
function CustomDropdown({ value, onChange, options, placeholder, searchable = false, disabled = false }) {
  const [open, setOpen] = useStateCC(false);
  const [query, setQuery] = useStateCC(value || '');
  const [hi, setHi] = useStateCC(-1);       // indexul opțiunii evidențiate
  const wrapRef = useRefCC(null);
  const listRef = useRefCC(null);
  const listId = React.useId();

  // Sincronizează query cu value extern
  useEffectCC(() => { setQuery(value || ''); }, [value]);

  // Click în afara → închide și restabilește query
  useEffectCC(() => {
    const handler = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) {
        setOpen(false);
        if (searchable) setQuery(value || '');
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [value, searchable]);

  const filtered = useMemoCC(() => {
    if (!searchable) return options;
    const q = _ccNormalize(query);
    if (!q) return options;
    return options.filter(o => _ccNormalize(o).includes(q));
  }, [options, query, searchable]);

  // La deschidere pornim de la opțiunea deja aleasă, nu de la prima din listă.
  useEffectCC(() => {
    if (!open) { setHi(-1); return; }
    const i = filtered.indexOf(value);
    setHi(i >= 0 ? i : (filtered.length ? 0 : -1));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  // Când lista se filtrează sub degete, indexul vechi poate rămâne în afara ei.
  useEffectCC(() => {
    if (!open) return;
    setHi(h => (filtered.length === 0 ? -1 : Math.min(h < 0 ? 0 : h, filtered.length - 1)));
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filtered.length]);

  // Lista derulează singură, ca opțiunea evidențiată să rămână vizibilă.
  useEffectCC(() => {
    if (!open || hi < 0 || !listRef.current) return;
    const el = listRef.current.querySelector('[data-cc-idx="' + hi + '"]');
    if (el && el.scrollIntoView) el.scrollIntoView({ block: 'nearest' });
  }, [hi, open]);

  const handleSelect = (opt) => {
    onChange(opt);
    setOpen(false);
    setQuery(opt);
  };

  const inchide = () => {
    setOpen(false);
    if (searchable) setQuery(value || '');
  };

  const deschide = () => {
    if (searchable) setQuery('');
    setOpen(true);
  };

  const onKeyDown = (e) => {
    if (disabled) return;
    const k = e.key;

    if (k === 'Escape') {
      if (!open) return;
      // Nu lăsăm Escape să urce la fereastra din spate: întâi se închide lista,
      // abia la a doua apăsare se închide modalul cu formularul completat.
      e.preventDefault();
      e.stopPropagation();
      inchide();
      return;
    }

    if (k === 'ArrowDown' || k === 'ArrowUp') {
      e.preventDefault();
      if (!open) { deschide(); return; }
      const n = filtered.length;
      if (n === 0) return;
      setHi(h => {
        if (h < 0) return k === 'ArrowDown' ? 0 : n - 1;
        return k === 'ArrowDown' ? (h + 1) % n : (h - 1 + n) % n;
      });
      return;
    }

    if (k === 'Home' || k === 'End') {
      if (!open || filtered.length === 0) return;
      e.preventDefault();
      setHi(k === 'Home' ? 0 : filtered.length - 1);
      return;
    }

    if (k === 'Enter') {
      if (!open) { e.preventDefault(); deschide(); return; }
      if (hi >= 0 && filtered[hi] != null) { e.preventDefault(); handleSelect(filtered[hi]); }
      return;
    }

    // Spațiu deschide / alege doar pe varianta fără căutare — pe cea cu input
    // omul scrie numele țării, acolo spațiul e literă.
    if (k === ' ' && !searchable) {
      e.preventDefault();
      if (!open) deschide();
      else if (hi >= 0 && filtered[hi] != null) handleSelect(filtered[hi]);
      return;
    }

    if (k === 'Tab' && open) inchide();
  };

  const activeId = (open && hi >= 0 && filtered[hi] != null) ? (listId + '-opt-' + hi) : undefined;
  const ariaCombo = {
    role: 'combobox',
    'aria-expanded': open && !disabled,
    'aria-controls': listId,
    'aria-haspopup': 'listbox',
    'aria-activedescendant': activeId,
    onKeyDown,
  };

  const chevronStyle = {
    position: 'absolute', right: 14, top: 0, bottom: 0,
    display: 'flex', alignItems: 'center',
    pointerEvents: 'none',
    color: 'var(--txt-2)', fontSize: 10,
  };

  const triggerDivStyle = {
    width: '100%', paddingRight: 36,
    display: 'flex', alignItems: 'center',
    cursor: disabled ? 'not-allowed' : 'pointer',
    opacity: disabled ? 0.5 : 1,
  };

  const listStyle = {
    position: 'absolute', top: '100%', left: 0, right: 0, marginTop: 4,
    background: '#0a0a0a', border: '.5px solid var(--line)', borderRadius: 8,
    maxHeight: 220, overflowY: 'auto', overscrollBehavior: 'contain',
    zIndex: 50, boxShadow: '0 8px 24px rgba(0,0,0,.5)',
  };

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      {searchable && !disabled ? (
        <input
          {...ariaCombo}
          aria-autocomplete="list"
          className="input"
          value={query}
          onChange={e => { setQuery(e.target.value); setOpen(true); }}
          onClick={() => { if (!open) deschide(); }}
          onFocus={() => { if (!open) deschide(); }}
          placeholder={placeholder}
          autoComplete="off"
          style={{ width: '100%', paddingRight: 36, cursor: open ? 'text' : 'pointer' }}
        />
      ) : (
        <div
          {...ariaCombo}
          tabIndex={disabled ? -1 : 0}
          aria-disabled={disabled || undefined}
          onClick={() => !disabled && (open ? inchide() : deschide())}
          className="input"
          style={triggerDivStyle}
        >
          <span style={{ flex: 1, color: value ? 'var(--txt-0)' : 'var(--txt-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {value || placeholder}
          </span>
        </div>
      )}
      <span style={chevronStyle}>▼</span>

      {open && !disabled && (
        <div ref={listRef} id={listId} role="listbox" style={listStyle}>
          {filtered.length === 0 ? (
            <div style={{ padding: '10px 16px', fontSize: 13, color: 'var(--txt-3)' }}>Niciun rezultat</div>
          ) : filtered.map((opt, i) => {
            const isSel = opt === value;
            const isHi = i === hi;
            return (
              <div
                key={opt}
                id={listId + '-opt-' + i}
                data-cc-idx={i}
                role="option"
                aria-selected={isSel}
                // mousedown, nu click: pe varianta cu input, clicul ar muta întâi
                // focusul și ar închide lista prin ascultătorul din afară.
                onMouseDown={e => { e.preventDefault(); handleSelect(opt); }}
                onMouseEnter={() => setHi(i)}
                style={{
                  padding: '10px 16px', cursor: 'pointer', fontSize: 14,
                  color: isSel ? 'var(--accent-1)' : 'var(--txt-1)',
                  background: isSel
                    ? (isHi ? 'rgba(82,242,15,.16)' : 'rgba(82,242,15,.08)')
                    : (isHi ? 'rgba(255,255,255,.08)' : 'transparent'),
                  fontWeight: isSel ? 500 : 400,
                  // Marcaj vizibil și fără culoare, pentru opțiunea evidențiată.
                  boxShadow: isHi ? 'inset 2px 0 0 var(--accent-1)' : 'none',
                }}
              >
                {opt}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

// ─── CountryCascade ──────────────────────────────────────────────
const ALL_COUNTIES_OPTION = 'Toate județele';
const ALL_CITIES_OPTION = 'Toate orașele';

function CountryCascade({
  country, county, city,
  setCountry, setCounty, setCity,
  required = true,
  showLabels = true,
  allowClear = false,
}) {
  const [cityOther, setCityOther] = useStateCC(false);

  const isRO = country === 'România';
  const roCityList = (isRO && county) ? (window.GEO_DATA.ro_cities_by_county[county] || []) : [];
  const hasRoCities = roCityList.length > 0;

  // La schimbare județ/țară: detectează automat dacă orașul existent e în afara listei
  useEffectCC(() => {
    if (hasRoCities) {
      if (city && !roCityList.includes(city)) setCityOther(true);
      else setCityOther(false);
    } else {
      setCityOther(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [county, isRO]);

  const handleCountryChange = (val) => {
    if (val !== country) {
      setCounty('');
      setCity('');
      setCityOther(false);
    }
    setCountry(val);
  };

  const handleCountyChange = (val) => {
    if (allowClear && val === ALL_COUNTIES_OPTION) {
      setCounty('');
      setCity('');
      setCityOther(false);
      return;
    }
    setCounty(val);
    setCity('');
    setCityOther(false);
  };

  const handleCityChange = (val) => {
    if (allowClear && val === ALL_CITIES_OPTION) {
      setCityOther(false);
      setCity('');
      return;
    }
    if (val === 'Altul...') {
      setCityOther(true);
      setCity('');
    } else {
      setCityOther(false);
      setCity(val);
    }
  };

  const star = required ? ' *' : '';
  const labelStyle = { fontSize: 12, color: 'var(--txt-2)', fontWeight: 500, marginBottom: 6, display: 'block' };

  const countryOptions = useMemoCC(() => window.GEO_DATA.countries.map(c => c.name), []);
  const countyOptions = allowClear
    ? [ALL_COUNTIES_OPTION, ...window.GEO_DATA.ro_counties]
    : window.GEO_DATA.ro_counties;
  const cityOptions = hasRoCities
    ? (allowClear ? [ALL_CITIES_OPTION, ...roCityList, 'Altul...'] : [...roCityList, 'Altul...'])
    : [];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }} className="cc-grid">
      {/* TARA */}
      <div>
        {showLabels && <label style={labelStyle}>{'Țară' + star}</label>}
        <CustomDropdown
          value={country}
          onChange={handleCountryChange}
          options={countryOptions}
          placeholder="Selectează țara"
          searchable={true}
        />
      </div>

      {/* JUDET */}
      <div>
        {showLabels && <label style={labelStyle}>{isRO ? 'Județ' + star : 'Județ / Stat / Regiune'}</label>}
        {isRO ? (
          <CustomDropdown
            value={county}
            onChange={handleCountyChange}
            options={countyOptions}
            placeholder="Selectează județul"
            searchable={false}
          />
        ) : (
          <input
            className="input"
            value={county || ''}
            onChange={e => setCounty(e.target.value)}
            placeholder="ex: California, Bayern"
            autoComplete="off"
            style={{ width: '100%' }}
          />
        )}
      </div>

      {/* ORAS */}
      <div>
        {showLabels && <label style={labelStyle}>{isRO ? 'Oraș' + star : 'Oraș'}</label>}
        {hasRoCities ? (
          <>
            <CustomDropdown
              value={cityOther ? 'Altul...' : city}
              onChange={handleCityChange}
              options={cityOptions}
              placeholder="Selectează orașul"
              searchable={false}
            />
            {cityOther && (
              <input
                className="input"
                value={city || ''}
                onChange={e => setCity(e.target.value)}
                placeholder="Scrie numele orașului tău..."
                autoComplete="off"
                style={{ width: '100%', marginTop: 8 }}
              />
            )}
          </>
        ) : (
          <input
            className="input"
            value={city || ''}
            onChange={e => setCity(e.target.value)}
            placeholder={isRO ? 'Numele orașului' : 'Oraș'}
            autoComplete="off"
            style={{ width: '100%' }}
          />
        )}
      </div>

      <style>{`@media (max-width: 600px) { .cc-grid { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

window.CustomDropdown = CustomDropdown;
window.CountryCascade = CountryCascade;
