// ============================================================
// app.jsx — AI Asset Registry shell: state, filtering, export
// ============================================================

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "defaultView": "table",
  "density": "comfortable",
  "colorCode": true,
  "accent": "#1867C0"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [assets, setAssets] = React.useState(() => window.REGISTRY.assets);
  const [view, setView] = React.useState(t.defaultView);
  const [query, setQuery] = React.useState('');
  const [filters, setFilters] = React.useState({ product: [], grade: [], type: [], status: [] });
  const [sort, setSort] = React.useState('date');
  const [openId, setOpenId] = React.useState(null);

  // keep view in sync if the tweak default changes
  React.useEffect(() => { setView(t.defaultView); }, [t.defaultView]);

  // ---- filter + search + sort ----
  const filtered = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    let out = assets.filter((a) => {
      if (filters.product.length && !filters.product.includes(a.product)) return false;
      if (filters.grade.length && !filters.grade.includes(a.grade)) return false;
      if (filters.type.length && !filters.type.includes(a.type)) return false;
      if (filters.status.length && !filters.status.includes(a.status)) return false;
      if (q) {
        const hay = `${a.id} ${a.title} ${a.prompt} ${a.tool} ${a.creator} ${a.lesson} ${a.unit} ${a.productShort}`.toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
    const cmp = {
      date:       (a, b) => (a.date < b.date ? 1 : -1),
      'date-asc': (a, b) => (a.date > b.date ? 1 : -1),
      id:         (a, b) => (a.id > b.id ? 1 : -1),
      'id-asc':   (a, b) => (a.id < b.id ? 1 : -1),
      title:      (a, b) => a.title.localeCompare(b.title),
      'title-asc':(a, b) => b.title.localeCompare(a.title),
      type:       (a, b) => a.type.localeCompare(b.type),
      'type-asc': (a, b) => b.type.localeCompare(a.type),
      tool:       (a, b) => a.tool.localeCompare(b.tool),
      'tool-asc': (a, b) => b.tool.localeCompare(a.tool),
      creator:    (a, b) => a.creator.localeCompare(b.creator),
      'creator-asc':(a, b) => b.creator.localeCompare(a.creator),
      product:    (a, b) => a.productShort.localeCompare(b.productShort),
      'product-asc':(a, b) => b.productShort.localeCompare(a.productShort),
      status:     (a, b) => a.status.localeCompare(b.status),
      'status-asc':(a, b) => b.status.localeCompare(a.status),
      humanEdited:(a, b) => (b.humanEdited - a.humanEdited),
      'humanEdited-asc':(a, b) => (a.humanEdited - b.humanEdited),
    };
    return out.sort(cmp[sort] || cmp.date);
  }, [assets, filters, query, sort]);

  const openAsset = filtered.find((a) => a.id === openId) || assets.find((a) => a.id === openId) || null;

  const onStatusChange = (id, status) => {
    setAssets((prev) => prev.map((a) => (a.id === id ? { ...a, status } : a)));
  };

  // ---- CSV export of the current filtered set ----
  const onExport = () => {
    const cols = ['ID', 'Title', 'Type', 'Product', 'Grade', 'Unit', 'Lesson', 'AI tool', 'Created by', 'Date', 'Human-edited', 'Edit note', 'Status', 'License', 'Prompt'];
    const S = window.REGISTRY.STATUSES;
    const esc = (v) => { const s = String(v == null ? '' : v); return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
    const rows = filtered.map((a) => [
      a.id, a.title, a.type, a.product, a.grade, a.unit, a.lesson, a.tool, a.creator, a.date,
      a.humanEdited ? 'Yes' : 'No', a.humanEditNote || '', S[a.status].label, a.license, a.prompt,
    ].map(esc).join(','));
    const csv = cols.join(',') + '\n' + rows.join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `ai-asset-registry_${new Date().toISOString().slice(0, 10)}.csv`;
    document.body.appendChild(link); link.click(); document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const viewEl = {
    table:   <TableView assets={filtered} onOpen={setOpenId} sort={sort} onSort={setSort} density={t.density} colorCode={t.colorCode}/>,
    gallery: <GalleryView assets={filtered} onOpen={setOpenId}/>,
    browse:  <BrowseView assets={filtered} onOpen={setOpenId}/>,
  }[view];

  return (
    <React.Fragment>
      <AppBar query={query} onQuery={setQuery} onExport={onExport} resultCount={filtered.length}/>
      <div style={{ flex: 1, overflowY: 'auto', background: 'var(--qv-grey-100)' }}>
        <div style={{ maxWidth: 1400, margin: '0 auto', padding: '20px 28px 56px' }}>
          <StatStrip all={assets} filtered={filtered}/>
          <FilterBar view={view} onView={setView} all={assets} filters={filters} setFilters={setFilters}
            resultCount={filtered.length} sort={sort} onSort={setSort}/>
          {viewEl}
        </div>
      </div>

      {openAsset && <DetailDrawer asset={openAsset} onClose={() => setOpenId(null)} onStatusChange={onStatusChange}/>}

      <TweaksPanel>
        <TweakSection label="Default view"/>
        <TweakRadio label="Open in" value={t.defaultView} options={['table', 'gallery', 'browse']}
          onChange={(v) => setTweak('defaultView', v)}/>
        <TweakSection label="Table"/>
        <TweakRadio label="Density" value={t.density} options={['comfortable', 'compact']}
          onChange={(v) => setTweak('density', v)}/>
        <TweakToggle label="Color-code by product" value={t.colorCode}
          onChange={(v) => setTweak('colorCode', v)}/>
      </TweaksPanel>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
