/* ============================================================
   P&L App (Lite) · Shared UI (from the US demo)
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ---------- Card ---------- */
function Card({ className = '', children, ...rest }) {
  return (
    <div className={`bg-surface rounded-2xl border border-line shadow-card ${className}`} {...rest}>
      {children}
    </div>
  );
}

/* ---------- Button ---------- */
function Button({ variant = 'primary', size = 'md', icon, iconRight, children, className = '', ...rest }) {
  const base = 'inline-flex items-center justify-center gap-2 font-700 rounded-xl transition-all duration-150 select-none disabled:opacity-50 disabled:pointer-events-none whitespace-nowrap';
  const sizes = { sm: 'text-[13px] px-3 h-8', md: 'text-sm px-4 h-10', lg: 'text-[15px] px-5 h-11' };
  const variants = {
    primary: 'text-white',
    soft: 'bg-[#F1FBD4] text-primary hover:bg-[#DDF2C6]',
    ghost: 'text-muted hover:text-ink hover:bg-[#F1FBD4]',
    outline: 'border border-line text-ink bg-surface hover:bg-bg hover:border-[#D9DED5]',
    danger: 'bg-[#FBEAE8] text-neg hover:bg-[#F7DCD9]',
    dangerSolid: 'bg-neg text-white hover:brightness-95',
    pos: 'bg-[#F1FBD4] text-[#3D5A0E] hover:bg-[#DDF2C6]',
  };
  const style = variant === 'primary' ? { background: 'var(--primary)' } : undefined;
  return (
    <button
      className={`${base} ${sizes[size]} ${variants[variant]} ${className}`}
      style={style}
      onMouseEnter={e => { if (variant === 'primary') e.currentTarget.style.background = 'var(--primary-deep)'; }}
      onMouseLeave={e => { if (variant === 'primary') e.currentTarget.style.background = 'var(--primary)'; }}
      {...rest}
    >
      {icon && <Icon name={icon} size={size === 'sm' ? 15 : 17} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === 'sm' ? 15 : 17} />}
    </button>
  );
}

/* ---------- IconButton ---------- */
function IconButton({ icon, title, tone = 'muted', size = 16, onClick }) {
  const tones = {
    muted: 'text-muted hover:text-ink hover:bg-[#F1FBD4]',
    primary: 'text-primary hover:bg-[#F1FBD4]',
    pos: 'text-pos hover:bg-[#E6F4EA]',
    neg: 'text-neg hover:bg-[#FBEAE8]',
  };
  return (
    <button title={title} onClick={onClick}
      className={`inline-flex items-center justify-center w-8 h-8 rounded-lg transition-colors ${tones[tone]}`}>
      <Icon name={icon} size={size} />
    </button>
  );
}

/* ---------- KPI tile ---------- */
function KPI({ label, value, sub, tone = 'default', icon, accentDot }) {
  const toneColor = { default: 'var(--ink)', pos: 'var(--pos)', neg: 'var(--neg)', primary: 'var(--primary)' }[tone];
  const iconBg = {
    default: 'bg-[#F1FBD4] text-primary', pos: 'bg-[#E6F4EA] text-pos',
    neg: 'bg-[#FBEAE8] text-neg', primary: 'bg-[#F1FBD4] text-primary',
  }[tone];
  return (
    <Card className="p-5 relative overflow-hidden">
      <div className="flex items-start justify-between gap-3">
        <div className="text-[12.5px] font-medium text-muted tracking-tight flex items-center gap-1.5">
          {accentDot && <span className="w-1.5 h-1.5 rounded-full" style={{ background: 'var(--accent)' }} />}
          {label}
        </div>
        {icon && <span className={`inline-flex items-center justify-center w-8 h-8 rounded-lg ${iconBg}`}><Icon name={icon} size={17} /></span>}
      </div>
      <div className="mt-3 font-display font-700 text-[26px] leading-none num tracking-tight" style={{ color: toneColor }}>
        {value}
      </div>
      {sub && <div className="mt-2 text-[12.5px] text-muted num">{sub}</div>}
    </Card>
  );
}

/* ---------- Status pill ---------- */
function statusStyle(status) {
  const map = {
    'Received': { bg: '#F1FBD4', fg: '#3D5A0E', dot: '#5DB53A' },
    'Partly received': { bg: '#E3EEF8', fg: '#2B6CA3', dot: '#3E8FD0' },
    'Paid': { bg: '#F1FBD4', fg: '#3D5A0E', dot: '#5DB53A' },
    'Partly paid': { bg: '#E3EEF8', fg: '#2B6CA3', dot: '#3E8FD0' },
    'Pending': { bg: '#FBF1DC', fg: '#9A6B12', dot: '#D9A036' },
    'Unpaid': { bg: '#FBF1DC', fg: '#9A6B12', dot: '#D9A036' },
    'Overdue': { bg: '#FBEAE8', fg: '#B23A2C', dot: '#C0392B' },
  };
  return map[status] || { bg: '#EEF1EA', fg: '#7B847C', dot: '#9A93A8' };
}
function StatusPill({ status }) {
  const s = statusStyle(status);
  return (
    <span className="inline-flex items-center gap-1.5 px-2.5 h-6 rounded-full text-[12px] font-medium whitespace-nowrap"
      style={{ background: s.bg, color: s.fg }}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: s.dot }} />
      {status}
    </span>
  );
}

/* ---------- Inline status editor (pill with hidden native select) ---------- */
function InlineStatus({ value, options, onChange }) {
  const s = statusStyle(value);
  const [open, setOpen] = useState(false);
  const ref = React.useRef(null);
  return (
    <div ref={ref} className="relative inline-flex items-center group" data-tip title="Change status"
         onClick={e => { e.stopPropagation(); setOpen(o => !o); }}>
      <span className="inline-flex items-center gap-1.5 pl-2.5 pr-1.5 h-6 rounded-full text-[12px] font-medium whitespace-nowrap cursor-pointer transition-shadow group-hover:ring-2 group-hover:ring-[rgba(15,59,44,0.18)]"
        style={{ background: s.bg, color: s.fg }}>
        <span className="w-1.5 h-1.5 rounded-full" style={{ background: s.dot }} />
        {value}
        <Icon name="chevronDown" size={12} className="opacity-60" />
      </span>
      {/* the app's own list (pickers.jsx), not the browser's */}
      <PickFloat anchorRef={ref} open={open} onClose={() => setOpen(false)} width={190}>
        <DropdownList options={options} value={value} onPick={v => { setOpen(false); if (v !== value) onChange(v); }} />
      </PickFloat>
    </div>
  );
}

/* ---------- Badge ---------- */
function Badge({ children, tone = 'neg' }) {
  const tones = {
    neg: { background: 'var(--neg)', color: '#fff' },
    primary: { background: 'var(--primary)', color: '#fff' },
    soft: { background: '#F1FBD4', color: 'var(--primary)' },
  };
  return (
    <span className="inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[11px] font-700 num"
      style={tones[tone]}>{children}</span>
  );
}

/* ---------- Auto-tag ---------- */
function AutoTag() {
  return (
    <span className="inline-flex items-center gap-1 px-2 h-5 rounded-full text-[10.5px] font-medium"
      style={{ background: '#F1FBD4', color: 'var(--primary)' }}>
      <Icon name="sparkles" size={11} /> Read automatically
    </span>
  );
}

/* ---------- Review reason pill ---------- */
function ReviewPill({ reason }) {
  return (
    <span className="inline-flex items-center gap-1 px-2 h-6 rounded-full text-[11.5px] font-medium"
      style={{ background: '#FBEAE8', color: 'var(--neg)' }}>
      <Icon name="alert" size={12} /> {reason}
    </span>
  );
}

/* ---------- Form fields ---------- */
function Field({ label, hint, children, className = '', required, as }) {
  const Tag = as || 'label';          // a pick-or-add field holds buttons and its own search box: use as="div"
  return (
    <Tag className={`block ${className}`}>
      {label && <span className="block text-[12.5px] font-medium text-ink mb-1.5">{label}{required && <span className="text-neg"> *</span>}</span>}
      {children}
      {hint && <span className="block text-[11.5px] text-muted mt-1">{hint}</span>}
    </Tag>
  );
}
const inputCls = 'field-focus w-full h-10 px-3 rounded-xl border border-line bg-surface text-sm text-ink placeholder:text-[#9AA298] transition-all';

const inputClsSm = inputCls.replace('h-10', 'h-8').replace('text-sm', 'text-[13px]');   // the small size, used in the advanced filter card
function Input({ className = '', compact, ...rest }) {
  // a date opens the app's own calendar (pickers.jsx); onChange still receives { target: { value } } so callers did not change
  if (rest.type === 'date') return <DateField compact={compact} className={className} value={rest.value || ''} required={rest.required} min={rest.min} max={rest.max}
                                              onChange={v => rest.onChange && rest.onChange({ target: { value: v || '' } })} />;
  return <input className={`${compact ? inputClsSm : inputCls} ${className}`} {...rest} />;
}
function NumberInput({ className = '', compact, ...rest }) { return <input inputMode="decimal" className={`${compact ? inputClsSm : inputCls} num text-right ${className}`} {...rest} />; }
function Textarea({ className = '', ...rest }) { return <textarea className={`field-focus w-full px-3 py-2.5 rounded-xl border border-line bg-surface text-sm text-ink placeholder:text-[#9AA298] transition-all resize-none ${className}`} {...rest} />; }

/* The <option>s a Select was given, as { value, label } (fragments and arrays are opened up). */
function _optionsOf(children) {
  const out = [];
  React.Children.toArray(children).forEach(c => {
    if (!c || !c.props) return;
    if (c.type === React.Fragment) { out.push(..._optionsOf(c.props.children)); return; }
    const label = React.Children.toArray(c.props.children).join('');
    out.push({ value: c.props.value != null ? String(c.props.value) : label, label });
  });
  return out;
}
/* A dropdown in the app's own look (pickers.jsx), written like a <select>: <option> children,
   onChange gets { target: { value } }. Every list on the page goes through here. */
function Select({ value, onChange, children, className = '', placeholder, compact }) {
  const opts = _optionsOf(children);
  if (placeholder) opts.unshift({ value: '', label: placeholder, muted: true });
  return <Dropdown className={className} compact={compact} value={value == null ? '' : String(value)} options={opts} placeholder={placeholder}
                   onChange={v => onChange && onChange({ target: { value: v } })} />;
}

/* compact filter select with leading label */
function FilterSelect({ label, value, onChange, options, allLabel = 'All', width }) {
  const opts = [{ value: '', label: allLabel, muted: true }].concat(options.map(o => ({ value: o, label: o })));
  return <Dropdown compact prefix={label} width={width} menuWidth={240} value={value || ''} options={opts} onChange={onChange} />;
}

/* search box */
function SearchInput({ value, onChange, placeholder = 'Search…', width = 220 }) {
  return (
    <div className="relative" style={{ width }}>
      <Icon name="search" size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted pointer-events-none" />
      <input value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        className="field-focus w-full h-9 pl-9 pr-3 rounded-xl border border-line bg-surface text-[13px] text-ink placeholder:text-[#9AA298] transition-all" />
    </div>
  );
}

/* review toggle pill */
function ReviewToggle({ active, count, onClick }) {
  return (
    <button onClick={onClick}
      className="inline-flex items-center gap-2 h-9 px-3 rounded-xl text-[13px] font-medium transition-all border"
      style={active
        ? { background: 'var(--neg)', color: '#fff', borderColor: 'var(--neg)' }
        : { background: '#FBEAE8', color: 'var(--neg)', borderColor: 'transparent' }}>
      <span className="w-1.5 h-1.5 rounded-full" style={{ background: active ? '#fff' : 'var(--neg)' }} />
      To review
      <span className="inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[11px] font-700 num"
        style={active ? { background: 'rgba(255,255,255,0.25)', color: '#fff' } : { background: 'var(--neg)', color: '#fff' }}>{count}</span>
    </button>
  );
}

/* ---------- Modal ---------- */
function Modal({ open, onClose, title, subtitle, children, footer, width = 640, icon }) {
  useEffect(() => {
    if (!open) return;
    const h = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', h); document.body.style.overflow = ''; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center p-4 sm:p-8 fade-in" style={{ background: 'rgba(16,32,24,0.42)' }} onMouseDown={onClose}>
      <div className="w-full pop-in my-auto" style={{ maxWidth: width }} onMouseDown={e => e.stopPropagation()}>
        <div className="bg-surface rounded-2xl shadow-pop border border-line overflow-hidden">
          <div className="flex items-start justify-between gap-4 px-6 pt-5 pb-4 border-b border-line">
            <div className="flex items-start gap-3">
              {icon && <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-[#F1FBD4] text-primary shrink-0"><Icon name={icon} size={19} /></span>}
              <div>
                <h3 className="text-[17px] font-700 text-ink">{title}</h3>
                {subtitle && <p className="text-[12.5px] text-muted mt-0.5">{subtitle}</p>}
              </div>
            </div>
            <IconButton icon="x" title="Close" onClick={onClose} />
          </div>
          <div className="px-6 py-5 max-h-[68vh] overflow-y-auto scroll-area">{children}</div>
          {footer && <div className="px-6 py-4 border-t border-line bg-[#F6F8F3] flex items-center justify-end gap-2.5">{footer}</div>}
        </div>
      </div>
    </div>
  );
}

/* ---------- Side panel (opens from the right; used by Admin) ---------- */
function SidePanel({ open, onClose, title, subtitle, icon, children, width = 460 }) {
  useEffect(() => {
    if (!open) return;
    const h = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 fade-in" style={{ background: 'rgba(16,32,24,0.32)' }} onMouseDown={onClose}>
      <aside className="absolute right-0 top-0 h-full w-full bg-surface border-l border-line shadow-pop flex flex-col panel-in" style={{ maxWidth: width }} onMouseDown={e => e.stopPropagation()}>
        <div className="flex items-start justify-between gap-4 px-6 pt-5 pb-4 border-b border-line shrink-0">
          <div className="flex items-start gap-3">
            {icon && <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-[#F1FBD4] text-primary shrink-0"><Icon name={icon} size={19} /></span>}
            <div>
              <h3 className="text-[17px] font-700 text-ink">{title}</h3>
              {subtitle && <p className="text-[12.5px] text-muted mt-0.5">{subtitle}</p>}
            </div>
          </div>
          <IconButton icon="x" title="Close" onClick={onClose} />
        </div>
        <div className="px-6 py-5 flex-1 overflow-y-auto scroll-area">{children}</div>
      </aside>
    </div>
  );
}

/* ---------- Confirm dialog ---------- */
function ConfirmDialog({ open, onClose, onConfirm, title, message, confirmLabel = 'Confirm', cancelLabel = 'Cancel', danger = true }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 fade-in" style={{ background: 'rgba(16,32,24,0.42)' }} onMouseDown={onClose}>
      <div className="w-full max-w-[420px] pop-in" onMouseDown={e => e.stopPropagation()}>
        <div className="bg-surface rounded-2xl shadow-pop border border-line overflow-hidden">
          <div className="px-6 pt-6 pb-2 flex items-start gap-3.5">
            <span className="inline-flex items-center justify-center w-10 h-10 rounded-xl shrink-0"
              style={{ background: danger ? '#FBEAE8' : '#F1FBD4', color: danger ? 'var(--neg)' : 'var(--primary)' }}>
              <Icon name={danger ? 'alert' : 'check'} size={20} />
            </span>
            <div>
              <h3 className="text-[16px] font-700 text-ink">{title}</h3>
              <p className="text-[13px] text-muted mt-1 leading-relaxed">{message}</p>
            </div>
          </div>
          <div className="px-6 py-4 flex items-center justify-end gap-2.5">
            <Button variant="ghost" onClick={onClose}>{cancelLabel}</Button>
            <Button variant={danger ? 'dangerSolid' : 'primary'} onClick={() => { onConfirm(); onClose(); }}>{confirmLabel}</Button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------- Empty state ---------- */
function EmptyState({ icon = 'search', title, message, action }) {
  return (
    <div className="flex flex-col items-center justify-center text-center py-16 px-6">
      <span className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-[#F1FBD4] text-primary mb-4"><Icon name={icon} size={26} /></span>
      <h4 className="text-[15px] font-600 text-ink font-display">{title}</h4>
      {message && <p className="text-[13px] text-muted mt-1.5 max-w-[340px]">{message}</p>}
      {action && <div className="mt-5">{action}</div>}
    </div>
  );
}

/* ---------- Avatar ---------- */
function Avatar({ initials = 'AG', size = 36 }) {
  return (
    <span className="inline-flex items-center justify-center rounded-full font-600 text-white font-display"
      style={{ width: size, height: size, fontSize: size * 0.36, background: 'linear-gradient(135deg, #0F3B2C, #D1F470)' }}>
      {initials}
    </span>
  );
}

/* ---------- Section header inside views ---------- */
function SectionTitle({ title, sub, right }) {
  return (
    <div className="flex items-end justify-between gap-4 mb-4">
      <div>
        <h3 className="text-[15.5px] font-700 text-ink font-display">{title}</h3>
        {sub && <p className="text-[12.5px] text-muted mt-0.5">{sub}</p>}
      </div>
      {right}
    </div>
  );
}

/* ---------- Toast ---------- */
function Toast({ toast }) {
  if (!toast) return null;
  return (
    <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-[70] slide-in">
      <div className="flex items-center gap-3 pl-3 pr-4 min-h-[48px] py-2 max-w-[560px] rounded-xl bg-surface border border-line shadow-pop">
        <span className="inline-flex items-center justify-center w-7 h-7 rounded-lg"
          style={{ background: (toast.tone === 'review' || toast.tone === 'error') ? '#FBEAE8' : '#F1FBD4', color: (toast.tone === 'review' || toast.tone === 'error') ? 'var(--neg)' : 'var(--primary)' }}>
          <Icon name={toast.tone === 'error' ? 'alert' : toast.tone === 'review' ? 'sparkles' : 'check'} size={16} />
        </span>
        <span className="text-[13px] text-ink font-medium">{toast.msg}</span>
      </div>
    </div>
  );
}

/* ============================================================
   Filtre — doar desenul. Ce câmpuri există, ce condiții primesc și cum se
   potrivește un rând trăiește în filters.jsx. Nicio vedere nu are logică proprie.
   ============================================================ */

/* Starea filtrelor unui tabel, păstrată în memorie cât timp pagina e deschisă —
   deci trecerea Încasări → Plăți → Încasări nu o pierde. La reîncărcare pornește goală. */
function useFilterState(table) {
  const [state, setStateRaw] = useState(() => keptFilters(table) || newFilterState());
  const setState = next => {
    const v = typeof next === 'function' ? next(state) : next;
    keepFilters(table, v); setStateRaw(v);
  };
  return [state, setState];
}

/* PickOrAdd — a Notion-style field for names that must not be typed freely (supplier, client, category…).

   Click it: a small card opens with a search box. Type to narrow the list (names that START with what
   you typed come first, A to Z, accents and capitals ignored). Pick one. If nothing matches you are
   offered "+ Creează «…»"; if what you typed is only another SPELLING of a name that already exists
   ("DEDEMAN SRL" when "Dedeman" is there) it says so and picks the existing one — a second copy cannot
   be made by accident. Keyboard: arrows, Enter, Esc.

   value / onChange   the chosen name (a string; '' = nothing)
   options            the official names
   onCreate(name)     async; adds the name and RETURNS the official name to select (or null if it failed)
   allowCreate=false  pick only (e.g. projects)
   emptyLabel         when given, a first row that clears the field (for optional fields) */
function PickOrAdd({ value, options, onChange, onCreate, allowCreate = true, emptyLabel,
                     placeholder = 'Choose…', searchPlaceholder = 'Search or type…', createLabel = 'Create',
                     existsLabel = 'Already exists', noMatch = 'Nothing matches.',
                     cell = false, defaultOpen = false, onDismiss }) {
  // cell = used inside a table cell / side panel: shows plain text (no box) and floats the list over the page
  const [open, setOpen] = useState(!!defaultOpen);
  const anchorRef = React.useRef(null);
  const [q, setQ] = useState('');
  const [active, setActive] = useState(0);
  const [busy, setBusy] = useState(false);
  const typed = q.trim();
  const ranked = rankOptions(options, q);
  const same = typed ? findSameName(options, typed) : null;
  const exact = !!same && foldText(same) === foldText(typed);
  const showSameNotice = !!same && !exact;
  const canCreate = !!allowCreate && !!typed && !same && !!onCreate;
  // the rows, in order: [clear], [existing spelling notice], options…, [create]
  const rows = [];
  if (emptyLabel && !typed) rows.push({ kind: 'empty' });
  if (showSameNotice) rows.push({ kind: 'same', name: same });
  ranked.forEach(o => { if (!(showSameNotice && o === same)) rows.push({ kind: 'opt', name: o }); });
  if (canCreate) rows.push({ kind: 'create', name: typed });

  const close = () => { setOpen(false); setQ(''); setActive(0); if (onDismiss) onDismiss(); };
  const choose = async row => {
    if (!row) return;
    if (row.kind === 'empty') { onChange(''); close(); return; }
    if (row.kind === 'opt' || row.kind === 'same') { onChange(row.name); close(); return; }
    if (row.kind === 'create') {
      setBusy(true);
      const made = await onCreate(row.name);
      setBusy(false);
      if (made) { onChange(made); close(); }
    }
  };
  const onKey = e => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(i => Math.min(i + 1, rows.length - 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(i => Math.max(i - 1, 0)); }
    else if (e.key === 'Enter') { e.preventDefault(); choose(rows[Math.min(active, rows.length - 1)]); }
    else if (e.key === 'Escape') { e.preventDefault(); e.nativeEvent.stopPropagation(); close(); }
  };

  const list = (
    <div className="flex flex-col gap-1.5">
      <input autoFocus value={q} onChange={e => { setQ(e.target.value); setActive(0); }} onKeyDown={onKey} placeholder={searchPlaceholder}
             className="field-focus w-full h-8 px-2.5 rounded-lg border border-line bg-surface text-[13px] text-ink placeholder:text-[#9AA298]" />
      <div className="flex flex-col max-h-[240px] overflow-auto scroll-area">
        {rows.map((r, i) => (
          <button key={r.kind + ':' + (r.name || '') + i} type="button" disabled={busy}
                  onMouseEnter={() => setActive(i)} onClick={() => choose(r)}
                  className={'text-left px-2 py-1.5 rounded-lg text-[13px] text-ink flex items-center gap-2 ' + (i === active ? 'bg-[#F1FBD4]' : '')}>
            {r.kind === 'empty' && <span className="text-muted">{emptyLabel}</span>}
            {r.kind === 'opt' && <><span className="truncate flex-1">{r.name}</span>{r.name === value && <Icon name="check" size={13} className="text-primary shrink-0" />}</>}
            {r.kind === 'same' && <><span className="text-[11.5px] text-muted shrink-0">{existsLabel}:</span><span className="truncate font-medium">{r.name}</span></>}
            {r.kind === 'create' && <><Icon name="plus" size={13} className="text-primary shrink-0" /><span className="truncate">{createLabel} "{r.name}"</span></>}
          </button>
        ))}
        {rows.length === 0 && <span className="text-[12px] text-muted px-2 py-1.5">{noMatch}</span>}
      </div>
    </div>
  );

  if (cell) {
    return (
      <div ref={anchorRef} className="relative min-w-0">
        <span className="block truncate text-[13px] text-ink">{value ? value : <span className="text-[#9AA298]">{placeholder}</span>}</span>
        <FloatPanel anchorRef={anchorRef} open={open} onClose={close} width={280}>{list}</FloatPanel>
      </div>
    );
  }
  return (
    <div className="relative">
      <button type="button" onClick={() => (open ? close() : setOpen(true))}
        className="field-focus w-full h-10 pl-3 pr-9 rounded-xl border border-line bg-surface text-sm text-left text-ink transition-all cursor-pointer truncate">
        {value ? value : <span className="text-[#9AA298]">{placeholder}</span>}
      </button>
      <Icon name="chevronDown" size={15} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted pointer-events-none" />
      <Popover open={open} onClose={close} width="100%">{list}</Popover>
    </div>
  );
}

/* A panel that floats under an element and is drawn at the page root, so a scrolling table
   cannot clip it. Flips above the element when there is no room below. Closes on click outside / Esc. */
function FloatPanel({ anchorRef, open, onClose, width = 280, children }) {
  const ref = React.useRef(null);
  const [pos, setPos] = React.useState(null);
  React.useEffect(() => {   // an effect (not a layout effect): the anchor's ref is only attached after the children's layout effects
    if (!open || !anchorRef.current) { setPos(null); return; }
    const r = anchorRef.current.getBoundingClientRect();
    const below = window.innerHeight - r.bottom;
    const left = Math.max(8, Math.min(r.left, window.innerWidth - width - 12));
    setPos(below < 320 && r.top > below ? { bottom: window.innerHeight - r.top + 4, left } : { top: r.bottom + 4, left });
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    const away = e => { if (e.target.closest && e.target.closest('[data-pick-float]')) return; if (ref.current && !ref.current.contains(e.target)) onClose(); };   // a click in a floating list or calendar (pickers.jsx) is not "outside"
    const esc = e => { if (e.key === 'Escape') { e.stopPropagation(); onClose(); } };
    const t = setTimeout(() => document.addEventListener('mousedown', away, true), 0);
    document.addEventListener('keydown', esc);
    return () => { clearTimeout(t); document.removeEventListener('mousedown', away, true); document.removeEventListener('keydown', esc); };
  }, [open]);
  if (!open || !pos) return null;
  return ReactDOM.createPortal(
    <div ref={ref} className="rounded-xl border border-line bg-surface shadow-pop p-3 pop-in" style={{ position: 'fixed', zIndex: 80, ...pos, width }}>{children}</div>,
    document.body);
}

/* Click a value, edit it right there (like a Notion table). Enter or click away saves, Esc cancels.
   type: 'text' | 'number' | 'date' | 'pick' | 'select'.  `children` is how the value looks when not editing. */
function EditCell({ type = 'text', value, children, onSave, options, onCreate, allowCreate = true, emptyLabel,
                    placeholder = '—', required = false, className = '', align, optionLabels }) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState('');
  const skip = React.useRef(false);
  const start = e => { if (e) e.stopPropagation(); skip.current = false; setDraft(value == null ? '' : String(value)); setEditing(true); };
  const stop = () => { skip.current = true; setEditing(false); };
  const commit = async raw => {
    if (skip.current) return;
    skip.current = true; setEditing(false);
    let v;
    if (type === 'number') { v = parseFloat(String(raw).replace(',', '.')); if (!Number.isFinite(v)) return; }
    else {
      v = String(raw == null ? '' : raw).trim();
      if (type === 'date') { if (v && !/^\d{4}-\d{2}-\d{2}$/.test(v)) return; if (!v) { if (required) return; v = null; } }
      else if (required && !v) return;
    }
    const before = value == null ? (type === 'date' ? null : '') : value;
    if (v === before) return;
    await onSave(v);
  };
  const alignCls = align === 'right' ? 'text-right justify-end' : '';
  if (!editing) {
    return (
      <div role="button" tabIndex={0} onClick={start} onKeyDown={e => { if (e.key === 'Enter') start(e); }}
           className={`cell-edit rounded-md px-1.5 py-1 -mx-1.5 min-h-[28px] flex items-center cursor-text hover:bg-[#F1FBD4] focus:outline-none focus:bg-[#F1FBD4] transition-colors ${alignCls} ${className}`}>
        {children != null ? children : (value === '' || value == null ? <span className="text-[#9AA298]">{placeholder}</span> : value)}
      </div>
    );
  }
  if (type === 'pick') {
    return (
      <div className={`px-1.5 -mx-1.5 min-h-[28px] flex items-center rounded-md bg-[#F1FBD4] ${className}`} onClick={e => e.stopPropagation()}>
        <PickOrAdd cell defaultOpen value={value || ''} options={options || []} allowCreate={allowCreate} onCreate={onCreate} emptyLabel={emptyLabel}
                   onChange={v => { skip.current = true; setEditing(false); onSave(v); }} onDismiss={stop} />
      </div>
    );
  }
  if (type === 'date') {
    // the cell keeps looking like text; the calendar floats under it, already open (Notion style)
    return <CellPicker className={className} onCancel={stop} render={done => (
      <CalendarPanel value={value || ''} allowClear={!required} onPick={v => done(() => commit(v))} onClear={() => done(() => commit(''))} />
    )}>{children != null ? children : value}</CellPicker>;
  }
  if (type === 'select') {
    return <CellPicker className={className} onCancel={stop} width={220} render={done => (
      <DropdownList value={value} options={(options || []).map(o => ({ value: o, label: (optionLabels && optionLabels[o]) || o }))} onPick={v => done(() => commit(v))} />
    )}>{children != null ? children : value}</CellPicker>;
  }
  const cls = 'w-full h-8 px-2 rounded-md border border-primary bg-white text-[13px] text-ink focus:outline-none' + (type === 'number' ? ' num' + (align === 'right' ? ' text-right' : '') : '');
  const onKey = e => { if (e.key === 'Enter') { e.preventDefault(); commit(draft); } else if (e.key === 'Escape') { e.preventDefault(); e.nativeEvent.stopPropagation(); stop(); } };
  return (
    <input autoFocus type="text" inputMode={type === 'number' ? 'decimal' : undefined} className={cls}
           value={draft} onChange={e => setDraft(e.target.value)} onBlur={() => commit(draft)} onKeyDown={onKey} onClick={e => e.stopPropagation()} />
  );
}

/* A cell being edited with a floating picker (date or list): it shows its value, highlighted, and the
   picker under it. render(done) draws the picker; done(fn) closes it and then runs fn (the save). */
function CellPicker({ children, render, onCancel, className = '', width = 282 }) {
  const ref = React.useRef(null);
  const [open, setOpen] = useState(true);
  const done = fn => { setOpen(false); fn(); };
  return (
    <div ref={ref} onClick={e => e.stopPropagation()} className={`rounded-md px-1.5 py-1 -mx-1.5 min-h-[28px] flex items-center bg-[var(--lime-soft)] ${className}`}>
      {children}
      <PickFloat anchorRef={ref} open={open} onClose={() => { setOpen(false); onCancel(); }} width={width}>{render(done)}</PickFloat>
    </div>
  );
}

/* Un panou care se deschide la click și se închide la click oriunde în afara lui. */
function Popover({ open, onClose, children, align = 'left', width = 300 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const away = e => { if (e.target.closest && e.target.closest('[data-pick-float]')) return; if (ref.current && !ref.current.contains(e.target)) onClose(); };   // a click in a floating list or calendar (pickers.jsx) is not "outside"
    const esc = e => { if (e.key === 'Escape') onClose(); };
    const t = setTimeout(() => document.addEventListener('mousedown', away, true), 0);
    document.addEventListener('keydown', esc);
    return () => { clearTimeout(t); document.removeEventListener('mousedown', away, true); document.removeEventListener('keydown', esc); };
  }, [open]);
  if (!open) return null;
  return (
    <div ref={ref} className="absolute top-full mt-2 z-50 rounded-xl border border-line bg-surface shadow-pop p-3 pop-in"
         style={{ [align]: 0, width, maxWidth: 'calc(100vw - 32px)' }}>
      {children}
    </div>
  );
}

/* O listă cu bife și căutare — ca în Notion: scrii ca să restrângi lista, bifezi ce vrei,
   iar ce ai ales apare sus ca etichete mici. */
function TickList({ options, value, onChange }) {
  const [q, setQ] = useState('');
  const chosen = Array.isArray(value) ? value : [];
  const set = new Set(chosen);
  const needle = q.trim().toLowerCase();
  const shown = options.filter(o => String(o).toLowerCase().includes(needle));
  const toggle = (o, on) => { const n = new Set(set); on ? n.add(o) : n.delete(o); onChange([...n]); };
  return (
    <div className="flex flex-col gap-2">
      {chosen.length > 0 && (
        <div className="flex flex-wrap gap-1">
          {chosen.map(o => (
            <span key={o} className="inline-flex items-center gap-1 h-6 pl-2 pr-1 rounded-md text-[12px] text-ink" style={{ background: '#F1FBD4' }}>
              <span className="max-w-[160px] truncate">{o}</span>
              <button type="button" onClick={() => toggle(o, false)} className="text-muted hover:text-neg" title="Remove"><Icon name="x" size={12} /></button>
            </span>
          ))}
        </div>
      )}
      <SearchInput value={q} onChange={setQ} placeholder="Search the list…" width="100%" />
      <div className="max-h-[220px] overflow-auto scroll-area flex flex-col gap-0.5">
        {shown.map(o => (
          <label key={o} className="flex items-center gap-2 text-[13px] cursor-pointer px-1.5 py-1 rounded-lg hover:bg-[#F6F8F3]">
            <input type="checkbox" checked={set.has(o)} onChange={e => toggle(o, e.target.checked)} />
            <span className="truncate">{o}</span>
          </label>
        ))}
        {!shown.length && <span className="text-[12px] text-muted px-1.5 py-1">{options.length ? 'Nothing matches.' : 'Nothing to choose yet.'}</span>}
      </div>
      <div className="flex items-center justify-between text-[12px]">
        <button type="button" className="text-primary hover:underline disabled:opacity-40" disabled={!shown.length}
                onClick={() => onChange([...new Set([...chosen, ...shown])])}>Select all{needle ? ' (the ones found)' : ''}</button>
        <button type="button" className="text-muted hover:text-neg disabled:opacity-40" disabled={!chosen.length}
                onClick={() => onChange([])}>Clear selection</button>
      </div>
    </div>
  );
}

/* Schimbarea condiției unui filtru. Trecerea de la „este" (o valoare) la o condiție cu listă
   păstrează ce era ales. */
function withOp(field, filter, op) {
  const next = { ...filter, op, preset: undefined };
  if (field.type === 'enum' && isListOp(op) && !Array.isArray(next.value)) next.value = next.value ? [next.value] : [];
  return next;
}

/* Câmpul de valoare, ales după tipul câmpului. */
function FilterValue({ field, filter, onChange, compact }) {
  const set = patch => onChange({ ...filter, ...patch });
  const op = filter.op;
  if (op === 'is empty' || op === 'is not empty') return null;

  if (field.type === 'date') {
    return (
      <div className="flex flex-col gap-2">
        <div className="flex flex-wrap items-center gap-2">
          <Input compact={compact} type="date" className="min-w-[142px] flex-1 px-2" value={filter.preset ? '' : (filter.value || '')}
                 onChange={e => set({ preset: undefined, value: e.target.value })} />
          {op === 'between' && <>
            <span className="text-muted text-[12px] shrink-0 whitespace-nowrap">to</span>
            <Input compact={compact} type="date" className="min-w-[142px] flex-1 px-2" value={filter.preset ? '' : (filter.value2 || '')}
                   onChange={e => set({ preset: undefined, value2: e.target.value })} />
          </>}
        </div>
      </div>
    );
  }

  if (field.type === 'boolean') {
    return (
      <Select compact={compact} value={filter.value === true ? 'Yes' : filter.value === false ? 'No' : ''}
              onChange={e => set({ value: e.target.value === 'Yes' })}>
        <option value="Yes">Yes</option><option value="No">No</option>
      </Select>
    );
  }

  if (field.type === 'enum') {
    const opts = field.options ? field.options() : [];
    if (isListOp(op)) return <TickList options={opts} value={filter.value} onChange={v => set({ value: v })} />;
    return (
      <Select compact={compact} value={filter.value || ''} onChange={e => set({ value: e.target.value })} placeholder="Choose…">
        {opts.map(o => <option key={o} value={o}>{o}</option>)}
      </Select>
    );
  }

  if (field.type === 'number') {
    return (
      <div className="flex items-center gap-2">
        <NumberInput compact={compact} value={filter.value ?? ''} onChange={e => set({ value: e.target.value })} placeholder="0" />
        {op === 'between' && <>
          <span className="text-muted text-[12px]">and</span>
          <NumberInput compact={compact} value={filter.value2 ?? ''} onChange={e => set({ value2: e.target.value })} placeholder="0" />
        </>}
      </div>
    );
  }

  return <Input compact={compact} value={filter.value || ''} onChange={e => set({ value: e.target.value })} placeholder="Type…" autoFocus />;
}

function FilterEditor({ field, filter, onChange }) {
  return (
    <div className="flex flex-col gap-2.5">
      <div className="text-[12px] font-600 text-muted uppercase tracking-wide">{field.label}</div>
      {!(field.type === 'date' && filter.preset) && (
        <Select value={filter.op} onChange={e => onChange(withOp(field, filter, e.target.value))}>
          {conditionsFor(field, filter.op).map(c => <option key={c} value={c}>{OP_LABELS[c] || c}</option>)}
        </Select>
      )}
      <FilterValue field={field} filter={filter} onChange={onChange} />
    </div>
  );
}

function FilterChip({ table, filter, onChange, onRemove, startOpen }) {
  const [open, setOpen] = useState(!!startOpen);
  const field = fieldByKey(table, filter.key);
  if (!field) return null;
  const complete = isComplete(filter, field);
  return (
    <span className="relative inline-flex">
      <span className="inline-flex items-center h-8 rounded-lg border text-[12.5px] overflow-hidden"
            style={complete ? { borderColor: 'var(--primary)', background: '#F1FBD4' } : { borderColor: 'var(--line)', borderStyle: 'dashed' }}>
        <button type="button" onClick={() => setOpen(o => !o)} className="px-2.5 h-full text-ink"
                title={complete ? 'Click to change' : 'Not applied yet: finish filling it in'}>
          {complete ? describeFilter(filter, table) : <span className="text-muted">{field.label}: choose…</span>}
        </button>
        <button type="button" onClick={onRemove} className="px-1.5 h-full text-muted hover:text-neg" title="Remove filter">
          <Icon name="x" size={13} />
        </button>
      </span>
      <Popover open={open} onClose={() => setOpen(false)} width={field.type === 'date' ? 400 : field.type === 'enum' ? 320 : 280}>
        <FilterEditor field={field} filter={filter} onChange={onChange} />
      </Popover>
    </span>
  );
}

/* The field picker inside "Filtrează": a search box on top (type to narrow, Enter picks the first),
   the fields, and — like Notion — "Add advanced filter" at the bottom. */
function FieldPicker({ table, onPick, onAdvanced, showAdvanced }) {
  const [q, setQ] = useState('');
  const needle = q.trim().toLowerCase();
  const list = filterableFields(table).filter(f => f.key !== 'needsReview' && f.label.toLowerCase().includes(needle));
  return (
    <div className="flex flex-col gap-1.5">
      <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Filter by…"
             onKeyDown={e => { if (e.key === 'Enter' && list[0]) onPick(list[0]); }}
             className="field-focus w-full h-8 px-2.5 rounded-lg border border-line bg-surface text-[13px] text-ink placeholder:text-[#9AA298]" />
      <div className="flex flex-col max-h-[320px] overflow-auto scroll-area">
        {list.map(f => (
          <button key={f.key} type="button" onClick={() => onPick(f)}
            className="text-left px-2 py-1.5 rounded-lg text-[13px] text-ink hover:bg-[#F1FBD4]">{f.label}</button>
        ))}
        {!list.length && <span className="text-[12px] text-muted px-2 py-1.5">Nothing matches.</span>}
      </div>
      {showAdvanced && (
        <button type="button" onClick={onAdvanced}
                className="flex items-center gap-2 text-left px-2 py-1.5 border-t border-line text-[13px] text-ink hover:bg-[#F1FBD4] rounded-lg">
          <Icon name="plus" size={14} />Add advanced filter
        </button>
      )}
    </div>
  );
}

/* The whole toolbar for one table. `rows` = every row in the table (for the review count); the
   view draws its own visible rows.

   Filters can be seen two ways, but they are ONE list: tags (simple) or, in the advanced view,
   a small "N rules" pill that opens a card on top of the page (it never pushes the table down,
   and closes when you click outside — like Notion). The AND / OR switch applies to all of them. */
function FilterBar({ table, state, setState, rows, onDownload, downloadCount, right, searchPlaceholder = 'Search…' }) {
  const [picking, setPicking] = useState(false);
  const [rulesOpen, setRulesOpen] = useState(false);
  const [justAdded, setJustAdded] = useState(null);
  const filters = state.filters || [];
  const mode = state.mode === 'or' ? 'or' : 'and';
  const advanced = !!state.advanced;
  const reviewOn = reviewFilterOn(filters);
  const others = filters.filter(f => f.key !== 'needsReview');
  const anything = filters.length > 0 || !!state.q;
  const nRules = others.length;

  const add = field => {
    setState({ ...state, filters: [...filters, newFilter(field)] });
    setJustAdded(filters.length);
    setPicking(false);
    if (advanced) setRulesOpen(true);
  };
  const change = (i, f) => { const n = filters.slice(); n[i] = f; setState({ ...state, filters: n }); };
  const remove = i => setState({ ...state, filters: filters.filter((_, j) => j !== i) });
  const flipMode = () => setState({ ...state, mode: mode === 'or' ? 'and' : 'or' });
  // Switching to the advanced view starts with one EMPTY rule (inert until a value is chosen),
  // so the card is not blank — and nothing is filtered by surprise.
  const goAdvanced = () => {
    const first = filterableFields(table).filter(f => f.key !== 'needsReview')[0];
    const empty = first && (first.type === 'date' ? { key: first.key, op: 'between', value: '', value2: '' } : newFilter(first));
    setState({ ...state, advanced: true, filters: others.length || !empty ? filters : [...filters, empty] });
    setPicking(false); setRulesOpen(true);
  };
  const goSimple = () => { setState({ ...state, advanced: false }); setRulesOpen(false); };

  return (
    <div className="flex flex-col gap-2.5">
      <div className="flex flex-wrap items-center gap-2.5">
        <span className="relative inline-flex">
          <Button variant="outline" size="sm" icon="filter" onClick={() => setPicking(p => !p)}>Filter</Button>
          <Popover open={picking} onClose={() => setPicking(false)} width={240}>
            <FieldPicker table={table} onPick={add} onAdvanced={goAdvanced} showAdvanced={!advanced} />
          </Popover>
        </span>
        {advanced && (
          <span className="relative inline-flex">
            <button type="button" onClick={() => setRulesOpen(o => !o)}
                    className="inline-flex items-center gap-1.5 h-8 px-3 rounded-lg border text-[13px] font-medium text-ink whitespace-nowrap"
                    style={{ borderColor: 'var(--primary)', background: '#F1FBD4' }}>
              <Icon name="filter" size={14} />
              {nRules === 0 ? 'No rules' : nRules + ' ' + (nRules === 1 ? 'rule' : 'rules')}
              <Icon name="chevronDown" size={13} />
            </button>
            <Popover open={rulesOpen} onClose={() => setRulesOpen(false)} width={800}>
              <AdvancedRules table={table} state={state} setState={setState} onSimple={goSimple} />
            </Popover>
          </span>
        )}
        <SearchInput value={state.q || ''} onChange={q => setState({ ...state, q })} placeholder={searchPlaceholder} width={220} />
        <ReviewToggle active={reviewOn} count={filteredReviewCount(rows, state, table)}
                      onClick={() => setState({ ...state, filters: toggleReviewFilter(filters) })} />
        {anything && (
          <Button variant="ghost" size="sm" icon="refresh" onClick={() => setState({ filters: [], q: '', sort: state.sort, mode: 'and', advanced })}>
            Clear all filters
          </Button>
        )}
        <div className="ml-auto flex flex-wrap items-center gap-2.5">
          {onDownload && (
            <Button variant="outline" icon="download" onClick={onDownload} disabled={!downloadCount}
                    title="Download exactly the rows on screen">
              Download ({downloadCount})
            </Button>
          )}
          {right}
        </div>
      </div>
      {!advanced && others.length > 0 && (
        <div className="flex flex-wrap items-center gap-2">
          {filters.map((f, i) => f.key === 'needsReview' ? null : (
            <React.Fragment key={i + ':' + f.key}>
              {i !== filters.findIndex(x => x.key !== 'needsReview') && (
                <button type="button" onClick={flipMode} title="Switch between AND and OR"
                        className="text-[11px] font-600 text-muted hover:text-ink px-1">{mode === 'or' ? 'OR' : 'AND'}</button>
              )}
              <FilterChip table={table} filter={f} startOpen={i === justAdded}
                          onChange={nf => change(i, nf)} onRemove={() => remove(i)} />
            </React.Fragment>
          ))}
        </div>
      )}
    </div>
  );
}

/* A rule's value in the advanced card: for list fields a small button that opens the tick list;
   for the rest, the ordinary input (in its small size). */
function RuleValue({ field, filter, onChange }) {
  const [open, setOpen] = useState(false);
  if (field.type === 'enum' && isListOp(filter.op)) {
    const vals = Array.isArray(filter.value) ? filter.value : [];
    return (
      <span className="relative flex flex-1 min-w-0">
        <button type="button" onClick={() => setOpen(o => !o)}
                className="field-focus h-8 w-full min-w-0 px-2.5 rounded-lg border border-line bg-surface text-[13px] text-left truncate">
          {vals.length ? _listText(vals) : <span className="text-[#9AA298]">Choose…</span>}
        </button>
        <Popover open={open} onClose={() => setOpen(false)} width={320}>
          <TickList options={field.options ? field.options() : []} value={vals} onChange={v => onChange({ ...filter, value: v })} />
        </Popover>
      </span>
    );
  }
  return <div className="flex-1 min-w-0"><FilterValue compact field={field} filter={filter} onChange={onChange} /></div>;
}

/* The rules inside the advanced card: "Where … / And … / And …", with ONE AND / OR switch
   for all of them. Compact, like Notion's. */
function AdvancedRules({ table, state, setState, onSimple }) {
  const filters = state.filters || [];
  const mode = state.mode === 'or' ? 'or' : 'and';
  const fields = filterableFields(table).filter(f => f.key !== 'needsReview');
  const rules = filters.map((f, i) => ({ f, i })).filter(x => x.f.key !== 'needsReview');
  const change = (i, f) => { const n = filters.slice(); n[i] = f; setState({ ...state, filters: n }); };
  const remove = i => setState({ ...state, filters: filters.filter((_, j) => j !== i) });
  const add = () => setState({ ...state, filters: [...filters, newFilter(fields[0])] });
  const clear = () => setState({ ...state, filters: filters.filter(f => f.key === 'needsReview'), mode: 'and' });
  return (
    <div className="flex flex-col gap-1.5">
      {rules.length === 0 && <div className="text-[12.5px] text-muted px-1 py-1">No rules yet. Add the first rule.</div>}
      {rules.map(({ f, i }, n) => {
        const field = fieldByKey(table, f.key);
        if (!field) return null;
        return (
          <div key={i + ':' + f.key} className="flex items-center gap-1.5">
            <span className="w-[60px] shrink-0 text-[12.5px] text-muted">
              {n === 0 ? 'Where'
                : n === 1 ? (
                  <Select compact value={mode} onChange={e => setState({ ...state, mode: e.target.value })} className="w-[60px]">
                    <option value="and">And</option><option value="or">Or</option>
                  </Select>)
                : (mode === 'or' ? 'Or' : 'And')}
            </span>
            <Select compact value={f.key} onChange={e => change(i, newFilter(fieldByKey(table, e.target.value)))} className="w-[140px] shrink-0">
              {fields.map(x => <option key={x.key} value={x.key}>{x.label}</option>)}
            </Select>
            <Select compact value={f.op} onChange={e => change(i, withOp(field, f, e.target.value))} className="w-[132px] shrink-0">
              {conditionsFor(field, f.op).map(c => <option key={c} value={c}>{OP_LABELS[c] || c}</option>)}
            </Select>
            <RuleValue field={field} filter={f} onChange={nf => change(i, nf)} />
            <span className="shrink-0"><IconButton icon="x" title="Remove rule" onClick={() => remove(i)} /></span>
          </div>
        );
      })}
      <div className="flex items-center justify-between pt-1.5 mt-0.5 border-t border-line">
        <div className="flex items-center gap-0.5">
          <Button variant="ghost" size="sm" icon="plus" onClick={add}>Add rule</Button>
          {rules.length > 0 && <Button variant="ghost" size="sm" icon="x" onClick={clear}>Clear filter</Button>}
        </div>
        <button type="button" onClick={onSimple} className="text-[12px] text-muted hover:text-ink px-1">Simple filters</button>
      </div>
    </div>
  );
}

/* Un antet de coloană care sortează. Fiecare coloană poate, din același registru. */
function SortHeader({ sortKey, state, setState, children, align = 'left', className = '' }) {
  const cur = state.sort || DEFAULT_SORT;
  const on = cur.key === sortKey;
  const next = () => setState({ ...state, sort: { key: sortKey, dir: on && cur.dir === 'desc' ? 'asc' : 'desc' } });
  return (
    <th className={`font-600 py-3 ${align === 'right' ? 'text-right' : 'text-left'} ${className}`}>
      <button type="button" onClick={next} className={'inline-flex items-center gap-1 uppercase tracking-wide ' + (on ? 'text-ink' : 'hover:text-ink')}
              title="Sort by this column">
        {children}
        <span className="text-[9px]" style={{ opacity: on ? 1 : 0.3 }}>{on && cur.dir === 'asc' ? '▲' : '▼'}</span>
      </button>
    </th>
  );
}

Object.assign(window, {
  Card, Button, IconButton, KPI, StatusPill, statusStyle, InlineStatus, Badge, AutoTag, ReviewPill,
  Field, Input, NumberInput, Textarea, Select, FilterSelect, SearchInput, ReviewToggle,
  Modal, SidePanel, FloatPanel, EditCell, ConfirmDialog, EmptyState, Avatar, SectionTitle, Toast,
  Popover, useFilterState, FilterValue, FilterEditor, FilterChip, FilterBar, SortHeader, TickList, RuleValue, AdvancedRules, FieldPicker, withOp, PickOrAdd,
});
