// ============================================================
// views.jsx — Table, Gallery, and Browse-by-curriculum views
// ============================================================

// ---- TABLE -------------------------------------------------
function TableView({ assets, onOpen, sort, onSort, density, colorCode }) {
  const cols = [
    { key: 'id', label: 'ID', w: 86 },
    { key: 'title', label: 'Asset', w: 'auto' },
    { key: 'type', label: 'Type', w: 92 },
    { key: 'location', label: 'Location', w: 210, nosort: true },
    { key: 'tool', label: 'AI tool', w: 168 },
    { key: 'creator', label: 'Created by', w: 150 },
    { key: 'date', label: 'Date', w: 110 },
    { key: 'humanEdited', label: 'Edited', w: 78 },
    { key: 'status', label: 'Status', w: 138 },
  ];
  const rowH = density === 'compact' ? 46 : 60;
  const allCols = colorCode ? [{ key: '_stripe', label: '', w: 4, nosort: true, stripe: true }, ...cols] : cols;
  const head = (c) => {
    if (c.stripe) return null;
    if (c.nosort) return <span>{c.label}</span>;
    const active = sort === c.key || sort === c.key + '-asc';
    const dir = sort === c.key + '-asc' ? 'asc' : 'desc';
    return (
      <button onClick={() => onSort(active && dir === 'desc' ? c.key + '-asc' : c.key)} style={viewStyles.th}>
        {c.label}
        <i className={`mdi mdi-arrow-${dir === 'asc' ? 'up' : 'down'}`}
           style={{ fontSize: 15, marginLeft: 3, opacity: active ? 0.85 : 0 }}/>
      </button>
    );
  };
  return (
    <div style={viewStyles.tableCard}>
      <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
        <colgroup>{allCols.map((c) => <col key={c.key} style={{ width: c.w === 'auto' ? 'auto' : c.w }}/>)}</colgroup>
        <thead>
          <tr style={{ position: 'sticky', top: 0, zIndex: 2 }}>
            {allCols.map((c) => <th key={c.key} style={viewStyles.thCell}>{head(c)}</th>)}
          </tr>
        </thead>
        <tbody>
          {assets.map((a) => (
            <tr key={a.id} onClick={() => onOpen(a.id)} style={{ ...viewStyles.tr, height: rowH }}
                className="reg-row">
              {colorCode && <td style={{ ...viewStyles.td, padding: 0 }}><span style={{ display: 'block', width: 4, height: rowH, background: a.color }}/></td>}
              <td style={{ ...viewStyles.td, fontFamily: 'var(--qv-font-mono)', fontSize: 12.5, color: 'rgba(0,0,0,0.55)' }}>{a.id}</td>
              <td style={viewStyles.td}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                  <Thumb asset={a} size="sm"/>
                  <span style={{ fontWeight: 500, fontSize: 13.5, color: 'rgba(0,0,0,0.87)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.title}</span>
                </div>
              </td>
              <td style={viewStyles.td}><TypeTag type={a.type}/></td>
              <td style={viewStyles.td}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12.5 }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: a.color, flexShrink: 0 }}/>
                  <span style={{ color: 'rgba(0,0,0,0.8)', whiteSpace: 'nowrap' }}>{a.productShort} · G{a.grade}</span>
                </div>
                <div style={{ fontSize: 11.5, color: 'rgba(0,0,0,0.5)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginTop: 1 }}>{a.lesson}</div>
              </td>
              <td style={{ ...viewStyles.td, fontSize: 13, color: 'rgba(0,0,0,0.75)' }}>{a.tool}</td>
              <td style={viewStyles.td}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13 }}>
                  <span style={viewStyles.miniAvatar}>{a.creatorInitials}</span>
                  <span style={{ color: 'rgba(0,0,0,0.75)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.creator}</span>
                </span>
              </td>
              <td style={{ ...viewStyles.td, fontSize: 12.5, color: 'rgba(0,0,0,0.6)', fontVariantNumeric: 'tabular-nums' }}>{a.date}</td>
              <td style={viewStyles.td}>
                {a.humanEdited
                  ? <i className="mdi mdi-account-check" title="Human-edited" style={{ fontSize: 19, color: '#2E7D32' }}/>
                  : <i className="mdi mdi-robot" title="As generated" style={{ fontSize: 18, color: 'rgba(0,0,0,0.32)' }}/>}
              </td>
              <td style={viewStyles.td}><StatusPill status={a.status} size="sm"/></td>
            </tr>
          ))}
        </tbody>
      </table>
      {assets.length === 0 && <EmptyState/>}
    </div>
  );
}

// ---- GALLERY -----------------------------------------------
function GalleryView({ assets, onOpen }) {
  if (assets.length === 0) return <div style={viewStyles.tableCard}><EmptyState/></div>;
  return (
    <div style={viewStyles.grid}>
      {assets.map((a) => (
        <button key={a.id} onClick={() => onOpen(a.id)} style={viewStyles.gCard} className="reg-card">
          <div style={{ height: 132, position: 'relative' }}>
            <Thumb asset={a} size="fill"/>
            <div style={{ position: 'absolute', top: 8, left: 8 }}><TypeTag type={a.type}/></div>
            <div style={{ position: 'absolute', top: 8, right: 8 }}><StatusPill status={a.status} size="sm"/></div>
          </div>
          <div style={{ padding: '12px 14px', textAlign: 'left' }}>
            <div style={{ fontFamily: 'var(--qv-font-mono)', fontSize: 11, color: 'rgba(0,0,0,0.45)', marginBottom: 3 }}>{a.id}</div>
            <div style={{ fontWeight: 500, fontSize: 14, color: 'rgba(0,0,0,0.87)', lineHeight: 1.35, marginBottom: 9, minHeight: 38,
              display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{a.title}</div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
              <ProductTag asset={a}/>
              <span style={{ fontSize: 12, color: 'rgba(0,0,0,0.5)', whiteSpace: 'nowrap' }}>Grade {a.grade}</span>
            </div>
            <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--qv-border)', display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'rgba(0,0,0,0.6)' }}>
              <i className="mdi mdi-creation-outline" style={{ fontSize: 15 }}/>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.tool}</span>
              {a.humanEdited && <i className="mdi mdi-account-check" title="Human-edited" style={{ fontSize: 16, color: '#2E7D32', marginLeft: 'auto' }}/>}
            </div>
          </div>
        </button>
      ))}
    </div>
  );
}

// ---- BROWSE BY CURRICULUM ----------------------------------
function BrowseView({ assets, onOpen }) {
  const P = window.REGISTRY.PRODUCTS;
  const [sel, setSel] = React.useState({ product: null, grade: null });

  // Build tree from the (already globally-filtered) asset set
  const tree = {};
  assets.forEach((a) => {
    tree[a.product] = tree[a.product] || { count: 0, grades: {} };
    tree[a.product].count++;
    tree[a.product].grades[a.grade] = (tree[a.product].grades[a.grade] || 0) + 1;
  });

  const shown = assets.filter((a) =>
    (!sel.product || a.product === sel.product) && (!sel.grade || a.grade === sel.grade));

  const gradeSort = (a, b) => (a === 'K' ? -1 : b === 'K' ? 1 : (+a) - (+b));

  return (
    <div style={viewStyles.browseWrap}>
      <aside style={viewStyles.tree}>
        <button onClick={() => setSel({ product: null, grade: null })}
          style={{ ...viewStyles.treeRoot, ...(!sel.product ? { background: '#E8F0FA', color: '#1867C0' } : {}) }}>
          <i className="mdi mdi-folder-multiple-outline" style={{ fontSize: 18 }}/>
          All curriculum
          <span style={viewStyles.treeCount}>{assets.length}</span>
        </button>
        {Object.keys(P).filter((p) => tree[p]).map((p) => {
          const open = sel.product === p;
          return (
            <div key={p}>
              <button onClick={() => setSel({ product: open ? null : p, grade: null })}
                style={{ ...viewStyles.treeProduct, ...(open ? { background: P[p].color + '12' } : {}) }}>
                <i className={`mdi mdi-chevron-${open ? 'down' : 'right'}`} style={{ fontSize: 18, color: 'rgba(0,0,0,0.4)' }}/>
                <span style={{ width: 10, height: 10, borderRadius: '50%', background: P[p].color, flexShrink: 0 }}/>
                <span style={{ flex: 1, textAlign: 'left', fontWeight: 500 }}>{P[p].short}</span>
                <span style={viewStyles.treeCount}>{tree[p].count}</span>
              </button>
              {open && Object.keys(tree[p].grades).sort(gradeSort).map((g) => (
                <button key={g} onClick={() => setSel({ product: p, grade: sel.grade === g ? null : g })}
                  style={{ ...viewStyles.treeGrade, ...(sel.grade === g ? { background: '#E8F0FA', color: '#1867C0', fontWeight: 500 } : {}) }}>
                  <i className="mdi mdi-school-outline" style={{ fontSize: 15, opacity: 0.6 }}/>
                  Grade {g}
                  <span style={viewStyles.treeCount}>{tree[p].grades[g]}</span>
                </button>
              ))}
            </div>
          );
        })}
      </aside>

      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={viewStyles.browseCrumb}>
          <i className="mdi mdi-map-marker-outline" style={{ fontSize: 17, color: 'rgba(0,0,0,0.4)' }}/>
          <b style={{ fontWeight: 500 }}>{sel.product ? P[sel.product].short : 'All curriculum'}</b>
          {sel.grade && <React.Fragment><i className="mdi mdi-chevron-right" style={{ fontSize: 16, color: 'rgba(0,0,0,0.3)' }}/><span>Grade {sel.grade}</span></React.Fragment>}
          <span style={{ marginLeft: 'auto', fontSize: 13, color: 'rgba(0,0,0,0.55)' }}>{shown.length} assets</span>
        </div>
        {shown.length === 0
          ? <div style={viewStyles.tableCard}><EmptyState/></div>
          : <div style={viewStyles.browseGrid}>
              {shown.map((a) => (
                <button key={a.id} onClick={() => onOpen(a.id)} style={viewStyles.browseItem} className="reg-card">
                  <Thumb asset={a} size="md"/>
                  <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
                    <div style={{ display: 'flex', gap: 6, marginBottom: 5 }}><TypeTag type={a.type}/><StatusPill status={a.status} size="sm"/></div>
                    <div style={{ fontWeight: 500, fontSize: 13.5, color: 'rgba(0,0,0,0.87)', lineHeight: 1.35, marginBottom: 4,
                      display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{a.title}</div>
                    <div style={{ fontSize: 12, color: 'rgba(0,0,0,0.55)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {a.lesson} · {a.tool}
                    </div>
                  </div>
                </button>
              ))}
            </div>}
      </div>
    </div>
  );
}

function EmptyState() {
  return (
    <div style={{ padding: '64px 24px', textAlign: 'center', color: 'rgba(0,0,0,0.45)' }}>
      <i className="mdi mdi-image-search-outline" style={{ fontSize: 48, opacity: 0.5 }}/>
      <div style={{ fontSize: 15, marginTop: 10, fontWeight: 500, color: 'rgba(0,0,0,0.6)' }}>No assets match your filters</div>
      <div style={{ fontSize: 13, marginTop: 4 }}>Try clearing a filter or adjusting your search.</div>
    </div>
  );
}

const viewStyles = {
  tableCard: { background: '#fff', border: '1px solid var(--qv-border)', borderRadius: 8, overflow: 'hidden', boxShadow: 'var(--qv-elev-1)' },
  thCell: { background: 'var(--qv-grey-50)', borderBottom: '1px solid var(--qv-border)', padding: 0, textAlign: 'left' },
  th: {
    display: 'inline-flex', alignItems: 'center', width: '100%', height: 42, padding: '0 14px', border: 0, background: 'transparent',
    cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 500, fontSize: 12, letterSpacing: '.04em', textTransform: 'uppercase',
    color: 'rgba(0,0,0,0.6)',
  },
  tr: { borderBottom: '1px solid var(--qv-border)', cursor: 'pointer', transition: 'background .12s' },
  td: { padding: '0 14px', overflow: 'hidden', verticalAlign: 'middle' },
  miniAvatar: { width: 24, height: 24, borderRadius: '50%', background: '#FFC107', color: 'rgba(0,0,0,0.8)', fontSize: 10, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 },

  grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(232px, 1fr))', gap: 16 },
  gCard: { background: '#fff', border: '1px solid var(--qv-border)', borderRadius: 10, overflow: 'hidden', cursor: 'pointer', padding: 0, textAlign: 'left', boxShadow: 'var(--qv-elev-1)', transition: 'box-shadow .15s, transform .15s' },

  browseWrap: { display: 'flex', gap: 20, alignItems: 'flex-start' },
  tree: { width: 232, flexShrink: 0, background: '#fff', border: '1px solid var(--qv-border)', borderRadius: 8, padding: 8, boxShadow: 'var(--qv-elev-1)', position: 'sticky', top: 0 },
  treeRoot: { display: 'flex', alignItems: 'center', gap: 9, width: '100%', height: 38, padding: '0 10px', border: 0, borderRadius: 6, background: 'transparent', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 500, fontSize: 13.5, color: 'rgba(0,0,0,0.8)', marginBottom: 4 },
  treeProduct: { display: 'flex', alignItems: 'center', gap: 8, width: '100%', height: 38, padding: '0 8px', border: 0, borderRadius: 6, background: 'transparent', cursor: 'pointer', fontFamily: 'Roboto', fontSize: 13.5, color: 'rgba(0,0,0,0.8)' },
  treeGrade: { display: 'flex', alignItems: 'center', gap: 8, width: '100%', height: 32, padding: '0 8px 0 30px', border: 0, borderRadius: 6, background: 'transparent', cursor: 'pointer', fontFamily: 'Roboto', fontSize: 13, color: 'rgba(0,0,0,0.7)' },
  treeCount: { marginLeft: 'auto', fontSize: 11.5, fontWeight: 600, color: 'rgba(0,0,0,0.45)', background: 'var(--qv-grey-100)', borderRadius: 9999, minWidth: 22, height: 18, padding: '0 6px', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' },
  browseCrumb: { display: 'flex', alignItems: 'center', gap: 8, padding: '0 4px 14px', fontSize: 14.5, color: 'rgba(0,0,0,0.8)' },
  browseGrid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(310px, 1fr))', gap: 14 },
  browseItem: { display: 'flex', gap: 13, background: '#fff', border: '1px solid var(--qv-border)', borderRadius: 10, padding: 12, cursor: 'pointer', boxShadow: 'var(--qv-elev-1)', transition: 'box-shadow .15s, transform .15s' },
};

Object.assign(window, { TableView, GalleryView, BrowseView, EmptyState });
