/* global React, Ic, Input */

// ============================================================
// GlassDropdown — shared custom dropdown component
//
// Props:
//   value        — currently selected value (any)
//   onChange     — (value) => void
//   options      — [{ value, label, count?, hint? }]
//                  count — optional badge / right-aligned number
//                  hint  — optional secondary text under label
//   placeholder  — text shown when nothing is selected
//   searchable   — boolean (default: auto — true if options.length > 6)
//   searchPlaceholder — string
//   emptyLabel   — string shown when no options / filter empty
//   size         — 'md' | 'lg' (default 'md')
//   minWidth     — px number for popover min width
//   maxWidth     — px for popover (default 420)
//   badgeValue   — override count badge for the trigger (when value is set)
// ============================================================
function GlassDropdown({
  value,
  onChange,
  options,
  placeholder = 'Wybierz…',
  searchable,
  searchPlaceholder = 'Szukaj…',
  emptyLabel = 'Brak opcji.',
  size = 'md',
  minWidth = 260,
  maxWidth = 420,
  badgeValue,
}) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const wrapRef = React.useRef(null);

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

  React.useEffect(() => {
    if (!open) setQ('');
  }, [open]);

  const opts = Array.isArray(options) ? options : [];
  const autoSearch = typeof searchable === 'boolean' ? searchable : opts.length > 6;
  const list = opts.filter((o) => !q || (o.label || '').toLowerCase().includes(q.toLowerCase()));
  const selected = opts.find((o) => o.value === value);

  const triggerFont = size === 'lg' ? 18 : 13;
  const triggerPad = size === 'lg' ? '8px 14px' : '6px 12px';

  return (
    <div ref={wrapRef} style={{ position: 'relative', display: 'inline-block', maxWidth: '100%' }}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: triggerPad,
          background: 'linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02))',
          backdropFilter: 'blur(14px) saturate(140%)',
          WebkitBackdropFilter: 'blur(14px) saturate(140%)',
          border: '1px solid var(--border-strong)',
          borderRadius: 'var(--r-md)',
          boxShadow: open
            ? '0 0 0 3px color-mix(in srgb, var(--fg) 10%, transparent), 0 8px 24px rgba(0,0,0,0.12)'
            : '0 1px 2px rgba(0,0,0,0.04), inset 0 1px 0 rgba(255,255,255,0.08)',
          color: 'var(--fg)',
          cursor: 'pointer',
          fontSize: triggerFont, fontWeight: 500, letterSpacing: '-0.01em',
          transition: 'box-shadow 0.15s, transform 0.1s',
          maxWidth: '100%',
          minWidth: size === 'lg' ? 200 : 160,
          fontFamily: 'inherit',
        }}
      >
        <span style={{
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
          color: selected ? 'var(--fg)' : 'var(--fg-muted)',
          flex: 1, textAlign: 'left',
        }}>
          {selected ? selected.label : placeholder}
        </span>
        {selected && (badgeValue != null ? badgeValue : selected.count) != null && (badgeValue != null ? badgeValue : selected.count) > 0 && (
          <span className="mono" style={{
            fontSize: 10.5, fontWeight: 500,
            padding: '2px 8px', borderRadius: 999,
            background: 'var(--ok-weak)', color: 'var(--ok)',
            border: '1px solid var(--ok-border)',
            letterSpacing: '0.03em',
          }}>
            {badgeValue != null ? badgeValue : selected.count}
          </span>
        )}
        <span style={{
          display: 'inline-flex', color: 'var(--fg-subtle)',
          transform: open ? 'rotate(180deg)' : 'rotate(0deg)',
          transition: 'transform 0.15s',
        }}>
          <Ic.chevronDown size={14} />
        </span>
      </button>

      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', left: 0,
          minWidth, maxWidth,
          maxHeight: 400, overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
          background: 'color-mix(in srgb, var(--surface) 85%, transparent)',
          backdropFilter: 'blur(22px) saturate(160%)',
          WebkitBackdropFilter: 'blur(22px) saturate(160%)',
          border: '1px solid var(--border-strong)',
          borderRadius: 'var(--r-md)',
          boxShadow: '0 12px 40px rgba(0,0,0,0.18), 0 2px 6px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.1)',
          zIndex: 50,
        }}>
          {autoSearch && (
            <div style={{ padding: 8, borderBottom: '1px solid var(--hairline)' }}>
              <Input
                icon={<Ic.search size={12} />}
                placeholder={searchPlaceholder}
                value={q}
                onChange={(e) => setQ(e.target.value)}
                autoFocus
              />
            </div>
          )}
          <div style={{ overflowY: 'auto', flex: 1, padding: 4 }}>
            {list.length === 0 && (
              <div style={{ padding: 16, textAlign: 'center', fontSize: 12, color: 'var(--fg-muted)' }}>
                {emptyLabel}
              </div>
            )}
            {list.map((o) => {
              const active = o.value === value;
              const hasCount = typeof o.count === 'number';
              const dim = hasCount && o.count === 0;
              return (
                <div
                  key={String(o.value)}
                  onClick={() => { onChange(o.value); setOpen(false); }}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '9px 10px',
                    borderRadius: 'var(--r-sm)',
                    cursor: 'pointer',
                    background: active ? 'var(--surface)' : 'transparent',
                    border: active ? '1px solid var(--border-strong)' : '1px solid transparent',
                  }}
                  onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--bg-sunken)'; }}
                  onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
                >
                  {hasCount && (
                    <span style={{
                      width: 6, height: 6, borderRadius: '50%',
                      background: dim ? 'var(--fg-subtle)' : 'var(--ok)',
                      opacity: dim ? 0.5 : 1,
                      flexShrink: 0,
                    }} />
                  )}
                  <span style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 2 }}>
                    <span style={{
                      fontSize: 13, fontWeight: active ? 500 : 400,
                      color: dim ? 'var(--fg-muted)' : 'var(--fg)',
                      overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>
                      {o.label}
                    </span>
                    {o.hint && (
                      <span className="mono" style={{
                        fontSize: 10.5, color: 'var(--fg-subtle)',
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                      }}>
                        {o.hint}
                      </span>
                    )}
                  </span>
                  {hasCount && (
                    <span className="mono" style={{
                      fontSize: 10.5,
                      color: dim ? 'var(--fg-subtle)' : 'var(--fg-muted)',
                    }}>
                      {o.count}
                    </span>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

window.GlassDropdown = GlassDropdown;
