/* global React */
const { useState, useRef, useEffect } = React;

/**
 * FilterBar — sticky top bar with search input + category dropdown.
 * Visual language: Prompt — sharp corners, hairline borders, yellow accent on focus.
 *
 * Props:
 *   query, setQuery        : string state for the search input
 *   category, setCategory  : current category, setter (string, default "All")
 *   categories             : array of category names (without "All")
 *   resultCount            : number — shown subtly on the right
 *   onClear                : optional — called when both query and category are reset
 */
function FilterBar({ query, setQuery, category, setCategory, categories, resultCount }) {
  const [open, setOpen] = useState(false);
  const lang = (typeof localStorage !== 'undefined' && localStorage.getItem('lang')) || 'en';
  const dict = (window.I18N && window.I18N[lang]) || {};
  const tt = (k, fb) => dict[k] != null ? dict[k] : fb;
  const dropRef = useRef(null);

  useEffect(() => {
    if (!open) return;
    const onDown = (e) => {
      if (dropRef.current && !dropRef.current.contains(e.target)) setOpen(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [open]);

  const allLabel = tt('categoryAll', 'All');
  const allOpts = [{ value: 'All', label: allLabel }, ...categories.map(c => ({ value: c, label: c }))];
  const isFiltered = query.trim() !== '' || category !== 'All';

  return (
    <div
      style={{
        position: 'sticky',
        top: 0,
        zIndex: 50,
        background: 'rgba(255, 255, 255, 0.92)',
        backdropFilter: 'saturate(140%) blur(10px)',
        WebkitBackdropFilter: 'saturate(140%) blur(10px)',
        borderBottom: '1px solid var(--prompt-light-gray)',
      }}
    >
      <div
        style={{
          maxWidth: 1320,
          margin: '0 auto',
          padding: '0 clamp(20px, 4vw, 56px)',
        }}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'stretch',
            gap: 0,
            height: 64,
          }}
        >
          {/* Search input */}
          <div
            style={{
              flex: 1,
              display: 'flex',
              alignItems: 'center',
              gap: 14,
              borderRight: '1px solid var(--prompt-light-gray)',
              paddingRight: 16,
            }}
          >
            <SearchIcon />
            <input
              type="text"
              placeholder={tt('searchPlaceholder', 'Search workflows…')}
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              style={{
                flex: 1,
                border: 0,
                outline: 0,
                background: 'transparent',
                fontFamily: 'Poppins, Arial, sans-serif',
                fontSize: 15,
                fontWeight: 300,
                color: 'var(--prompt-black)',
                padding: '8px 0',
                letterSpacing: '-0.005em',
              }}
            />
            {query && (
              <button
                onClick={() => setQuery('')}
                aria-label={tt('clearSearch', 'Clear search')}
                style={iconBtn}
                onMouseEnter={(e) => (e.currentTarget.style.color = 'var(--prompt-black)')}
                onMouseLeave={(e) => (e.currentTarget.style.color = 'var(--prompt-gray)')}
              >
                ✕
              </button>
            )}
          </div>

          {/* Category dropdown */}
          <div
            ref={dropRef}
            style={{ position: 'relative', display: 'flex', alignItems: 'stretch' }}
          >
            <button
              onClick={() => setOpen((v) => !v)}
              style={{
                ...dropTrigger,
                color: 'var(--prompt-black)',
                background: open ? 'var(--prompt-paper)' : 'transparent',
              }}
            >
              <span
                style={{
                  fontSize: 10,
                  letterSpacing: '0.18em',
                  textTransform: 'uppercase',
                  fontWeight: 600,
                  color: 'var(--prompt-gray)',
                  marginRight: 12,
                }}
              >
                {tt('category', 'Category')}
              </span>
              <span
                style={{
                  fontSize: 14,
                  fontWeight: 500,
                  letterSpacing: '-0.005em',
                  color: 'var(--prompt-black)',
                }}
              >
                {category === 'All' ? allLabel : category}
              </span>
              <Caret open={open} />
            </button>

            {open && (
              <div
                style={{
                  position: 'absolute',
                  top: '100%',
                  right: 0,
                  minWidth: 220,
                  background: 'var(--prompt-white)',
                  border: '1px solid var(--prompt-black)',
                  borderTop: 0,
                  zIndex: 60,
                  boxShadow: '0 12px 32px rgba(20,23,28,0.08)',
                  animation: 'fb-drop 140ms cubic-bezier(0.2,0.6,0.2,1)',
                }}
              >
                {allOpts.map((c) => {
                  const active = c.value === category;
                  return (
                    <button
                      key={c.value}
                      onClick={() => {
                        setCategory(c.value);
                        setOpen(false);
                      }}
                      style={{
                        display: 'flex',
                        width: '100%',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        padding: '14px 18px',
                        background: active ? 'var(--prompt-yellow)' : 'transparent',
                        border: 0,
                        borderBottom: '1px solid var(--prompt-light-gray)',
                        cursor: 'pointer',
                        fontFamily: 'Poppins, Arial, sans-serif',
                        fontSize: 13,
                        fontWeight: active ? 600 : 400,
                        color: 'var(--prompt-black)',
                        textAlign: 'left',
                        letterSpacing: '-0.005em',
                      }}
                      onMouseEnter={(e) => {
                        if (!active) e.currentTarget.style.background = 'var(--prompt-paper)';
                      }}
                      onMouseLeave={(e) => {
                        if (!active) e.currentTarget.style.background = 'transparent';
                      }}
                    >
                      <span>{c.label}</span>
                      {active && (
                        <span style={{ fontSize: 11, fontWeight: 700 }}>✓</span>
                      )}
                    </button>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>

      <style>{`
        @keyframes fb-drop {
          from { opacity: 0; transform: translateY(-4px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        input::placeholder { color: var(--prompt-gray); font-weight: 300; }
      `}</style>
    </div>
  );
}

const iconBtn = {
  background: 'transparent',
  border: 0,
  color: 'var(--prompt-gray)',
  cursor: 'pointer',
  fontSize: 14,
  padding: '4px 6px',
  fontFamily: 'inherit',
  transition: 'color 160ms',
};

const dropTrigger = {
  display: 'flex',
  alignItems: 'center',
  border: 0,
  cursor: 'pointer',
  padding: '0 18px 0 24px',
  fontFamily: 'Poppins, Arial, sans-serif',
  height: '100%',
  transition: 'background 140ms',
};

function SearchIcon() {
  return (
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <circle cx="7" cy="7" r="5" stroke="var(--prompt-charcoal)" strokeWidth="1.5" />
      <line x1="11" y1="11" x2="14.5" y2="14.5" stroke="var(--prompt-charcoal)" strokeWidth="1.5" strokeLinecap="square" />
    </svg>
  );
}

function Caret({ open }) {
  return (
    <svg
      width="10"
      height="10"
      viewBox="0 0 10 10"
      fill="none"
      style={{
        marginLeft: 14,
        transform: open ? 'rotate(180deg)' : 'rotate(0)',
        transition: 'transform 160ms cubic-bezier(0.2,0.6,0.2,1)',
      }}
      aria-hidden="true"
    >
      <path d="M2 3.5 L5 6.5 L8 3.5" stroke="var(--prompt-black)" strokeWidth="1.5" strokeLinecap="square" />
    </svg>
  );
}

window.FilterBar = FilterBar;
