// ============================================================
// controls.jsx — filter bar, view switcher, detail drawer
// ============================================================

// ---- Segmented view switcher ------------------------------
function ViewSwitcher({ view, onView }) {
  const opts = [
    { id: 'table',   icon: 'mdi-table',            label: 'Table' },
    { id: 'gallery', icon: 'mdi-view-grid-outline', label: 'Gallery' },
    { id: 'browse',  icon: 'mdi-file-tree-outline', label: 'Browse' },
  ];
  return (
    <div style={ctrlStyles.segment}>
      {opts.map((o) => {
        const active = view === o.id;
        return (
          <button key={o.id} onClick={() => onView(o.id)}
            style={{ ...ctrlStyles.segBtn, ...(active ? ctrlStyles.segBtnActive : {}) }}>
            <i className={`mdi ${o.icon}`} style={{ fontSize: 17 }}/>
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

// ---- Faceted filter dropdown ------------------------------
function FilterDropdown({ label, icon, options, selected, onChange }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    function onDoc(e) { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);
  const toggle = (val) => {
    if (selected.includes(val)) onChange(selected.filter((s) => s !== val));
    else onChange([...selected, val]);
  };
  const count = selected.length;
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen(!open)}
        style={{ ...ctrlStyles.filterBtn, ...(count ? ctrlStyles.filterBtnActive : {}) }}>
        <i className={`mdi ${icon}`} style={{ fontSize: 17 }}/>
        {label}
        {count > 0 && <span style={ctrlStyles.filterCount}>{count}</span>}
        <i className={`mdi mdi-chevron-${open ? 'up' : 'down'}`} style={{ fontSize: 18, marginLeft: -2 }}/>
      </button>
      {open && (
        <div style={ctrlStyles.popover}>
          {options.map((o) => {
            const on = selected.includes(o.value);
            return (
              <button key={o.value} onClick={() => toggle(o.value)} style={ctrlStyles.popItem}>
                <span style={{ ...ctrlStyles.check, ...(on ? ctrlStyles.checkOn : {}) }}>
                  {on && <i className="mdi mdi-check" style={{ fontSize: 14, color: '#fff' }}/>}
                </span>
                {o.dot && <span style={{ width: 9, height: 9, borderRadius: '50%', background: o.dot }}/>}
                {o.icon && <i className={`mdi ${o.icon}`} style={{ fontSize: 16, color: o.iconColor || 'rgba(0,0,0,0.6)' }}/>}
                <span style={{ flex: 1, textAlign: 'left' }}>{o.label}</span>
                <span style={{ color: 'rgba(0,0,0,0.4)', fontSize: 12.5 }}>{o.count}</span>
              </button>
            );
          })}
          {count > 0 && (
            <button onClick={() => onChange([])} style={ctrlStyles.popClear}>Clear</button>
          )}
        </div>
      )}
    </div>
  );
}

// ---- Filter bar -------------------------------------------
function FilterBar({ view, onView, all, filters, setFilters, resultCount, sort, onSort }) {
  const tally = (key, val) => all.filter((a) => a[key] === val).length;
  const P = window.REGISTRY.PRODUCTS, S = window.REGISTRY.STATUSES;
  const productOpts = Object.keys(P).map((k) => ({ value: k, label: P[k].short, dot: P[k].color, count: tally('product', k) }));
  const gradeOpts = window.REGISTRY.GRADES.map((g) => ({ value: g, label: 'Grade ' + g, count: tally('grade', g) }));
  const typeOpts = [
    { value: 'image', label: 'Image', icon: 'mdi-image-outline', count: tally('type', 'image') },
    { value: 'video', label: 'Video', icon: 'mdi-play-box-outline', count: tally('type', 'video') },
  ];
  const statusOpts = Object.keys(S).map((k) => ({ value: k, label: S[k].label, icon: S[k].icon, count: tally('status', k) }));

  const set = (key) => (vals) => setFilters({ ...filters, [key]: vals });
  const activeTotal = filters.product.length + filters.grade.length + filters.type.length + filters.status.length;

  return (
    <div style={ctrlStyles.bar}>
      <ViewSwitcher view={view} onView={onView}/>
      <div style={{ width: 1, height: 26, background: 'var(--qv-border)', margin: '0 4px' }}/>
      <FilterDropdown label="Product" icon="mdi-shape-outline" options={productOpts} selected={filters.product} onChange={set('product')}/>
      <FilterDropdown label="Grade" icon="mdi-school-outline" options={gradeOpts} selected={filters.grade} onChange={set('grade')}/>
      <FilterDropdown label="Type" icon="mdi-multimedia" options={typeOpts} selected={filters.type} onChange={set('type')}/>
      <FilterDropdown label="Status" icon="mdi-shield-check-outline" options={statusOpts} selected={filters.status} onChange={set('status')}/>
      {activeTotal > 0 && (
        <button onClick={() => setFilters({ product: [], grade: [], type: [], status: [] })} style={ctrlStyles.resetBtn}>
          <i className="mdi mdi-close-circle-outline" style={{ fontSize: 16 }}/> Reset
        </button>
      )}
      <div style={{ flex: 1 }}/>
      <span style={{ fontSize: 13, color: 'rgba(0,0,0,0.6)', whiteSpace: 'nowrap' }}>
        <b style={{ color: 'rgba(0,0,0,0.87)', fontWeight: 500 }}>{resultCount}</b> {resultCount === 1 ? 'asset' : 'assets'}
      </span>
      {view !== 'table' && (
        <select value={sort} onChange={(e) => onSort(e.target.value)} style={ctrlStyles.sortSelect}>
          <option value="date">Newest first</option>
          <option value="date-asc">Oldest first</option>
          <option value="id">ID</option>
          <option value="product">Product</option>
          <option value="status">Status</option>
        </select>
      )}
    </div>
  );
}

// ---- Detail drawer ----------------------------------------
function DetailDrawer({ asset, onClose, onStatusChange }) {
  const [copied, setCopied] = React.useState(false);
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [onClose]);
  if (!asset) return null;
  const S = window.REGISTRY.STATUSES;
  const copyPrompt = () => {
    navigator.clipboard && navigator.clipboard.writeText(asset.prompt);
    setCopied(true); setTimeout(() => setCopied(false), 1400);
  };
  const Row = ({ label, children }) => (
    <div style={{ display: 'flex', padding: '11px 0', borderBottom: '1px solid var(--qv-border)', gap: 12 }}>
      <div style={{ width: 116, flexShrink: 0, fontSize: 12.5, color: 'rgba(0,0,0,0.55)', paddingTop: 1 }}>{label}</div>
      <div style={{ flex: 1, fontSize: 13.5, color: 'rgba(0,0,0,0.87)' }}>{children}</div>
    </div>
  );
  return (
    <React.Fragment>
      <div style={ctrlStyles.scrim} onClick={onClose}/>
      <aside style={ctrlStyles.drawer}>
        <div style={ctrlStyles.drawerHead}>
          <span style={{ fontFamily: 'var(--qv-font-mono)', fontSize: 13, color: 'rgba(0,0,0,0.55)' }}>{asset.id}</span>
          <button onClick={onClose} style={ctrlStyles.drawerClose} aria-label="Close"><i className="mdi mdi-close" style={{ fontSize: 22 }}/></button>
        </div>
        <div style={{ overflowY: 'auto', flex: 1 }}>
          <div style={{ height: 200, position: 'relative' }}><Thumb asset={asset} size="fill"/></div>
          <div style={{ padding: '18px 22px' }}>
            <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
              <TypeTag type={asset.type}/>
              <StatusPill status={asset.status}/>
            </div>
            <h2 style={{ margin: '0 0 4px', fontSize: 19, fontWeight: 500, lineHeight: 1.3, color: 'rgba(0,0,0,0.87)' }}>{asset.title}</h2>

            <div style={{ marginTop: 16, marginBottom: 6, fontSize: 11.5, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)' }}>Location in curriculum</div>
            <div style={ctrlStyles.breadcrumb}>
              <ProductTag asset={asset}/>
              <i className="mdi mdi-chevron-right" style={{ fontSize: 16, color: 'rgba(0,0,0,0.3)' }}/>
              <span>Grade {asset.grade}</span>
              <i className="mdi mdi-chevron-right" style={{ fontSize: 16, color: 'rgba(0,0,0,0.3)' }}/>
              <span>{asset.unit}</span>
            </div>
            <div style={{ fontSize: 14, fontWeight: 500, color: 'rgba(0,0,0,0.87)', marginTop: 6, marginBottom: 4 }}>
              <i className="mdi mdi-book-open-variant" style={{ fontSize: 16, color: 'rgba(0,0,0,0.4)', marginRight: 6 }}/>
              {asset.lesson}
            </div>

            <div style={{ marginTop: 18, marginBottom: 6, fontSize: 11.5, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)' }}>Generation prompt</div>
            <div style={ctrlStyles.promptBox}>
              <span style={{ flex: 1 }}>{asset.prompt}</span>
              <button onClick={copyPrompt} style={ctrlStyles.copyBtn} aria-label="Copy prompt">
                <i className={`mdi ${copied ? 'mdi-check' : 'mdi-content-copy'}`} style={{ fontSize: 16, color: copied ? '#2E7D32' : 'rgba(0,0,0,0.5)' }}/>
              </button>
            </div>

            <div style={{ marginTop: 16 }}>
              <Row label="AI tool / model"><b style={{ fontWeight: 500 }}>{asset.tool}</b></Row>
              <Row label="Asset type">{asset.type === 'video' ? `Video · ${asset.duration}` : 'Still image'}</Row>
              <Row label="Created by">
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                  <span style={ctrlStyles.miniAvatar}>{asset.creatorInitials}</span>{asset.creator}
                </span>
              </Row>
              <Row label="Date generated">{asset.date}</Row>
              <Row label="Human-edited">
                {asset.humanEdited
                  ? <span style={{ color: '#2E7D32' }}><i className="mdi mdi-check-circle" style={{ fontSize: 15, marginRight: 5 }}/>Yes — {asset.humanEditNote}</span>
                  : <span style={{ color: 'rgba(0,0,0,0.55)' }}>No — used as generated</span>}
              </Row>
              <Row label="License / rights">{asset.license}</Row>
            </div>

            <div style={{ marginTop: 20, marginBottom: 8, fontSize: 11.5, fontWeight: 600, letterSpacing: '.08em', textTransform: 'uppercase', color: 'rgba(0,0,0,0.5)' }}>Compliance status</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {Object.keys(S).map((k) => {
                const on = asset.status === k;
                return (
                  <button key={k} onClick={() => onStatusChange(asset.id, k)}
                    style={{ ...ctrlStyles.statusOpt, ...(on ? { borderColor: '#1867C0', background: '#E8F0FA' } : {}) }}>
                    <i className={`mdi ${S[k].icon}`} style={{ fontSize: 16 }}/>{S[k].label}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </aside>
    </React.Fragment>
  );
}

const ctrlStyles = {
  bar: { display: 'flex', alignItems: 'center', gap: 8, padding: '12px 0', flexShrink: 0, flexWrap: 'wrap' },
  segment: { display: 'inline-flex', background: '#fff', border: '1px solid var(--qv-border)', borderRadius: 8, padding: 3, gap: 2 },
  segBtn: {
    display: 'inline-flex', alignItems: 'center', gap: 6, height: 32, padding: '0 14px', border: 0, borderRadius: 6,
    background: 'transparent', color: 'rgba(0,0,0,0.6)', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 500, fontSize: 13.5,
    transition: 'all .15s',
  },
  segBtnActive: { background: '#1867C0', color: '#fff', boxShadow: 'var(--qv-elev-1)' },
  filterBtn: {
    display: 'inline-flex', alignItems: 'center', gap: 6, height: 38, padding: '0 12px', borderRadius: 8,
    background: '#fff', border: '1px solid var(--qv-border)', color: 'rgba(0,0,0,0.7)', cursor: 'pointer',
    fontFamily: 'Roboto', fontWeight: 500, fontSize: 13.5,
  },
  filterBtnActive: { borderColor: '#1867C0', color: '#1867C0', background: '#F3F8FE' },
  filterCount: { minWidth: 18, height: 18, padding: '0 5px', borderRadius: 9, background: '#1867C0', color: '#fff', fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  popover: {
    position: 'absolute', top: 'calc(100% + 6px)', left: 0, minWidth: 220, background: '#fff', borderRadius: 8,
    boxShadow: 'var(--qv-elev-8)', border: '1px solid var(--qv-border)', padding: 6, zIndex: 40, maxHeight: 320, overflowY: 'auto',
  },
  popItem: {
    display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '8px 9px', border: 0, borderRadius: 6,
    background: 'transparent', cursor: 'pointer', fontFamily: 'Roboto', fontSize: 13.5, color: 'rgba(0,0,0,0.8)',
  },
  check: { width: 18, height: 18, borderRadius: 4, border: '2px solid var(--qv-border-strong)', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  checkOn: { background: '#1867C0', borderColor: '#1867C0' },
  popClear: { width: '100%', marginTop: 4, padding: '8px', border: 0, borderTop: '1px solid var(--qv-border)', background: 'transparent', color: '#1867C0', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 500, fontSize: 13, textTransform: 'uppercase', letterSpacing: '.04em' },
  resetBtn: { display: 'inline-flex', alignItems: 'center', gap: 5, height: 38, padding: '0 10px', border: 0, borderRadius: 8, background: 'transparent', color: 'rgba(0,0,0,0.55)', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 500, fontSize: 13 },
  sortSelect: { height: 38, borderRadius: 8, border: '1px solid var(--qv-border)', background: '#fff', padding: '0 10px', fontFamily: 'Roboto', fontSize: 13.5, color: 'rgba(0,0,0,0.75)', cursor: 'pointer' },

  scrim: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.42)', zIndex: 50, animation: 'fadeIn .2s' },
  drawer: {
    position: 'fixed', top: 0, right: 0, width: 440, maxWidth: '92vw', height: '100vh', background: '#fff',
    boxShadow: 'var(--qv-elev-16)', zIndex: 51, display: 'flex', flexDirection: 'column', animation: 'slideIn .26s cubic-bezier(0,0,0.2,1)',
  },
  drawerHead: { height: 52, display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 12px 0 22px', borderBottom: '1px solid var(--qv-border)', flexShrink: 0 },
  drawerClose: { width: 38, height: 38, borderRadius: '50%', border: 0, background: 'transparent', cursor: 'pointer', color: 'rgba(0,0,0,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center' },
  breadcrumb: { display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap', fontSize: 13.5, color: 'rgba(0,0,0,0.7)' },
  promptBox: { display: 'flex', gap: 8, background: 'var(--qv-grey-100)', border: '1px solid var(--qv-border)', borderRadius: 8, padding: '12px 12px 12px 14px', fontFamily: 'var(--qv-font-mono)', fontSize: 12.5, lineHeight: 1.55, color: 'rgba(0,0,0,0.78)' },
  copyBtn: { width: 30, height: 30, flexShrink: 0, border: 0, borderRadius: 6, background: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: 'var(--qv-elev-1)' },
  miniAvatar: { width: 24, height: 24, borderRadius: '50%', background: '#FFC107', color: 'rgba(0,0,0,0.8)', fontSize: 10.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center' },
  statusOpt: { display: 'inline-flex', alignItems: 'center', gap: 6, height: 34, padding: '0 12px', borderRadius: 8, border: '1px solid var(--qv-border)', background: '#fff', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 500, fontSize: 13, color: 'rgba(0,0,0,0.75)' },
};

Object.assign(window, { ViewSwitcher, FilterDropdown, FilterBar, DetailDrawer });
