// components-view.jsx — ComponentsView: table + kanban for hooks/leads/bodies
const { useState, useContext, useMemo } = React;

const COMP_STATUS_COLS = ['Testing', 'Winner', 'Loser'];

function ComponentsView({ searchQuery, onOpenComponent }) {
  const { state, dispatch } = useContext(window.AppCtx);
  const wsId = state.activeWorkspaceId;
  const allComps = useMemo(() =>
    state.components.filter(c => c.workspaceId === wsId), [state.components, wsId]);

  const [viewMode, setViewMode] = useState('table');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');

  const [showLosers, setShowLosers] = useState(false);
  const [sortCol, setSortCol] = useState('id');
  const [sortDir, setSortDir] = useState('asc');
  const [addModal, setAddModal] = useState(null); // 'hook'|'lead'|'body'
  const [detailId, setDetailId] = useState(null);

  const filtered = useMemo(() => {
    let items = allComps;
    if (typeFilter !== 'all') items = items.filter(c => c.type === typeFilter);
    if (statusFilter !== 'all') items = items.filter(c => c.status === statusFilter);
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      items = items.filter(c =>
        c.id.toLowerCase().includes(q) ||
        c.description?.toLowerCase().includes(q) ||
        c.notes?.toLowerCase().includes(q)
      );
    }
    return items;
  }, [allComps, typeFilter, statusFilter, searchQuery]);

  const sorted = useMemo(() => {
    const arr = [...filtered];
    arr.sort((a, b) => {
      let av, bv;
      if (sortCol === 'id') { av = parseInt(a.id.slice(1)) || 0; bv = parseInt(b.id.slice(1)) || 0; }
      else if (sortCol === 'created') { av = a.createdAt; bv = b.createdAt; }
      else { av = (a[sortCol] || '').toLowerCase(); bv = (b[sortCol] || '').toLowerCase(); }
      if (av < bv) return sortDir === 'asc' ? -1 : 1;
      if (av > bv) return sortDir === 'asc' ? 1 : -1;
      return 0;
    });
    return arr;
  }, [filtered, sortCol, sortDir]);

  const sort = col => {
    if (sortCol === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortCol(col); setSortDir('asc'); }
  };
  const sortArrow = col => sortCol === col ? (sortDir === 'asc' ? ' ↑' : ' ↓') : '';

  const addType = typeFilter !== 'all' ? typeFilter : 'hook';

  return (
    <div className="view-area">
      {/* Toolbar */}
      <div className="view-toolbar">
        <div className="seg">
          <button className={`seg-opt${viewMode==='table'?' active':''}`} onClick={() => setViewMode('table')}>Table</button>
          <button className={`seg-opt${viewMode==='kanban'?' active':''}`} onClick={() => setViewMode('kanban')}>Kanban</button>
        </div>
        <div style={{ width: 1, height: 20, background: 'var(--bd)', margin: '0 4px' }} />
        <select className="filter-select" value={typeFilter} onChange={e => setTypeFilter(e.target.value)}>
          <option value="all">All types</option>
          <option value="hook">Hooks</option>
          <option value="lead">Leads</option>
          <option value="body">Bodies</option>
        </select>
        {viewMode === 'table' && (
          <select className="filter-select" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
            <option value="all">All statuses</option>
            {COMP_STATUS_COLS.map(s => <option key={s}>{s}</option>)}
          </select>
        )}

        {viewMode === 'kanban' && (
          <button
            className={`btn btn-ghost btn-sm${showLosers ? ' active' : ''}`}
            onClick={() => setShowLosers(s => !s)}
          >
            {showLosers ? 'Hide Losers' : 'Show Losers'}
          </button>
        )}
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 11, color: '#3a3a58', marginRight: 8 }}>{filtered.length} items</span>
        <div style={{ display: 'flex', gap: 5 }}>
          {['hook','lead','body'].map(t => (
            <button key={t} className="btn btn-primary btn-sm" onClick={() => setAddModal(t)}>
              + {window.TYPE_STYLES[t].label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div className="view-content">
        {viewMode === 'table'
          ? <CompTable rows={sorted} sort={sort} sortArrow={sortArrow} typeFilter={typeFilter} onOpen={setDetailId} dispatch={dispatch} wsId={wsId} />
          : <CompKanban items={filtered} showLosers={showLosers} onOpen={setDetailId} dispatch={dispatch} wsId={wsId} />
        }
      </div>

      {addModal && <window.AddComponentModal compType={addModal} onClose={() => setAddModal(null)} />}
      {detailId && <window.ComponentDetailModal itemId={detailId} onClose={() => setDetailId(null)} onOpenComponent={onOpenComponent} />}
    </div>
  );
}

function CompTable({ rows, sort, sortArrow, typeFilter, onOpen, dispatch, wsId }) {
  if (rows.length === 0) return (
    <div className="empty">
      <div className="empty-icon">⬚</div>
      <div className="empty-txt">No components yet — add a Hook, Lead, or Body above</div>
    </div>
  );

  return (
    <div className="tbl-wrap">
      <table className="tbl">
        <colgroup>
          <col style={{ width: 56 }} />
          {typeFilter === 'all' && <col style={{ width: 64 }} />}
          <col />
          <col style={{ width: 100 }} />
          <col style={{ width: 110 }} />
          <col style={{ width: 96 }} />
        </colgroup>
        <thead>
          <tr>
            <th className="sort" onClick={() => sort('id')}>ID{sortArrow('id')}</th>
            {typeFilter === 'all' && <th>Type</th>}
            <th className="sort" onClick={() => sort('description')}>Description{sortArrow('description')}</th>
            <th className="sort" onClick={() => sort('status')}>Status{sortArrow('status')}</th>
            <th>Editing</th>
            <th className="sort" onClick={() => sort('created')}>Created{sortArrow('created')}</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(c => (
            <tr key={c.id + c.workspaceId} onClick={() => onOpen(c.id)}>
              <td><window.IdBadge id={c.id} /></td>
              {typeFilter === 'all' && <td><window.TypeChip type={c.type} /></td>}
              <td style={{ maxWidth: 0 }}>
                <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', display: 'block' }}>
                  {c.description || <span style={{ color: '#3a3a58' }}>—</span>}
                </span>
              </td>
              <td><window.StatusPill status={c.status} /></td>
              <td><window.StatusPill status={c.editingStatus} /></td>
              <td style={{ color: '#4a4a68', fontSize: 11 }}>{new Date(c.createdAt).toLocaleDateString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function CompKanban({ items, showLosers, onOpen, dispatch, wsId }) {
  const [dragging, setDragging] = useState(null);
  const [dragOver, setDragOver] = useState(null);

  const cols = showLosers ? COMP_STATUS_COLS : COMP_STATUS_COLS.filter(c => c !== 'Loser');

  const drop = (status) => {
    if (dragging && dragging !== status) {
      dispatch({ type: 'UPD_COMP', id: dragging.id, data: { status } });
    }
    setDragging(null);
    setDragOver(null);
  };

  return (
    <div className="kanban">
      {cols.map(status => {
        const colItems = items.filter(c => c.status === status);
        const dot = window.COL_DOTS[status] || '#6a6a88';
        return (
          <div key={status} className="kcol">
            <div className="kcol-hd">
              <div className="kcol-dot" style={{ background: dot }} />
              <span className="kcol-hd-label" style={{ color: dot }}>{status}</span>
              <span className="kcol-cnt">{colItems.length}</span>
            </div>
            <div
              className={`kcol-body${dragOver === status ? ' drag-over' : ''}`}
              onDragOver={e => { e.preventDefault(); setDragOver(status); }}
              onDragLeave={() => setDragOver(null)}
              onDrop={() => drop(status)}
            >
              {colItems.map(c => (
                <div
                  key={c.id}
                  className={`kcard${dragging?.id === c.id ? ' dragging' : ''}`}
                  style={{ borderLeftColor: dot }}
                  draggable
                  onDragStart={() => setDragging(c)}
                  onDragEnd={() => { setDragging(null); setDragOver(null); }}
                  onClick={() => onOpen(c.id)}
                >
                  <div className="kcard-top">
                    <window.IdBadge id={c.id} />
                    <window.TypeChip type={c.type} />
                  </div>
                  <div className="kcard-desc">{c.description || <span style={{ color: '#3a3a50' }}>No description</span>}</div>
                  <div className="kcard-meta">
                    <window.StatusPill status={c.editingStatus} />
                  </div>
                </div>
              ))}
              {colItems.length === 0 && (
                <div style={{ textAlign: 'center', color: '#2a2a40', fontSize: 11, paddingTop: 20 }}>Empty</div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { ComponentsView });
