// Queue interactions: filter popover, sort, bulk actions, saved views
const { useState: useStateQI, useRef: useRefQI, useEffect: useEffectQI } = React;

// Popover helper reused from ticket-actions.jsx style
const QueuePopover = ({ open, onClose, anchor, children, width = 300, align = 'left' }) => {
  const ref = useRefQI(null);
  useEffectQI(() => {
    if (!open) return;
    const handle = (e) => {
      if (ref.current && !ref.current.contains(e.target) && !anchor?.contains?.(e.target)) onClose();
    };
    document.addEventListener('mousedown', handle);
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', esc);
    return () => { document.removeEventListener('mousedown', handle); document.removeEventListener('keydown', esc); };
  }, [open, onClose, anchor]);
  if (!open || !anchor) return null;
  const rect = anchor.getBoundingClientRect();
  const left = align === 'right' ? rect.right - width : rect.left;
  return (
    <div ref={ref} style={{
      position: 'fixed', top: rect.bottom + 6, left, width,
      background: 'white', borderRadius: 12, border: '1px solid var(--border)',
      boxShadow: 'var(--shadow-lg)', zIndex: 90, animation: 'popIn 140ms ease',
      overflow: 'hidden',
    }}>
      {children}
    </div>
  );
};

// ---------- Filter popover ----------
const QueueFilterPopover = ({ open, onClose, anchor, filters, setFilters, onClear }) => {
  const urgencies = ['critical', 'high', 'normal', 'low'];
  const categories = ['Account access', 'Device', 'Software install', 'Network', 'Security', 'Clinical apps'];
  const times = [
    { id: 'any', label: 'Any time' },
    { id: '1h', label: 'Last 1h' },
    { id: '4h', label: 'Last 4h' },
    { id: '24h', label: 'Last 24h' },
  ];

  const toggle = (key, value) => {
    const arr = filters[key] || [];
    setFilters({ ...filters, [key]: arr.includes(value) ? arr.filter(v => v !== value) : [...arr, value] });
  };

  const activeCount = (filters.urgency?.length || 0) + (filters.category?.length || 0) + (filters.time && filters.time !== 'any' ? 1 : 0);

  return (
    <QueuePopover open={open} onClose={onClose} anchor={anchor} width={300}>
      <div style={{padding: '14px 16px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between'}}>
        <div>
          <div style={{fontSize: 13, fontWeight: 700}}>Filter queue</div>
          <div style={{fontSize: 11, color: 'var(--nyu-text)', marginTop: 2}}>{activeCount} active filter{activeCount !== 1 ? 's' : ''}</div>
        </div>
        {activeCount > 0 && <button onClick={onClear} style={{fontSize: 11, background: 'none', border: 'none', color: 'var(--nyu-purple)', cursor: 'pointer', fontWeight: 600}}>Clear all</button>}
      </div>

      <div style={{padding: '0 16px 12px'}}>
        <div style={{fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--nyu-text)', marginBottom: 6}}>Urgency</div>
        <div style={{display: 'flex', flexWrap: 'wrap', gap: 4}}>
          {urgencies.map(u => {
            const active = filters.urgency?.includes(u);
            const color = { critical: '#B00045', high: '#E85A00', normal: 'var(--nyu-purple)', low: 'var(--nyu-text)' }[u];
            return (
              <button key={u} onClick={() => toggle('urgency', u)} style={{
                padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 600, cursor: 'pointer',
                background: active ? color : 'white',
                color: active ? 'white' : color,
                border: `1px solid ${active ? color : 'var(--border)'}`,
                textTransform: 'capitalize',
              }}>{u}</button>
            );
          })}
        </div>
      </div>

      <div style={{padding: '0 16px 12px'}}>
        <div style={{fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--nyu-text)', marginBottom: 6}}>Category</div>
        <div style={{display: 'flex', flexWrap: 'wrap', gap: 4}}>
          {categories.map(c => {
            const active = filters.category?.includes(c);
            return (
              <button key={c} onClick={() => toggle('category', c)} style={{
                padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: active ? 600 : 500, cursor: 'pointer',
                background: active ? 'var(--purple-tint)' : 'white',
                color: active ? 'var(--nyu-purple)' : 'var(--nyu-text)',
                border: `1px solid ${active ? 'var(--nyu-purple)' : 'var(--border)'}`,
              }}>{c}</button>
            );
          })}
        </div>
      </div>

      <div style={{padding: '0 16px 14px'}}>
        <div style={{fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--nyu-text)', marginBottom: 6}}>Time window</div>
        <div style={{display: 'flex', gap: 4}}>
          {times.map(t => {
            const active = (filters.time || 'any') === t.id;
            return (
              <button key={t.id} onClick={() => setFilters({ ...filters, time: t.id })} style={{
                flex: 1, padding: '6px 4px', borderRadius: 6, fontSize: 11, fontWeight: active ? 700 : 500, cursor: 'pointer',
                background: active ? 'var(--nyu-purple)' : 'white',
                color: active ? 'white' : 'var(--nyu-text)',
                border: `1px solid ${active ? 'var(--nyu-purple)' : 'var(--border)'}`,
              }}>{t.label}</button>
            );
          })}
        </div>
      </div>
    </QueuePopover>
  );
};

// ---------- Sort menu ----------
const QueueSortMenu = ({ open, onClose, anchor, sort, setSort }) => {
  const opts = [
    { id: 'newest', label: 'Newest first', sub: 'Created time ↓' },
    { id: 'urgency', label: 'Urgency', sub: 'Critical → Low' },
    { id: 'sla', label: 'SLA due', sub: 'Closest deadline first' },
    { id: 'confidence', label: 'Agent confidence', sub: 'Lowest first' },
  ];
  return (
    <QueuePopover open={open} onClose={onClose} anchor={anchor} width={240} align="right">
      <div style={{padding: 6}}>
        {opts.map(o => (
          <button key={o.id}
            onClick={() => { setSort(o.id); onClose(); }}
            style={{
              width: '100%', padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 10,
              borderRadius: 8, cursor: 'pointer', textAlign: 'left',
              background: sort === o.id ? 'var(--purple-tint)' : 'transparent',
              border: 'none',
            }}>
            <div style={{flex: 1}}>
              <div style={{fontSize: 12, fontWeight: 600, color: sort === o.id ? 'var(--nyu-purple)' : 'var(--nyu-black)'}}>{o.label}</div>
              <div style={{fontSize: 10, color: 'var(--nyu-text)'}}>{o.sub}</div>
            </div>
            {sort === o.id && <Icon name="check" size={12} color="var(--nyu-purple)" strokeWidth={3}/>}
          </button>
        ))}
      </div>
    </QueuePopover>
  );
};

// ---------- Saved views bar ----------
const SavedViewsBar = ({ active, onSelect }) => {
  const views = [
    { id: 'my-day', label: 'My day', count: 3 },
    { id: 'phi-risk', label: 'PHI risk', count: 2 },
    { id: 'clinical', label: 'Clinical apps', count: 4 },
    { id: 'new-hires', label: 'New hires', count: 1 },
  ];
  return (
    <div style={{padding: '8px 10px 6px', borderBottom: '1px solid var(--border)'}}>
      <div style={{fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--nyu-text)', marginBottom: 6, padding: '0 4px'}}>Saved views</div>
      <div style={{display: 'flex', flexWrap: 'wrap', gap: 4}}>
        {views.map(v => (
          <button key={v.id} onClick={() => onSelect(v.id)} style={{
            fontSize: 11, padding: '4px 8px', borderRadius: 6,
            background: active === v.id ? 'var(--nyu-deep-purple)' : 'var(--nyu-gray-50)',
            color: active === v.id ? 'white' : 'var(--nyu-text)',
            border: 'none', cursor: 'pointer', fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            {v.label}
            <span style={{
              fontSize: 9, padding: '1px 5px', borderRadius: 999,
              background: active === v.id ? 'rgba(255,255,255,0.25)' : 'var(--nyu-gray-100)',
              color: active === v.id ? 'white' : 'var(--nyu-text)',
            }}>{v.count}</span>
          </button>
        ))}
        <button style={{
          fontSize: 11, padding: '4px 8px', borderRadius: 6,
          background: 'transparent', color: 'var(--nyu-text)',
          border: '1px dashed var(--border)', cursor: 'pointer', fontWeight: 500,
        }}>+ Save current</button>
      </div>
    </div>
  );
};

// ---------- Bulk action bar ----------
const BulkActionBar = ({ count, onClear, onAssign, onReassign, onArchive, onExport }) => {
  if (count === 0) return null;
  return (
    <div style={{
      padding: '10px 14px', borderBottom: '1px solid var(--border)',
      background: 'var(--nyu-deep-purple)', color: 'white',
      display: 'flex', alignItems: 'center', gap: 10,
      animation: 'slideDown 180ms ease',
    }}>
      <button onClick={onClear} style={{background: 'rgba(255,255,255,0.15)', color: 'white', border: 'none', width: 24, height: 24, borderRadius: 6, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
        <Icon name="x" size={12} color="white"/>
      </button>
      <span style={{fontSize: 12, fontWeight: 700, flex: 1}}>{count} selected</span>
      <button onClick={onAssign} title="Assign to Violet" style={{background: 'rgba(255,255,255,0.15)', color: 'white', border: 'none', padding: '5px 8px', borderRadius: 6, cursor: 'pointer', fontSize: 11, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4}}>
        <Icon name="violet" size={11} color="white"/> Violet
      </button>
      <button onClick={onReassign} title="Reassign" style={{background: 'rgba(255,255,255,0.15)', color: 'white', border: 'none', padding: '5px 8px', borderRadius: 6, cursor: 'pointer', fontSize: 11, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4}}>
        <Icon name="route" size={11} color="white"/> Route
      </button>
      <button onClick={onExport} title="Export" style={{background: 'rgba(255,255,255,0.15)', color: 'white', border: 'none', padding: '5px 8px', borderRadius: 6, cursor: 'pointer', fontSize: 11, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4}}>
        <Icon name="download" size={11} color="white"/> Export
      </button>
      <button onClick={onArchive} title="Archive" style={{background: 'rgba(255,255,255,0.15)', color: 'white', border: 'none', padding: '5px 8px', borderRadius: 6, cursor: 'pointer', fontSize: 11, fontWeight: 600}}>
        <Icon name="inbox" size={11} color="white"/>
      </button>
      <style>{`@keyframes slideDown { from { max-height: 0; opacity: 0; } to { max-height: 60px; opacity: 1; } }`}</style>
    </div>
  );
};

// ---------- Row with checkbox (for bulk) ----------
const BulkTicketRow = ({ ticket, selected, onClick, checked, onToggleCheck, anySelected }) => {
  const user = USERS[ticket.user];
  return (
    <div
      onClick={(e) => { if (e.target.tagName !== 'INPUT' && !e.target.closest('[data-checkbox]')) onClick(); }}
      style={{
        padding: '12px 14px 12px 10px',
        borderBottom: '1px solid var(--border)',
        cursor: 'pointer',
        background: selected ? 'var(--purple-tint)' : checked ? 'var(--purple-tint)' : 'transparent',
        borderLeft: selected ? '3px solid var(--nyu-purple)' : '3px solid transparent',
        transition: 'background 100ms',
        display: 'flex', gap: 8,
      }}
      onMouseEnter={e => { if (!selected && !checked) e.currentTarget.style.background = 'var(--nyu-gray-50)'; }}
      onMouseLeave={e => { if (!selected && !checked) e.currentTarget.style.background = 'transparent'; }}
    >
      <div data-checkbox style={{
        width: 16, marginTop: 3, flexShrink: 0,
        opacity: anySelected || checked ? 1 : 0.3,
        transition: 'opacity 120ms',
      }}>
        <input type="checkbox" checked={checked} onChange={onToggleCheck}
          onClick={e => e.stopPropagation()}
          style={{accentColor: 'var(--nyu-purple)', cursor: 'pointer', width: 14, height: 14}}/>
      </div>
      <div style={{flex: 1, minWidth: 0}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4}}>
          {urgencyDot(ticket.urgency)}
          <span className="mono" style={{fontSize: 11, color: 'var(--nyu-text)'}}>{ticket.id}</span>
          <span style={{marginLeft: 'auto', fontSize: 11, color: 'var(--nyu-text)'}}>{relTime(ticket.createdAt)}</span>
        </div>
        <div style={{fontSize: 13.5, fontWeight: 600, color: 'var(--nyu-black)', marginBottom: 4, lineHeight: 1.3}}>
          {ticket.subject}
        </div>
        <div style={{fontSize: 12, color: 'var(--nyu-text)', marginBottom: 6}}>
          {user?.name} · {user?.dept}
        </div>
        <div style={{display: 'flex', gap: 6, flexWrap: 'wrap'}}>
          {statusChip(ticket)}
        </div>
      </div>
    </div>
  );
};

// Helpers reference shared utilities
const { urgencyDot, statusChip, relTime } = window.TechConsoleShared;

Object.assign(window, { QueueFilterPopover, QueueSortMenu, SavedViewsBar, BulkActionBar, BulkTicketRow });
