// screens.jsx — Library, Search, Actress for VideoHub

const { useState, useMemo, useRef, useEffect } = React;

// ═══════════════════════════════════════════════════════════════
// LIBRARY — Smart Collections rail, grid/list, click → detail
// ═══════════════════════════════════════════════════════════════
function LibraryScreen({ items, locked, accent, onOpenVideo, onOpenAdd, loading }) {
  const [layout, setLayout] = useState('grid');     // grid | list
  const [collection, setCollection] = useState('all');

  const filtered = useMemo(() => {
    return window.applySmartCollection(items, collection);
  }, [items, collection]);

  return (
    <div style={{ paddingBottom: 140 }}>
      <window.TopBar
        topPad={locked.topPad}
        title="Library"
        subtitle={`${items.length} saved`}
        locked={locked.value}
        onToggleLock={locked.toggle}
        accent={accent}
        right={
          <button
            onClick={() => setLayout(layout === 'grid' ? 'list' : 'grid')}
            style={{
              width: 36, height: 36, borderRadius: 99, border: 'none', cursor: 'pointer',
              background: 'rgba(255,255,255,0.07)', color: window.VH_TEXT,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
            {layout === 'grid' ? (
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M2 4h12M2 8h12M2 12h12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
            ) : (
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                <rect x="2" y="2" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.5"/>
                <rect x="9" y="2" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.5"/>
                <rect x="2" y="9" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.5"/>
                <rect x="9" y="9" width="5" height="5" rx="1" stroke="currentColor" strokeWidth="1.5"/>
              </svg>
            )}
          </button>
        }
      />

      {/* Smart collection rail */}
      <div style={{
        display: 'flex', gap: 8, padding: '6px 16px 14px', overflowX: 'auto',
        scrollbarWidth: 'none',
      }}>
        {window.SMART_COLLECTIONS.map(f => {
          const count = f.id === 'all' ? items.length : window.applySmartCollection(items, f.id).length;
          if (f.id !== 'all' && count === 0) return null;
          return (
            <window.Chip key={f.id}
              active={collection === f.id}
              onClick={() => setCollection(f.id)}
              accent={accent}>
              {f.label}{count !== undefined && f.id === 'all' ? ` · ${count}` : count > 0 ? ` · ${count}` : ''}
            </window.Chip>
          );
        })}
      </div>

      {/* body */}
      {loading ? (
        <PosterGrid items={[]} locked={locked.value} accent={accent} loading={true}/>
      ) : filtered.length === 0 ? (
        <EmptyState accent={accent} signedIn={locked.signedIn} onOpenAuth={locked.openAuth} onAdd={onOpenAdd}/>
      ) : layout === 'grid' ? (
        <PosterGrid items={filtered} locked={locked.value} accent={accent} onClick={onOpenVideo}/>
      ) : (
        <RowList items={filtered} locked={locked.value} accent={accent} onClick={onOpenVideo}/>
      )}
    </div>
  );
}

function PosterGrid({ items, locked, accent, onOpenActress, onClick, loading }) {
  if (loading) {
    return (
      <div className="vh-video-grid">
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i}>
            <div className="vh-skel" style={{ aspectRatio: '2 / 3', borderRadius: 12 }}/>
            <div className="vh-skel" style={{ height: 10, width: '40%', marginTop: 10 }}/>
            <div className="vh-skel" style={{ height: 12, width: '85%', marginTop: 6 }}/>
            <div className="vh-skel" style={{ height: 10, width: '60%', marginTop: 4 }}/>
          </div>
        ))}
      </div>
    );
  }
  return (
    <div className="vh-video-grid">
      {items.map(it => (
        <button key={it.id}
          onClick={onClick ? () => onClick(it.id) : undefined}
          disabled={!onClick}
          className="vh-tap vh-card"
          style={{
            minWidth: 0, background: 'transparent', border: 'none', padding: 0,
            color: window.VH_TEXT, textAlign: 'left',
            cursor: onClick ? 'pointer' : 'default', fontFamily: 'inherit',
          }}>
          <window.PosterTile code={it.code} status={it.status} locked={locked} accent={accent} coverUrl={it.coverUrl}/>
          <div style={{ marginTop: 9, minWidth: 0 }}>
            <div style={{
              fontSize: 10, letterSpacing: 0.8, fontWeight: 600,
              fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
              color: window.VH_DIM, marginBottom: 2,
            }}>{locked ? '••••••' : it.code}</div>
            <div style={{
              fontSize: 13.5, color: window.VH_TEXT, fontWeight: 600,
              overflow: 'hidden', textOverflow: 'ellipsis',
              display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical',
              filter: locked ? 'blur(5px)' : 'none',
            }}>{it.title}</div>
            <div style={{
              fontSize: 12, color: window.VH_DIM,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              marginTop: 1,
              filter: locked ? 'blur(5px)' : 'none',
            }} onClick={() => onOpenActress?.(it.actresses[0])}>
              {it.actresses.join(', ')}
            </div>
            {!locked && (it.sourceBadges || []).length > 0 && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 6 }}>
                {(it.sourceBadges || []).slice(0, 2).map(label => (
                  <span key={label} style={{
                    display: 'inline-flex', alignItems: 'center', height: 20,
                    padding: '0 7px', borderRadius: 99,
                    background: 'rgba(255,255,255,0.05)', border: `0.5px solid ${window.VH_HAIRLINE}`,
                    color: window.VH_DIM, fontSize: 10.5, fontWeight: 700,
                  }}>{label}</span>
                ))}
              </div>
            )}
            <div style={{ marginTop: 6 }}>
              <window.RatingDots value={it.rating} accent={accent}/>
            </div>
          </div>
        </button>
      ))}
    </div>
  );
}

function RowList({ items, locked, accent, onClick }) {
  return (
    <div style={{ padding: '4px 12px' }}>
      {items.map((it, idx) => (
        <button key={it.id}
          onClick={onClick ? () => onClick(it.id) : undefined}
          disabled={!onClick}
          className="vh-tap"
          style={{
            display: 'flex', gap: 12, padding: '10px 4px',
            borderBottom: idx === items.length - 1 ? 'none' : `0.5px solid ${window.VH_HAIRLINE}`,
            alignItems: 'center', width: '100%',
            background: 'transparent', border: 'none', textAlign: 'left',
            color: window.VH_TEXT, fontFamily: 'inherit',
            cursor: onClick ? 'pointer' : 'default',
          }}>
          <div style={{ width: 52, flexShrink: 0 }}>
            <window.PosterTile code={it.code} status={it.status} locked={locked} accent={accent} ratio="3 / 4" coverUrl={it.coverUrl}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'ui-monospace, "SF Mono", Menlo, monospace',
              fontSize: 10, letterSpacing: 0.6, fontWeight: 600,
              color: window.VH_DIM,
            }}>{locked ? '••••••' : it.code}</div>
            <div style={{
              fontSize: 14, color: window.VH_TEXT, fontWeight: 600,
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              filter: locked ? 'blur(5px)' : 'none',
              marginTop: 1,
            }}>{it.title}</div>
            <div style={{
              fontSize: 12, color: window.VH_DIM, marginTop: 2,
              filter: locked ? 'blur(5px)' : 'none',
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>{it.actresses.join(', ')}{it.studio ? ' · ' + it.studio : ''}</div>
            {!locked && (it.sourceBadges || []).length > 0 && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                {(it.sourceBadges || []).slice(0, 2).map(label => (
                  <span key={label} style={{
                    display: 'inline-flex', alignItems: 'center', height: 20,
                    padding: '0 7px', borderRadius: 99,
                    background: 'rgba(255,255,255,0.05)', border: `0.5px solid ${window.VH_HAIRLINE}`,
                    color: window.VH_DIM, fontSize: 10.5, fontWeight: 700,
                  }}>{label}</span>
                ))}
              </div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}>
              <window.StatusPill status={it.status} compact/>
              <window.RatingDots value={it.rating} accent={accent}/>
            </div>
          </div>
          {onClick && (
            <svg width="10" height="10" viewBox="0 0 10 10" style={{ color: window.VH_DIM2, flexShrink: 0 }}>
              <path d="M3 1l4 4-4 4" stroke="currentColor" strokeWidth="1.6" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          )}
        </button>
      ))}
    </div>
  );
}

function EmptyState({ accent, signedIn, onOpenAuth, onAdd }) {
  return (
    <div style={{
      padding: '60px 28px', textAlign: 'center', color: window.VH_DIM,
    }}>
      <div className={signedIn ? '' : 'vh-lock-glow'} style={{
        width: 72, height: 72, borderRadius: 18, margin: '0 auto 18px',
        background: `linear-gradient(135deg, ${accent}33, ${accent}11)`,
        border: `0.5px solid ${accent}55`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {signedIn ? (
          <svg width="28" height="28" viewBox="0 0 26 26" fill="none">
            <path d="M13 5v16M5 13h16" stroke={accent} strokeWidth="2" strokeLinecap="round"/>
          </svg>
        ) : (
          <svg width="22" height="26" viewBox="0 0 20 22" fill="none">
            <rect x="3" y="10" width="14" height="10" rx="2" stroke={accent} strokeWidth="1.8"/>
            <path d="M6 10V6.5a4 4 0 018 0V10" stroke={accent} strokeWidth="1.8"/>
          </svg>
        )}
      </div>
      <div style={{ color: window.VH_TEXT, fontSize: 17, fontWeight: 700, marginBottom: 6, letterSpacing: -0.2 }}>
        {signedIn ? 'Nothing here yet' : 'Unlock your private library'}
      </div>
      <div style={{ fontSize: 13, lineHeight: 1.55, maxWidth: 280, margin: '0 auto' }}>
        {signedIn
          ? 'Tap the + button to save your first code. Everything stays private.'
          : 'Sign in to see your real saves. Codes, titles, and cast stay hidden until you do.'}
      </div>
      <button onClick={signedIn ? onAdd : onOpenAuth} className="vh-tap" style={{
        marginTop: 20, padding: '11px 22px', borderRadius: 99, border: 'none',
        background: accent, color: '#fff', fontSize: 13, fontWeight: 600,
        cursor: 'pointer', fontFamily: 'inherit',
        boxShadow: `0 8px 24px ${accent}44, 0 1px 0 rgba(255,255,255,0.18) inset`,
      }}>
        {signedIn ? '+  Add via URL' : 'Unlock library'}
      </button>
    </div>
  );
}


// ═══════════════════════════════════════════════════════════════
// SEARCH — code-normalized, multi-field, click → detail
// ═══════════════════════════════════════════════════════════════
function SearchScreen({ items, locked, accent, onOpenVideo, onOpenCast }) {
  const [q, setQ] = useState('');
  const [statusFilter, setStatusFilter] = useState(null);
  const [studioFilter, setStudioFilter] = useState(null);
  const [ratingFilter, setRatingFilter] = useState(0);
  const [sort, setSort] = useState('added');

  const studios = useMemo(() => [...new Set(items.map(i => i.studio).filter(Boolean))], [items]);

  const results = useMemo(() => {
    const term = q.trim().toLowerCase();
    const normTerm = window.VHCast.normalizeCode(term);
    let out = items.filter(it => {
      if (statusFilter && it.status !== statusFilter) return false;
      if (studioFilter && it.studio !== studioFilter) return false;
      if (ratingFilter && (it.rating || 0) < ratingFilter) return false;
      if (!term) return true;
      const codeNorm = window.VHCast.normalizeCode(it.code || '');
      return (
        codeNorm.includes(normTerm) ||
        it.code?.toLowerCase().includes(term) ||
        (it.title || '').toLowerCase().includes(term) ||
        (it.actresses || []).join(' ').toLowerCase().includes(term) ||
        (it.studio || '').toLowerCase().includes(term) ||
        (it.tags || []).join(' ').toLowerCase().includes(term) ||
        (it.note || '').toLowerCase().includes(term) ||
        (it.sourceUrl || '').toLowerCase().includes(term) ||
        (it.sourceDomain || '').toLowerCase().includes(term)
      );
    });
    if (sort === 'rating')  out = [...out].sort((a,b) => (b.rating||0) - (a.rating||0));
    if (sort === 'code')    out = [...out].sort((a,b) => (a.code||'').localeCompare(b.code||''));
    if (sort === 'watched') out = [...out].sort((a,b) => (b.watchedAt || 0) - (a.watchedAt || 0));
    if (sort === 'added')   out = [...out].sort((a,b) => (b.createdAt || 0) - (a.createdAt || 0));
    return out;
  }, [items, q, statusFilter, studioFilter, ratingFilter, sort]);

  const recents = useMemo(() => {
    const out = new Set();
    items.slice(0, 8).forEach(i => {
      (i.actresses || []).slice(0,1).forEach(a => out.add(a));
      if (i.studio) out.add(i.studio);
    });
    return [...out].slice(0, 5);
  }, [items]);

  const hasFilter = statusFilter || studioFilter || ratingFilter;

  return (
    <div style={{ paddingBottom: 140 }}>
      <window.TopBar
        topPad={locked.topPad}
        title="Search"
        subtitle="codes · titles · actress · tags"
        locked={locked.value}
        onToggleLock={locked.toggle}
        accent={accent}
      />

      {/* search field */}
      <div style={{ padding: '0 16px 12px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: window.VH_SURFACE, borderRadius: 12,
          padding: '11px 14px',
          border: `0.5px solid ${window.VH_HAIRLINE}`,
        }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <circle cx="7" cy="7" r="5" stroke={window.VH_DIM} strokeWidth="1.6"/>
            <path d="M11 11l3 3" stroke={window.VH_DIM} strokeWidth="1.6" strokeLinecap="round"/>
          </svg>
          <input
            value={q} onChange={e => setQ(e.target.value)}
            placeholder="Search code, title, actress…"
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: window.VH_TEXT, fontSize: 14, fontFamily: 'inherit',
            }}
          />
          {q && (
            <button onClick={() => setQ('')} style={{
              border: 'none', background: 'rgba(255,255,255,0.08)',
              width: 18, height: 18, borderRadius: 99, color: window.VH_DIM,
              display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
            }}>
              <svg width="8" height="8" viewBox="0 0 8 8"><path d="M1 1l6 6M7 1L1 7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            </button>
          )}
        </div>
      </div>

      {/* filter rail */}
      <div style={{ display: 'flex', gap: 8, padding: '0 16px 10px', overflowX: 'auto', scrollbarWidth: 'none' }}>
        <FilterChip label={statusFilter ? window.STATUS_META[statusFilter].label : 'Status'}
          active={!!statusFilter} accent={accent}
          onClick={() => {
            const order = [null, 'want_to_watch', 'favorite', 'watched', 'rewatch'];
            setStatusFilter(order[(order.indexOf(statusFilter) + 1) % order.length]);
          }} />
        <FilterChip label={studioFilter || 'Studio'}
          active={!!studioFilter} accent={accent}
          onClick={() => {
            const order = [null, ...studios];
            setStudioFilter(order[(order.indexOf(studioFilter) + 1) % order.length]);
          }} />
        <FilterChip label={ratingFilter ? `${ratingFilter}+ ★` : 'Rating'}
          active={!!ratingFilter} accent={accent}
          onClick={() => setRatingFilter((ratingFilter + 1) % 6)} />
        <FilterChip
          label={`Sort: ${ {added:'Added', watched:'Watched', rating:'Rating', code:'Code'}[sort] }`}
          active accent={accent}
          onClick={() => {
            const order = ['added', 'watched', 'rating', 'code'];
            setSort(order[(order.indexOf(sort) + 1) % order.length]);
          }}
          icon={<svg width="10" height="10" viewBox="0 0 10 10"><path d="M2 4l3-3 3 3M2 6l3 3 3-3" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round"/></svg>}
        />
      </div>

      {/* recent / results */}
      {!q && !hasFilter ? (
        locked.value ? (
          <div style={{ padding: '12px 16px' }}>
            <div style={{
              padding: '18px 16px', borderRadius: 12,
              background: 'rgba(255,255,255,0.03)', border: `0.5px solid ${window.VH_HAIRLINE}`,
              color: window.VH_DIM, fontSize: 12.5, textAlign: 'center', lineHeight: 1.55,
            }}>
              Recent searches are hidden in locked mode.
              <div style={{ marginTop: 4, color: window.VH_DIM2 }}>
                Sign in to see suggestions from your library.
              </div>
            </div>
          </div>
        ) : (
        <div>
          <window.SectionHeader>Recent</window.SectionHeader>
          <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 0 }}>
            {recents.map((r, i) => (
              <button key={r} onClick={() => setQ(r)} className="vh-tap" style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '12px 4px',
                borderBottom: i === recents.length - 1 ? 'none' : `0.5px solid ${window.VH_HAIRLINE}`,
                background: 'transparent', border: 'none', cursor: 'pointer',
                color: window.VH_TEXT, fontSize: 14, textAlign: 'left',
                fontFamily: 'inherit',
              }}>
                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <circle cx="7" cy="7" r="5.5" stroke={window.VH_DIM} strokeWidth="1.3"/>
                  <path d="M7 4v3l2 1.5" stroke={window.VH_DIM} strokeWidth="1.3" strokeLinecap="round"/>
                </svg>
                <span style={{ flex: 1 }}>{r}</span>
                <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                  <path d="M8 3L3 8M3 3h5v5" stroke={window.VH_DIM2} strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
            ))}
          </div>
          {studios.length > 0 && (<>
            <window.SectionHeader>Browse by studio</window.SectionHeader>
            <div style={{ display: 'flex', gap: 8, padding: '0 16px', flexWrap: 'wrap' }}>
              {studios.map(s => (
                <window.Chip key={s} onClick={() => setStudioFilter(s)} accent={accent}>{s}</window.Chip>
              ))}
            </div>
          </>)}
        </div>
        )
      ) : (
        <div>
          <div style={{
            padding: '8px 16px 6px', display: 'flex', justifyContent: 'space-between',
            color: window.VH_DIM, fontSize: 11.5, letterSpacing: 0.4,
          }}>
            <span>{results.length} {results.length === 1 ? 'result' : 'results'}</span>
            {hasFilter && (
              <button onClick={() => { setStatusFilter(null); setStudioFilter(null); setRatingFilter(0); }}
                style={{ background:'transparent', border:'none', color: accent, fontSize: 11.5, fontWeight: 600, cursor:'pointer', fontFamily:'inherit' }}>
                Clear filters
              </button>
            )}
          </div>
          {results.length === 0 ? (
            <div style={{ padding: '50px 24px', textAlign: 'center', color: window.VH_DIM }}>
              <div style={{ fontSize: 14, color: window.VH_TEXT, fontWeight: 600, marginBottom: 4 }}>
                No matches
              </div>
              <div style={{ fontSize: 12.5 }}>Try a different code or clear filters.</div>
            </div>
          ) : (
            <RowList items={results} locked={locked.value} accent={accent} onClick={onOpenVideo}/>
          )}
        </div>
      )}
    </div>
  );
}

function FilterChip({ label, active, onClick, accent, icon }) {
  return (
    <button onClick={onClick} style={{
      display: 'inline-flex', alignItems: 'center', gap: 5,
      padding: '6px 12px', borderRadius: 99,
      background: active ? `${accent}22` : 'rgba(255,255,255,0.05)',
      color: active ? accent : window.VH_TEXT,
      border: active ? `0.5px solid ${accent}66` : `0.5px solid ${window.VH_HAIRLINE}`,
      fontSize: 12, fontWeight: 500, letterSpacing: 0.1,
      cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
      fontFamily: 'inherit',
    }}>
      {label}
      {icon || (
        <svg width="8" height="8" viewBox="0 0 8 8" style={{ marginLeft: 1 }}>
          <path d="M1 2l3 3 3-3" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round"/>
        </svg>
      )}
    </button>
  );
}


// ═══════════════════════════════════════════════════════════════
Object.assign(window, { LibraryScreen, SearchScreen, RowList });
