/* global React, Card, Button, Input, Ic, VS, LoadingState, ErrorState */

// ============================================================
// SCHEMA PICKER — full-screen modal with grid of thumbnails
// ============================================================
function SchemaPicker({ currentId, onPick, onClose }) {
  const [list, setList] = React.useState(null);
  const [cats, setCats] = React.useState(null);
  const [err, setErr] = React.useState('');
  const [q, setQ] = React.useState('');
  const [cat, setCat] = React.useState(''); // '' = all

  React.useEffect(() => {
    VS.schemaLibrary()
      .then((r) => setList(r || []))
      .catch((e) => setErr(e.message));
    VS.schemaLibraryCategories()
      .then((r) => setCats(r || []))
      .catch(() => setCats([]));
  }, []);

  // ESC → close
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose && onClose(); }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);

  const filtered = React.useMemo(() => {
    if (!list) return [];
    const qq = (q || '').trim().toLowerCase();
    return list.filter((it) => {
      if (cat && (it.category || '') !== cat) return false;
      if (!qq) return true;
      return (
        (it.name || '').toLowerCase().includes(qq) ||
        (it.category || '').toLowerCase().includes(qq) ||
        (it.filename || '').toLowerCase().includes(qq)
      );
    });
  }, [list, q, cat]);

  function pick(item) {
    if (onPick) onPick(item.id, item.name);
    if (onClose) onClose();
  }

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(0,0,0,0.45)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: 'min(1100px, 100%)',
          maxHeight: 'calc(100vh - 48px)',
          background: 'var(--bg)',
          border: '1px solid var(--border)',
          borderRadius: 'var(--r-md)',
          boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
        }}
      >
        {/* Header */}
        <div style={{
          padding: '14px 18px',
          borderBottom: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          gap: 12, flexShrink: 0,
        }}>
          <div>
            <div className="uppercase-label" style={{ marginBottom: 4 }}>Biblioteka schematów</div>
            <div style={{ fontSize: 15, fontWeight: 500, letterSpacing: '-0.01em' }}>
              Wybierz schemat z biblioteki
            </div>
          </div>
          <button
            onClick={onClose}
            title="Zamknij"
            style={{
              width: 28, height: 28, padding: 0,
              background: 'transparent', border: '1px solid var(--border)',
              borderRadius: 'var(--r-sm)', cursor: 'pointer',
              color: 'var(--fg-muted)', fontSize: 16, lineHeight: 1,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
          >×</button>
        </div>

        {/* Toolbar: search + categories */}
        <div style={{
          padding: '12px 18px',
          borderBottom: '1px solid var(--hairline)',
          display: 'flex', flexDirection: 'column', gap: 10,
          flexShrink: 0,
        }}>
          <div style={{ maxWidth: 340 }}>
            <Input
              icon={<Ic.search size={13} />}
              placeholder="Szukaj po nazwie lub kategorii…"
              value={q}
              onChange={(e) => setQ(e.target.value)}
            />
          </div>
          {/* Category chips */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            <CategoryChip
              active={cat === ''}
              onClick={() => setCat('')}
              label="Wszystkie"
              count={list ? list.length : undefined}
            />
            {(cats || []).map((c) => (
              <CategoryChip
                key={c.category}
                active={cat === c.category}
                onClick={() => setCat(c.category)}
                label={c.category || '— bez kategorii —'}
                count={c.count}
              />
            ))}
          </div>
        </div>

        {/* Grid */}
        <div style={{
          flex: 1, overflowY: 'auto',
          padding: 18, background: 'var(--bg)',
        }}>
          {err && <ErrorState message={err} />}
          {!err && !list && <LoadingState />}
          {!err && list && list.length === 0 && (
            <div style={{
              padding: 48, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13,
            }}>
              <div className="uppercase-label" style={{ marginBottom: 6 }}>Biblioteka pusta</div>
              <div>Administrator może dodać schematy w Konfiguracji.</div>
            </div>
          )}
          {!err && list && list.length > 0 && filtered.length === 0 && (
            <div style={{
              padding: 48, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 13,
            }}>
              Brak wyników dla wybranych filtrów.
            </div>
          )}
          {!err && filtered.length > 0 && (
            <div style={{
              display: 'grid',
              gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
              gap: 14,
            }}>
              {filtered.map((it) => (
                <SchemaTile
                  key={it.id}
                  item={it}
                  selected={currentId === it.id}
                  onClick={() => pick(it)}
                />
              ))}
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{
          padding: '10px 18px',
          borderTop: '1px solid var(--border)',
          background: 'var(--bg-elev)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          flexShrink: 0,
        }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--fg-subtle)', letterSpacing: '0.04em' }}>
            {list ? `${filtered.length} / ${list.length} schematów` : ''}
          </span>
          <Button variant="ghost" onClick={onClose}>Anuluj</Button>
        </div>
      </div>
    </div>
  );
}

function CategoryChip({ active, onClick, label, count }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: '4px 10px',
        fontSize: 11.5,
        background: active ? 'var(--fg)' : 'var(--surface)',
        color: active ? 'var(--bg)' : 'var(--fg-muted)',
        border: '1px solid ' + (active ? 'var(--fg)' : 'var(--border-strong)'),
        borderRadius: 999,
        cursor: 'pointer',
        fontFamily: 'inherit',
        display: 'inline-flex', alignItems: 'center', gap: 6,
        whiteSpace: 'nowrap',
      }}
    >
      <span>{label}</span>
      {typeof count === 'number' && (
        <span className="mono" style={{
          fontSize: 10,
          color: active ? 'var(--bg)' : 'var(--fg-subtle)',
          opacity: 0.8,
        }}>{count}</span>
      )}
    </button>
  );
}

function SchemaTile({ item, selected, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'flex', flexDirection: 'column',
        background: 'var(--surface)',
        border: '1px solid ' + (selected ? 'var(--accent)' : hover ? 'var(--border-strong)' : 'var(--border)'),
        boxShadow: selected ? '0 0 0 2px var(--accent-weak)' : 'none',
        borderRadius: 'var(--r-sm)',
        overflow: 'hidden',
        cursor: 'pointer',
        transition: 'border-color 0.12s, box-shadow 0.12s',
      }}
    >
      <div style={{
        width: '100%', height: 140,
        background: 'var(--bg-sunken)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 8,
      }}>
        <img
          src={VS.schemaLibraryImageUrl(item.id)}
          alt={item.name || ''}
          loading="lazy"
          style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }}
          onError={(e) => { e.currentTarget.style.visibility = 'hidden'; }}
        />
      </div>
      <div style={{
        padding: '8px 10px',
        borderTop: '1px solid var(--hairline)',
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        <div style={{
          fontSize: 12, fontWeight: 500,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          color: 'var(--fg)',
        }} title={item.name || item.filename || ''}>
          {item.name || item.filename || '—'}
        </div>
        {item.category && (
          <div style={{
            fontSize: 9.5, letterSpacing: '0.06em', textTransform: 'uppercase',
            color: 'var(--fg-muted)',
            fontFamily: 'var(--font-mono)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          }} title={item.category}>
            {item.category}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SchemaPicker });
