// Collections page — grid (default) / list-accordion / table views.
// Clicking a collection opens the in-page detail view (kept under the Collections tab).

function CollectionsPage({ onOpenCollection }) {
  const [view, setView] = React.useState('grid'); // 'grid' | 'list' | 'table'

  const topLevel = SAMPLE.collections.filter(c => !c.parentId);

  const viewOptions = [
    { id: 'grid',  label: 'Grid',         icon: I.Grid, desc: 'Cards with previews' },
    { id: 'list',  label: 'List',         icon: I.List, desc: 'Accordion with nested' },
    { id: 'table', label: 'Table',        icon: I.Sort, desc: 'Dense spreadsheet rows' },
  ];

  return (
    <div className="main-inner">
      <div className="page-head">
        <div>
          <span className="page-section-chip chip-muted">
            <I.Folder className="icon icon-xs" style={{width:10,height:10}} /> Collections
          </span>
          <h1 className="page-title">Collections</h1>
          <p className="page-subtitle">
            {topLevel.length} top-level · {SAMPLE.collections.length} total · {SAMPLE.collections.reduce((a,c)=>a+c.count,0)} bookmarks
          </p>
        </div>
        <div className="page-actions">
          <ViewToggle view={view} onChange={setView} options={viewOptions} />
          <button className="btn btn-ghost btn-sm hide-mobile"><I.Sparkle className="icon icon-sm" /> Suggest collections</button>
          <button className="btn btn-primary btn-sm"><I.Plus className="icon icon-sm" /> New collection</button>
        </div>
      </div>

      {view === 'grid'  && <CollectionsGrid onOpenCollection={onOpenCollection} />}
      {view === 'list'  && <CollectionsAccordion onOpenCollection={onOpenCollection} />}
      {view === 'table' && <CollectionsTable onOpenCollection={onOpenCollection} />}

      <div style={{height:48}} />
    </div>
  );
}

// ─── GRID VIEW ───
function CollectionsGrid({ onOpenCollection }) {
  const topLevel = SAMPLE.collections.filter(c => !c.parentId);

  return (
    <div className="collections-grid" style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px, 1fr))', gap:12}}>
      {topLevel.map((c, i) => {
        const sample = SAMPLE.bookmarksInCollectionTree(c.id).slice(0, 3);
        const children = SAMPLE.childCollections(c.id);
        return (
          <div
            key={c.id}
            className="card fade-up"
            style={{padding:16, cursor:'pointer', transition:'box-shadow var(--t-base) var(--ease), transform var(--t-base) var(--ease), border-color var(--t-base) var(--ease)', animationDelay:`${i*0.03}s`, display:'flex', flexDirection:'column'}}
            onClick={() => onOpenCollection(c.id)}
            onMouseEnter={e => { e.currentTarget.style.boxShadow='var(--shadow-sm)'; e.currentTarget.style.transform='translateY(-1px)'; }}
            onMouseLeave={e => { e.currentTarget.style.boxShadow='none'; e.currentTarget.style.transform='translateY(0)'; }}
          >
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12}}>
              <div style={{
                width:32, height:32, borderRadius:9,
                background: c.color + '22',
                color: c.color,
                display:'inline-flex', alignItems:'center', justifyContent:'center',
              }}>
                <I.Folder className="icon icon-sm" />
              </div>
              <button className="btn-icon" onClick={(e)=>e.stopPropagation()}><I.More className="icon icon-sm" /></button>
            </div>

            <div style={{fontSize:14, fontWeight:600, color:'var(--text-1)', marginBottom:2, letterSpacing:'-0.01em'}}>{c.name}</div>
            <div style={{fontSize:11, color:'var(--text-4)', marginBottom:12}}>
              {SAMPLE.bookmarksInCollectionTree(c.id).length} bookmarks
              {children.length > 0 && <> · <span style={{color:'var(--text-3)'}}>{children.length} nested</span></>}
              · updated 2h ago
            </div>

            {/* Nested-collections chip row */}
            {children.length > 0 && (
              <div style={{display:'flex', flexWrap:'wrap', gap:4, marginBottom:12}}>
                {children.slice(0, 4).map(ch => (
                  <button
                    key={ch.id}
                    className="nested-chip"
                    onClick={(e) => { e.stopPropagation(); onOpenCollection(ch.id); }}
                    style={{'--chip-color': ch.color}}
                  >
                    <span className="dot" style={{background: ch.color}}></span>
                    {ch.name}
                    <span className="nested-chip-count">{ch.count}</span>
                  </button>
                ))}
                {children.length > 4 && (
                  <span className="nested-chip nested-chip-more">+{children.length - 4} more</span>
                )}
              </div>
            )}

            {/* Sample bookmarks */}
            <div style={{display:'flex', flexDirection:'column', gap:6, paddingTop:10, borderTop:'0.5px solid var(--border-sub)', marginTop:'auto'}}>
              {sample.map(s => (
                <div key={s.id} style={{fontSize:11, color:'var(--text-3)', whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis', display:'flex', alignItems:'center', gap:6}}>
                  <span className="b-thumb" style={{background: s.thumbColor + '22', color: s.thumbColor, width:18, height:18, fontSize:8, borderRadius:4}}>{s.thumb}</span>
                  {s.title}
                </div>
              ))}
              {sample.length === 0 && (
                <div style={{fontSize:11, color:'var(--text-4)', fontStyle:'italic'}}>No bookmarks yet</div>
              )}
            </div>
          </div>
        );
      })}

      {/* New collection card */}
      <div
        className="card"
        style={{padding:16, cursor:'pointer', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', minHeight:240, color:'var(--text-4)', borderStyle:'dashed', transition:'background-color var(--t-fast)'}}
        onMouseEnter={e => e.currentTarget.style.background='var(--surface-2)'}
        onMouseLeave={e => e.currentTarget.style.background='var(--surface)'}
      >
        <div style={{width:32, height:32, borderRadius:9, background:'var(--surface-3)', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom:10}}>
          <I.Plus className="icon icon-sm" />
        </div>
        <div style={{fontSize:13, fontWeight:600, color:'var(--text-3)'}}>New collection</div>
        <div style={{fontSize:11, color:'var(--text-4)', marginTop:2}}>Or use AI to suggest</div>
      </div>
    </div>
  );
}

// ─── LIST / ACCORDION VIEW ───
function CollectionsAccordion({ onOpenCollection }) {
  const topLevel = SAMPLE.collections.filter(c => !c.parentId);
  const [expanded, setExpanded] = React.useState(new Set(['ai', 'design'])); // start with AI & Design open

  const toggle = (id) => {
    const next = new Set(expanded);
    next.has(id) ? next.delete(id) : next.add(id);
    setExpanded(next);
  };

  return (
    <div className="card" style={{padding: 0, overflow:'hidden'}}>
      {topLevel.map((c, i) => {
        const children = SAMPLE.childCollections(c.id);
        const hasChildren = children.length > 0;
        const isExpanded = expanded.has(c.id);
        const totalInTree = SAMPLE.bookmarksInCollectionTree(c.id).length;

        return (
          <div key={c.id} className={`acc-row ${i === 0 ? 'first' : ''}`}>
            <div className="acc-parent">
              {/* Chevron */}
              <button
                className="acc-chevron"
                onClick={() => hasChildren && toggle(c.id)}
                aria-label={isExpanded ? 'Collapse' : 'Expand'}
                style={{visibility: hasChildren ? 'visible' : 'hidden'}}
              >
                <I.ChevronRight
                  className="icon icon-xs"
                  style={{
                    transform: isExpanded ? 'rotate(90deg)' : 'rotate(0)',
                    transition: 'transform var(--t-fast) var(--ease)',
                  }}
                />
              </button>

              {/* Folder + name */}
              <button className="acc-name-btn" onClick={() => onOpenCollection(c.id)}>
                <div className="acc-folder" style={{background: c.color + '22', color: c.color}}>
                  <I.Folder className="icon icon-sm" />
                </div>
                <div className="acc-name-stack">
                  <div className="acc-name">{c.name}</div>
                  <div className="acc-meta">
                    {c.count} direct
                    {hasChildren && <> · <span>{children.length} nested · {totalInTree} total</span></>}
                  </div>
                </div>
              </button>

              {/* Right: pills + actions */}
              <div className="acc-right">
                {hasChildren && (
                  <span className="acc-children-count">
                    <I.Folder className="icon icon-xs" /> {children.length}
                  </span>
                )}
                <span className="acc-bookmark-count">{totalInTree}</span>
                <button
                  className="btn-icon tooltip-host"
                  data-tip="Add nested"
                  onClick={(e) => e.stopPropagation()}
                ><I.Plus className="icon icon-sm" /></button>
                <button
                  className="btn-icon tooltip-host"
                  data-tip="More"
                  onClick={(e) => e.stopPropagation()}
                ><I.More className="icon icon-sm" /></button>
              </div>
            </div>

            {/* Nested children */}
            {isExpanded && hasChildren && (
              <div className="acc-children">
                {children.map(child => (
                  <div key={child.id} className="acc-child">
                    <span className="acc-child-rail" />
                    <button className="acc-name-btn child" onClick={() => onOpenCollection(child.id)}>
                      <div className="acc-folder small" style={{background: child.color + '22', color: child.color}}>
                        <I.Folder className="icon icon-xs" />
                      </div>
                      <div className="acc-name-stack">
                        <div className="acc-name child-name">{child.name}</div>
                        <div className="acc-meta">{child.count} bookmarks</div>
                      </div>
                    </button>
                    <div className="acc-right">
                      <span className="acc-bookmark-count">{child.count}</span>
                      <button className="btn-icon tooltip-host" data-tip="More" onClick={(e) => e.stopPropagation()}>
                        <I.More className="icon icon-sm" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─── TABLE VIEW — all bookmarks using the shared BookmarksTable component ───
function CollectionsTable({ onOpenCollection }) {
  const allBookmarks = SAMPLE.bookmarks;
  const [selected, setSelected] = React.useState(new Set());
  const [page, setPage] = React.useState(1);

  const PAGE_SIZE = 50;
  const totalPages = Math.max(1, Math.ceil(allBookmarks.length / PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const pageRows = allBookmarks.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);

  const toggle = (id) => {
    const s = new Set(selected);
    s.has(id) ? s.delete(id) : s.add(id);
    setSelected(s);
  };
  const toggleAll = () => {
    const allSel = pageRows.every(b => selected.has(b.id));
    const s = new Set(selected);
    if (allSel) pageRows.forEach(b => s.delete(b.id));
    else pageRows.forEach(b => s.add(b.id));
    setSelected(s);
  };

  // Clicking a row navigates to the bookmark's collection detail
  const handleOpen = (id) => {
    const b = SAMPLE.bookmarks.find(bk => bk.id === id);
    if (b) onOpenCollection(b.collection);
  };

  return (
    <React.Fragment>
      <BookmarksTable
        rows={pageRows}
        selected={selected}
        onToggle={toggle}
        onToggleAll={toggleAll}
        onOpenBookmark={handleOpen}
      />
      {allBookmarks.length > PAGE_SIZE && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          totalItems={allBookmarks.length}
          pageSize={PAGE_SIZE}
          onPage={setPage}
        />
      )}
    </React.Fragment>
  );
}

window.CollectionsPage = CollectionsPage;