/* ===== Page views ===== */

/* ---------- Dashboard home ---------- */
function DashboardView({ nav, favs, toggleFav }) {
  const total = window.SECTIONS.length;
  const catCount = window.CATEGORIES.length;
  const myDownloads = window.getMyDownloads ? window.getMyDownloads() : 0;

  const [tab, setTab] = useState('recent');
  const recent = window.SECTIONS.slice()
    .sort((a, b) => new Date(b.added) - new Date(a.added)).slice(0, 6);
  const popular = window.SECTIONS.slice()
    .sort((a, b) => b.popularity - a.popularity).slice(0, 6);
  const topCats = window.CATEGORIES.slice()
    .sort((a, b) => window.catCount(b.id) - window.catCount(a.id)).slice(0, 6);
  const feed = tab === 'recent' ? recent : popular;

  const openCat = (c) => nav({ view: 'category', catId: c.id });
  const openSec = (s) => nav({ view: 'section', sectionId: s.id });

  const spark = [40, 62, 34, 74, 52, 90, 64];

  return (
    <div className="content-inner">
      <div className="dash">

        {/* KPI row */}
        <div className="kpi-row">
          <section className="kpi kpi-navy fade-up" data-screen-label="Sections Available">
            <div className="kpi-head">
              <span className="kpi-ico"><Icon name="library" size={20} /></span>
              <span className="kpi-pill">Live library</span>
            </div>
            <div className="kpi-num">{total}</div>
            <div className="kpi-cap">Sections Available</div>
            <div className="kpi-spark">
              {spark.map((h, i) => <span key={i} className={i === 5 ? 'hot' : ''} style={{ height: h + '%' }} />)}
            </div>
          </section>

          <section className="kpi fade-up" data-screen-label="Categories">
            <div className="kpi-head">
              <span className="kpi-ico tint-purple"><Icon name="collections" size={20} /></span>
            </div>
            <div className="kpi-num">{catCount}</div>
            <div className="kpi-cap">Categories</div>
            <button className="kpi-link" onClick={() => nav({ view: 'browse' })}>Browse all <Icon name="arrow" size={13} /></button>
          </section>

          <section className="kpi fade-up" data-screen-label="Your Downloads">
            <div className="kpi-head">
              <span className="kpi-ico tint-teal"><Icon name="download" size={20} /></span>
            </div>
            <div className="kpi-num">{myDownloads}</div>
            <div className="kpi-cap">Your Downloads</div>
            <span className="kpi-sub">HTML &amp; React exports</span>
          </section>

          <section className="kpi kpi-lime fade-up" data-screen-label="Favorites">
            <div className="kpi-head">
              <span className="kpi-ico"><Icon name="heart" size={20} /></span>
            </div>
            <div className="kpi-num">{favs.length}</div>
            <div className="kpi-cap">Favorites</div>
            <button className="kpi-link" onClick={() => nav({ view: 'favorites' })}>View saved <Icon name="arrow" size={13} /></button>
          </section>
        </div>

        {/* Browse by Category (left) + tabbed feed (right) */}
        <div className="dash-split">
          <section className="dash-cats">
            <div className="split-head">
              <h2 className="sec-title">Browse by Category</h2>
            </div>
            <div className="cat-rows">
              {topCats.map(c => <CatRow key={c.id} cat={c} onOpen={openCat} />)}
            </div>
            <button className="cat-rows-all" onClick={() => nav({ view: 'browse' })}>
              All categories <Icon name="arrow" size={14} />
            </button>
          </section>

          <section className="dash-feed">
            <div className="split-head feed-tabs">
              <button className={'feed-tab' + (tab === 'recent' ? ' active' : '')} onClick={() => setTab('recent')}>Recently Added</button>
              <button className={'feed-tab' + (tab === 'popular' ? ' active' : '')} onClick={() => setTab('popular')}>Most Popular Items</button>
            </div>
            <div className="sec-rows">
              {feed.map((s, i) => <SectionRow key={s.id} section={s} onOpen={openSec} rank={tab === 'popular' ? i + 1 : null} />)}
            </div>
          </section>
        </div>

      </div>
    </div>
  );
}

/* ---------- Browse / library ---------- */
function BrowseView({ nav, favs, toggleFav, search, route }) {
  const [cats, setCats] = useState(route.catId ? [route.catId] : []);
  const [fw, setFw] = useState('all');
  const [sort, setSort] = useState(route.sort || 'popular');

  let list = window.SECTIONS.filter(s => {
    if (cats.length && !cats.includes(s.category)) return false;
    if (fw !== 'all' && !s.frameworks.includes(fw)) return false;
    if (search) {
      const q = search.toLowerCase();
      const hay = (s.name + ' ' + s.tags.join(' ') + ' ' + window.catById(s.category).label).toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  });
  list = list.sort((a, b) =>
    sort === 'new' ? new Date(b.added) - new Date(a.added) :
    sort === 'downloads' ? b.downloads - a.downloads :
    b.popularity - a.popularity);

  return (
    <div className="content-inner">
      <div className="h-row" style={{ marginBottom: 18 }}>
        <div>
          <span className="eyebrow">Library</span>
          <h2 style={{ fontSize: 28, marginTop: 6 }}>Browse all sections</h2>
        </div>
        <button className="btn btn-primary" onClick={() => nav({ view: 'add' })}>
          <Icon name="plus" size={16} /> Add New Section
        </button>
      </div>

      <div className="browse-filters">
        <div className="browse-filters-left">
          <MultiCatSelect cats={cats} setCats={setCats} />
          <span className="results-count">{list.length} {list.length === 1 ? 'result' : 'results'}{search ? ' for “' + search + '”' : ''}</span>
        </div>
        <div className="browse-filters-right">
          <div className="seg">
            {['all', 'html', 'react'].map(f =>
              <button key={f} className={fw === f ? 'active' : ''} onClick={() => setFw(f)}>{f === 'all' ? 'All' : f.toUpperCase()}</button>)}
          </div>
          <div className="select-wrap">
            <select className="btn t-input" value={sort} onChange={e => setSort(e.target.value)}>
              <option value="popular">Most popular</option>
              <option value="new">Newest</option>
              <option value="downloads">Most downloaded</option>
            </select>
            <span className="select-chev"><Icon name="arrow" size={14} /></span>
          </div>
        </div>
      </div>

      {cats.length > 0 && (
        <div className="active-cats">
          {cats.map(id => {
            const c = window.catById(id);
            return (
              <button key={id} className="active-cat" onClick={() => setCats(cats.filter(x => x !== id))} title="Remove filter">
                <CatDot cat={c} /> {c.label} <Icon name="x" size={12} />
              </button>
            );
          })}
          <button className="active-cat-clear" onClick={() => setCats([])}>Clear all</button>
        </div>
      )}

      {list.length === 0
        ? <EmptyState />
        : <div className="card-grid">
            {list.map(s => <SectionCard key={s.id} section={s} fav={favs.includes(s.id)} onFav={toggleFav}
              onOpen={(sec) => nav({ view: 'section', sectionId: sec.id })} />)}
          </div>}
    </div>
  );
}

/* ---------- Category detail ---------- */
function CategoryView({ nav, favs, toggleFav, route }) {
  const cat = window.catById(route.catId);
  const list = window.SECTIONS.filter(s => s.category === cat.id).sort((a, b) => b.popularity - a.popularity);
  return (
    <div className="content-inner">
      <button className="btn btn-ghost btn-sm" style={{ marginBottom: 18 }} onClick={() => nav({ view: 'browse' })}>
        <Icon name="back" size={15} /> Library
      </button>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 28 }}>
        <div className="cat-tile-ico" style={{ width: 56, height: 56, borderRadius: 16, background: cat.color + '1e', color: cat.color }}>
          <Icon name={cat.icon} size={28} />
        </div>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 28, letterSpacing: '-.02em', margin: '0 0 4px' }}>{cat.label}</h1>
          <p style={{ margin: 0, color: 'var(--text-2)' }}>{cat.blurb} · {list.length} sections</p>
        </div>
      </div>
      <div className="card-grid">
        {list.map(s => <SectionCard key={s.id} section={s} fav={favs.includes(s.id)} onFav={toggleFav}
          onOpen={(sec) => nav({ view: 'section', sectionId: sec.id })} />)}
      </div>
    </div>
  );
}

/* ---------- Collections ---------- */
function CollectionsView({ nav, favs, toggleFav }) {
  return (
    <div className="content-inner">
      <span className="eyebrow">Curated</span>
      <h2 style={{ fontSize: 28, margin: '6px 0 4px' }}>Collections</h2>
      <p style={{ color: 'var(--text-2)', marginTop: 0, marginBottom: 28 }}>Hand-picked bundles ready to assemble into full pages.</p>
      <div style={{ display: 'grid', gap: 30 }}>
        {window.COLLECTIONS.map(col => {
          const items = col.items.map(window.sectionById).filter(Boolean);
          return (
            <div key={col.id}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
                <div style={{ width: 46, height: 46, borderRadius: 13, background: col.grad, flex: 'none' }} />
                <div style={{ flex: 1 }}>
                  <h3 style={{ margin: 0, fontFamily: 'var(--font-display)', fontSize: 18 }}>{col.name}</h3>
                  <p style={{ margin: '3px 0 0', color: 'var(--text-2)', fontSize: 14 }}>{col.desc} · {items.length} sections</p>
                </div>
              </div>
              <div className="card-grid">
                {items.map(s => <SectionCard key={s.id} section={s} fav={favs.includes(s.id)} onFav={toggleFav}
                  onOpen={(sec) => nav({ view: 'section', sectionId: sec.id })} />)}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- Favorites ---------- */
function FavoritesView({ nav, favs, toggleFav }) {
  const list = favs.map(window.sectionById).filter(Boolean);
  return (
    <div className="content-inner">
      <span className="eyebrow">Saved</span>
      <h2 style={{ fontSize: 28, margin: '6px 0 4px' }}>Your favorites</h2>
      <p style={{ color: 'var(--text-2)', marginTop: 0, marginBottom: 28 }}>{list.length} saved {list.length === 1 ? 'section' : 'sections'}.</p>
      {list.length === 0
        ? <EmptyState heart />
        : <div className="card-grid">
            {list.map(s => <SectionCard key={s.id} section={s} fav={true} onFav={toggleFav}
              onOpen={(sec) => nav({ view: 'section', sectionId: sec.id })} />)}
          </div>}
    </div>
  );
}

/* ---------- Section detail ---------- */
function SectionView({ nav, favs, toggleFav, route, notify, refresh }) {
  const section = window.sectionById(route.sectionId);
  const cat = window.catById(section.category);
  const isCustom = window.SectionStore.isCustom(section.id);
  const isEdited = window.SectionStore.isEdited(section.id);
  const [confirmDel, setConfirmDel] = useState(false);
  const [device, setDevice] = useState('desktop');
  const widths = { desktop: 1280, tablet: 834, mobile: 390 };
  const isFav = favs.includes(section.id);
  const related = window.SECTIONS.filter(s => s.category === cat.id && s.id !== section.id).slice(0, 3);

  useEffect(() => {
    const el = document.querySelector('.content');
    if (el) el.scrollTop = 0;
  }, [route.sectionId]);

  return (
    <div className="content-inner">
      <button className="btn btn-ghost btn-sm back" style={{ marginBottom: 14 }}
        onClick={() => nav({ view: 'category', catId: cat.id })}>
        <Icon name="back" size={15} /> {cat.label}
      </button>
      <div className="detail-head">
        <div className="detail-title">
          <h1>{section.name}</h1>
          <div className="meta">
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><CatDot cat={cat} /> {cat.label}</span>
            <span>·</span>
            <span><Icon name="download" size={13} style={{ verticalAlign: '-2px' }} /> {section.downloads.toLocaleString()} downloads</span>
            <span>·</span>
            <span>Added {window.timeAgo(section.added)}</span>
            {section.pro && <span className="badge pro"><Icon name="star" size={11} /> Pro</span>}
            {isCustom && <span className="tag-custom">Custom</span>}
            {isEdited && <span className="tag-custom" style={{ color: '#d97706', background: 'color-mix(in srgb,#f59e0b 14%,var(--surface))', borderColor: 'color-mix(in srgb,#f59e0b 30%,var(--surface))' }}>Edited</span>}
          </div>
        </div>
        <div className="detail-actions">
          {confirmDel
            ? <div className="confirm-row" style={{ border: '1px solid color-mix(in srgb,#ef4444 30%,var(--border))', borderRadius: 'var(--r-sm)', padding: '0 6px 0 12px', height: 32 }}>
                <span>Delete this section?</span>
                <button className="btn btn-sm" style={{ color: '#ef4444', borderColor: 'color-mix(in srgb,#ef4444 30%,var(--border))' }}
                  onClick={() => { window.SectionStore.remove(section.id); refresh && refresh(); notify && notify(isCustom ? 'Section deleted' : 'Built-in section removed'); nav(isCustom ? { view: 'manage' } : { view: 'category', catId: cat.id }); }}>
                  <Icon name="trash" size={15} /> Yes, delete
                </button>
                <button className="btn btn-sm btn-ghost" onClick={() => setConfirmDel(false)}>Cancel</button>
              </div>
            : <>
                {isEdited && <button className="btn btn-sm" onClick={() => { window.SectionStore.restore(section.id); refresh && refresh(); notify && notify('Restored to original'); nav({ view: 'section', sectionId: section.id }); }} title="Undo your edits"><Icon name="back" size={15} /> Restore</button>}
                <button className="btn btn-sm" onClick={() => nav({ view: 'add', editId: section.id })}><Icon name="edit" size={15} /> Edit</button>
                <button className="btn btn-sm" onClick={() => setConfirmDel(true)}
                  style={{ color: '#ef4444', borderColor: 'color-mix(in srgb,#ef4444 30%,var(--border))' }}><Icon name="trash" size={15} /> Delete</button>
              </>}
          <button className={'btn btn-sm' + (isFav ? '' : '')} onClick={() => toggleFav(section.id)}
            style={isFav ? { color: '#ef4444', borderColor: 'color-mix(in srgb,#ef4444 30%,var(--border))' } : {}}>
            <Icon name="heart" size={15} /> {isFav ? 'Saved' : 'Save'}
          </button>
          <div className="seg">
            {[['desktop', 'desktop'], ['tablet', 'device'], ['mobile', 'device']].map(([d, ic]) =>
              <button key={d} className={device === d ? 'active' : ''} onClick={() => setDevice(d)} title={d}>
                <Icon name={ic} size={15} />
              </button>)}
          </div>
        </div>
      </div>

      <div className="preview-shell">
        <div className="preview-bar">
          <div className="dots"><i></i><i></i><i></i></div>
          <div className="preview-url"><Icon name="lock" size={12} /> sectionly.app/preview/{section.id}</div>
          <span style={{ flex: 1 }} />
          <button className="btn btn-sm" style={{ height: 30 }} onClick={() => window.openFullPreview(section)} title="Open the full preview in a new tab">
            <Icon name="external" size={14} /> Open full view
          </button>
          <span style={{ fontSize: 12.5, color: 'var(--text-3)', fontWeight: 600 }}>{widths[device]}px</span>
        </div>
        <div className="preview-stage">
          <div style={{ width: '100%', maxWidth: widths[device], transition: 'max-width .25s var(--ease)' }}>
            <ScaledFrame key={section.id + device} section={section} mode="fit" logicalWidth={widths[device]} maxScale={1} />
          </div>
        </div>
      </div>

      <CodePanel section={section} />

      {related.length > 0 && <>
        <div className="h-row" style={{ marginTop: 40 }}>
          <div><h2>More in {cat.label}</h2></div>
          <button className="link-more" onClick={() => nav({ view: 'category', catId: cat.id })}>View all <Icon name="arrow" size={15} /></button>
        </div>
        <div className="card-grid">
          {related.map(s => <SectionCard key={s.id} section={s} fav={favs.includes(s.id)} onFav={toggleFav}
            onOpen={(sec) => nav({ view: 'section', sectionId: sec.id })} />)}
        </div>
      </>}
    </div>
  );
}

/* ---------- Empty state ---------- */
function EmptyState({ heart }) {
  return (
    <div className="empty">
      <Icon name={heart ? 'heart' : 'search'} size={46} />
      <h3>{heart ? 'No favorites yet' : 'No sections found'}</h3>
      <p>{heart ? 'Tap the heart on any section to save it here.' : 'Try a different search or category filter.'}</p>
    </div>
  );
}

Object.assign(window, { DashboardView, BrowseView, CategoryView, CollectionsView, FavoritesView, SectionView, EmptyState });
