/* global React */
const { useState: useStateNP, useMemo: useMemoNP } = React;

function NationCard({ team, selected, onClick }) {
  const primary = team.pattern.colors[0];
  const secondary = team.pattern.colors[1] || primary;
  return (
    <button
      onClick={onClick}
      style={{
        position: 'relative',
        height: 80,
        borderRadius: 12,
        overflow: 'hidden',
        background: `linear-gradient(180deg, ${primary} 0%, ${primary} 50%, ${secondary} 50%, ${secondary} 100%)`,
        cursor: 'pointer',
        border: selected ? '2px solid #fff' : '2px solid transparent',
        boxShadow: selected ? '0 0 0 3px #1c2127' : 'none',
        transition: 'all .12s ease',
        padding: 0,
        width: '100%',
      }}
    >
      <div style={{
        position: 'absolute', inset: 0,
        background: 'linear-gradient(180deg, transparent 40%, rgba(0,0,0,0.5) 100%)',
      }} />
      <div style={{
        position: 'absolute', top: 6, left: 8,
        fontFamily: 'var(--mono)', fontSize: 10, color: '#fff', opacity: 0.9, letterSpacing: '0.15em',
      }}>
        {team.isoCode}
      </div>
      <div style={{
        position: 'absolute', top: 6, right: 8,
        fontFamily: 'var(--mono)', fontSize: 9, color: '#fff', opacity: 0.7, letterSpacing: '0.15em',
      }}>
        {team.groupLetter}
      </div>
      <div style={{
        position: 'absolute', bottom: 8, left: 8, right: 8,
        textAlign: 'left',
      }}>
        <span className="display" style={{
          fontSize: 14, color: '#fff', textShadow: '0 1px 2px rgba(0,0,0,0.5)', lineHeight: 0.95,
        }}>
          {team.name}
        </span>
      </div>
      {selected && (
        <div style={{
          position: 'absolute', top: 26, right: 8,
          width: 18, height: 18, borderRadius: '50%', background: '#fff',
          display: 'grid', placeItems: 'center',
        }}>
          <svg width="10" height="8" viewBox="0 0 11 9">
            <path d="M1 4.5l3 3 6-6" stroke="#111" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </div>
      )}
    </button>
  );
}

function NationPicker({ teams, selectedId, onSelect }) {
  const [search, setSearch] = useStateNP('');
  const initialGroup = useMemoNP(() => {
    if (!selectedId) return 'A';
    const t = teams.find((x) => x.id === selectedId);
    return t?.groupLetter || 'A';
  }, [teams, selectedId]);
  const [group, setGroup] = useStateNP(initialGroup);

  const filtered = useMemoNP(() => {
    if (!search.trim()) return [];
    const q = search.trim().toLowerCase();
    return teams
      .filter((t) =>
        t.name.toLowerCase().includes(q) ||
        t.isoCode.toLowerCase().includes(q) ||
        t.slug.includes(q.replace(/\s+/g, '-'))
      )
      .slice(0, 12);
  }, [search, teams]);

  const grouped = useMemoNP(() => teams.filter((t) => t.groupLetter === group), [teams, group]);
  const groupLetters = ['A','B','C','D','E','F','G','H','I','J','K','L'];

  const showSearch = search.trim().length > 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <input
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Search nation…"
        autoCapitalize="off" autoCorrect="off"
        style={{
          width: '100%', height: 44, padding: '0 14px',
          background: 'var(--bg-2)', border: '1.5px solid var(--line)',
          borderRadius: 12, color: 'var(--ink)',
          fontFamily: 'var(--sans)', fontSize: 14,
        }}
      />

      {!showSearch && (
        <div style={{ display: 'flex', gap: 4, overflowX: 'auto', paddingBottom: 4 }}>
          {groupLetters.map((g) => (
            <button
              key={g}
              onClick={() => setGroup(g)}
              style={{
                flexShrink: 0,
                padding: '6px 10px', borderRadius: 999,
                background: group === g ? 'var(--ink)' : 'var(--bg-2)',
                color: group === g ? '#111' : 'var(--ink-2)',
                fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 700,
                letterSpacing: '0.15em',
                border: 'none',
              }}
            >
              {g}
            </button>
          ))}
        </div>
      )}

      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8,
        maxHeight: 280, overflowY: 'auto',
      }}>
        {(showSearch ? filtered : grouped).map((t) => (
          <NationCard key={t.id} team={t} selected={selectedId === t.id} onClick={() => onSelect(t.id)} />
        ))}
        {showSearch && filtered.length === 0 && (
          <div style={{
            gridColumn: '1 / -1',
            padding: 20, textAlign: 'center',
            color: 'var(--ink-3)', fontSize: 13, fontFamily: 'var(--sans)',
          }}>
            No nation matches "{search}"
          </div>
        )}
      </div>
    </div>
  );
}

window.NationPicker = NationPicker;
