// City combobox — single searchable dropdown with country flag, country, tz.

const { useState: useStateC, useRef: useRefC, useEffect: useEffectC } = React;
const { CITIES, tzOffsetLabel } = window.JL;
const { Flag, haptic } = window.JLFX;

function CityCombo({ value, onChange, label, accent = '#7df9ff' }) {
  const [open, setOpen] = useStateC(false);
  const [query, setQuery] = useStateC('');
  const [hover, setHover] = useStateC(0);
  const wrapRef = useRefC(null);
  const inputRef = useRefC(null);
  const listRef = useRefC(null);

  useEffectC(() => {
    if (!open) return;
    const onDown = (e) => { if (!wrapRef.current?.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [open]);

  const q = query.trim().toLowerCase();
  const matches = q
    ? CITIES.filter(c => c.haystack.includes(q)).slice(0, 60)
    : CITIES.slice(0, 60);

  useEffectC(() => { setHover(0); }, [q]);
  useEffectC(() => {
    if (!open || !listRef.current) return;
    const node = listRef.current.querySelector(`[data-i="${hover}"]`);
    if (node) node.scrollIntoView({ block: 'nearest' });
  }, [hover, open]);

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setHover(h => Math.min(h + 1, matches.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setHover(h => Math.max(h - 1, 0)); }
    else if (e.key === 'Enter')   { e.preventDefault(); matches[hover] && pick(matches[hover]); }
    else if (e.key === 'Escape')  { setOpen(false); setQuery(''); inputRef.current?.blur(); }
  };

  const pick = (c) => {
    haptic(14);
    onChange(c);
    setQuery('');
    setOpen(false);
    inputRef.current?.blur();
  };

  return (
    <div ref={wrapRef} style={{ position: 'relative', width: '100%' }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 6 }}>
        <span style={{ fontSize: 10, color: accent, letterSpacing: '0.3em', fontWeight: 700 }}>{label}</span>
        {value && (
          <span style={{ fontSize: 10, color: 'rgba(255,255,255,.5)', letterSpacing: '0.15em' }}>
            UTC{tzOffsetLabel(value.tz)}
          </span>
        )}
      </div>

      <div style={{
        position: 'relative',
        background: 'rgba(255,255,255,0.04)',
        border: `1px solid ${open ? accent + 'aa' : 'rgba(255,255,255,0.14)'}`,
        borderRadius: 10,
        boxShadow: open ? `0 0 0 1px ${accent}55, 0 12px 32px rgba(0,0,0,0.45)` : 'none',
        transition: 'box-shadow .15s, border-color .15s',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px' }}>
          {value && !open && <Flag code={value.code} size={20} />}
          {open && (
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.6)" strokeWidth="2">
              <circle cx="11" cy="11" r="7" />
              <line x1="21" y1="21" x2="16.5" y2="16.5" strokeLinecap="round" />
            </svg>
          )}
          <input
            ref={inputRef}
            value={open ? query : (value ? `${value.name} · ${value.country}` : '')}
            placeholder={open ? 'Search city, country…' : 'Select a city'}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => { setOpen(true); setQuery(''); }}
            onKeyDown={onKey}
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: '#fafafa', fontSize: 14, fontFamily: 'inherit', minWidth: 0,
            }}
          />
          <svg width="10" height="10" viewBox="0 0 12 12" style={{
            fill: 'rgba(255,255,255,.5)', transition: 'transform .15s',
            transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
          }}>
            <path d="M2 4 L6 8 L10 4 Z" />
          </svg>
        </div>

        {open && (
          <div ref={listRef} style={{
            position: 'absolute', top: 'calc(100% + 6px)',
            left: 0, right: 0, zIndex: 60,
            background: '#14131c', border: '1px solid rgba(255,255,255,0.12)', borderRadius: 10,
            maxHeight: 280, overflowY: 'auto',
            boxShadow: '0 24px 48px rgba(0,0,0,0.5)',
            padding: '6px 0',
          }}>
            {matches.length === 0 && (
              <div style={{ padding: '12px 16px', color: 'rgba(255,255,255,.5)', fontSize: 13 }}>
                No matches for "{query}"
              </div>
            )}
            {matches.map((c, i) => {
              const isCurrent = value && value.tz === c.tz && value.name === c.name;
              return (
                <div key={`${c.name}-${c.tz}`} data-i={i}
                  className="jl-row"
                  onMouseEnter={() => setHover(i)}
                  onMouseDown={(e) => { e.preventDefault(); pick(c); }}
                  style={{
                    display: 'grid', gridTemplateColumns: '24px 1fr auto',
                    alignItems: 'center', gap: 12,
                    padding: '8px 14px', cursor: 'pointer',
                    background: i === hover ? 'rgba(255,255,255,0.08)' : 'transparent',
                    borderLeft: `2px solid ${isCurrent ? accent : 'transparent'}`,
                  }}>
                  <Flag code={c.code} size={20} />
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 14, color: '#fafafa', fontWeight: 500,
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {c.name}
                      <span style={{ color: 'rgba(255,255,255,.5)', fontWeight: 400 }}> · {c.country}</span>
                    </div>
                    <div style={{ fontSize: 10, color: 'rgba(255,255,255,.45)', marginTop: 1 }}>
                      {c.tz}
                    </div>
                  </div>
                  <span style={{ fontSize: 11, color: 'rgba(255,255,255,.55)',
                    fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                    UTC{tzOffsetLabel(c.tz)}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

window.CityCombo = CityCombo;
