// Chrome UI: CollectionsDrawer, Toolbar, ShortcutBar

// Pin icon for drawer
function IconPin({ size = 13 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none">
      <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
    </svg>
  );
}

function CollectionsDrawer({ open, collections, activeCollection, setActiveCollection, files, onClose, onNew, moodboards }) {
  const activeMoodboards = (moodboards || []).filter(m => m.pins && m.pins.length > 0);
  return (
    <>
      {open && <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 40, animation: 'fade-in 200ms',
      }}/>}
      <aside style={{
        position: 'fixed', top: 0, bottom: 0, left: 0, width: 260, zIndex: 41,
        background: 'var(--bg-1)', borderRight: '1px solid var(--line-1)',
        transform: open ? 'translateX(0)' : 'translateX(-100%)',
        transition: 'transform 220ms cubic-bezier(0.3,0.9,0.3,1)',
        display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.12 }}>Library</div>
            <div className="serif" style={{ fontSize: 20, color: 'var(--ink-0)', letterSpacing: -0.3, marginTop: 2 }}>Collections</div>
          </div>
          <Btn size="sm" onClick={onClose} icon={<IconX size={13}/>}/>
        </div>
        <div style={{ padding: 10, flex: 1, overflowY: 'auto' }}>
          <CollectionItem active={activeCollection === null} label="All photos" count={files.length}
            onClick={() => { setActiveCollection(null); onClose(); }} icon={<IconCamera size={13}/>}/>
          <CollectionItem active={activeCollection === '_picks'} label="Picks"
            count={files.filter(f => f.pick).length}
            onClick={() => { setActiveCollection('_picks'); onClose(); }} dot="var(--accent)"/>
          <CollectionItem active={activeCollection === '_rejected'} label="Rejected"
            count={files.filter(f => f.reject).length}
            onClick={() => { setActiveCollection('_rejected'); onClose(); }} dot="var(--reject)"/>
          <CollectionItem active={activeCollection === '_rated'} label="Rated 3★+"
            count={files.filter(f => (f.rating||0) >= 3).length}
            onClick={() => { setActiveCollection('_rated'); onClose(); }} icon={<IconStar size={13}/>}/>
          <CollectionItem active={activeCollection === '_blur'} label="Soft focus"
            count={files.filter(f => f.blur).length}
            onClick={() => { setActiveCollection('_blur'); onClose(); }} icon={<IconZoom size={13}/>}/>

          {/* Client Picks / Mood Boards */}
          {activeMoodboards.length > 0 && (
            <>
              <div style={{ height: 1, background: 'var(--line-1)', margin: '10px 4px' }}/>
              <div style={{ padding: '4px 8px', marginBottom: 2, display: 'flex', alignItems: 'center', gap: 6 }}>
                <span className="mono" style={{ fontSize: 9.5, color: 'var(--accent)', letterSpacing: 0.1, textTransform: 'uppercase' }}>Client Picks</span>
                <span style={{
                  background: 'var(--accent)', color: '#1a1200', fontSize: 9, fontWeight: 700,
                  borderRadius: 99, padding: '1px 5px', fontFamily: 'var(--mono)',
                }}>{activeMoodboards.length}</span>
              </div>
              {activeMoodboards.map(m => (
                <CollectionItem
                  key={m.token}
                  active={activeCollection === `_mb_${m.token}`}
                  label={m.label}
                  count={m.pins.length}
                  onClick={() => { setActiveCollection(`_mb_${m.token}`); onClose(); }}
                  icon={<IconPin size={13}/>}
                  accent
                />
              ))}
            </>
          )}

          <div style={{ height: 1, background: 'var(--line-1)', margin: '10px 4px' }}/>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 8px', marginBottom: 2 }}>
            <span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)', letterSpacing: 0.1, textTransform: 'uppercase' }}>Collections</span>
            <button onClick={onNew} style={{ background: 'none', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', fontSize: 11, display: 'flex', alignItems: 'center', gap: 2 }}>
              <IconPlus size={11}/> New
            </button>
          </div>
          {collections.map(c => (
            <CollectionItem key={c.name} active={activeCollection === c.name} label={c.name}
              count={c.count || (c.files && c.files.length) || 0}
              onClick={() => { setActiveCollection(c.name); onClose(); }} icon={<IconFolder size={13}/>}/>
          ))}
        </div>
      </aside>
    </>
  );
}

function CollectionItem({ active, label, count, onClick, icon, dot, accent }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 9,
      padding: '7px 10px', borderRadius: 6, cursor: 'pointer',
      background: active ? (accent ? 'var(--accent-soft)' : 'var(--bg-3)') : 'transparent',
      color: active ? (accent ? 'var(--accent)' : 'var(--ink-0)') : 'var(--ink-1)',
      fontSize: 12, transition: 'background 120ms',
      borderLeft: accent && active ? '2px solid var(--accent)' : '2px solid transparent',
    }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      <span style={{ color: active ? (accent ? 'var(--accent)' : 'var(--ink-0)') : 'var(--ink-3)', display: 'flex' }}>
        {dot ? <span style={{ width: 8, height: 8, borderRadius: '50%', background: dot, margin: '0 2px' }}/> : icon}
      </span>
      <span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
      <span className="mono" style={{ fontSize: 10.5, color: accent ? 'var(--accent)' : 'var(--ink-3)' }}>{count}</span>
    </div>
  );
}

function Toolbar({ filter, setFilter, sort, setSort, search, setSearch, selCount, onDlSel, onDelSel, totalShown, activeTag, setActiveTag, colorFilter, setColorFilter }) {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const fn = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', fn);
    return () => window.removeEventListener('resize', fn);
  }, []);
  const filters = [
    { id: 'all',        label: 'All' },
    { id: 'RAW',        label: 'RAW' },
    { id: 'JPG',        label: 'JPEG' },
    { id: 'picks',      label: '✓ Picks' },
    { id: 'rejected',   label: '✕ Rejected' },
    { id: 'rated3',     label: '3★+' },
    { id: 'unreviewed', label: 'New' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: isMobile ? '6px 10px' : '8px 16px', minHeight: isMobile ? 38 : 44, flexShrink: 0,
      background: 'var(--bg-0)', borderBottom: '1px solid var(--line-1)',
      overflowX: isMobile ? 'auto' : 'visible',
      WebkitOverflowScrolling: 'touch',
    }}>
      {/* Filter tabs */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 2, background: 'var(--bg-2)', padding: 2, borderRadius: 7, border: '1px solid var(--line-1)' }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: '4px 9px', fontSize: 11.5, fontWeight: 500,
            background: filter === f.id ? 'var(--bg-4)' : 'transparent',
            color: filter === f.id ? 'var(--ink-0)' : 'var(--ink-2)',
            border: 'none', borderRadius: 5, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 4, transition: 'all 120ms',
          }}>
            {f.icon && <span style={{ opacity: 0.8 }}>{f.icon}</span>}
            {f.label}
          </button>
        ))}
      </div>

      {/* Color label filter — hidden on mobile */}
      {!isMobile && <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '3px 8px', background: 'var(--bg-2)', borderRadius: 7, border: '1px solid var(--line-1)', height: 28, flexShrink: 0 }}>
        <span className="mono" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: 0.1, textTransform: 'uppercase', marginRight: 2 }}>Label</span>
        {[null, 'red', 'yellow', 'green', 'blue', 'purple'].map(c => (
          <ColorDot key={c||'none'} color={c} size={10} active={colorFilter === c && c !== null}
            onClick={() => setColorFilter(colorFilter === c ? null : c)}/>
        ))}
      </div>}

      {/* Sort */}
      <select value={sort} onChange={e => setSort(e.target.value)} style={{
        background: 'var(--bg-2)', border: '1px solid var(--line-1)',
        color: 'var(--ink-1)', fontSize: 11.5, padding: '5px 7px',
        borderRadius: 6, height: 28, outline: 'none', cursor: 'pointer', flexShrink: 0,
      }}>
        <option value="capture_desc">Newest first</option>
        <option value="capture_asc">Oldest first</option>
        <option value="rating_desc">Rating</option>
        <option value="filename_asc">Name A–Z</option>
        <option value="size_desc">Largest first</option>
      </select>

      {/* Search — hidden on mobile */}
      {!isMobile && <div style={{ position: 'relative', flex: 1, maxWidth: 280 }}>
        <IconSearch size={12} style={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', color: 'var(--ink-3)' }}/>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search filename, tag…" style={{
          width: '100%', height: 28, padding: '0 10px 0 26px',
          background: 'var(--bg-2)', border: '1px solid var(--line-1)', borderRadius: 6,
          color: 'var(--ink-1)', fontSize: 11.5, outline: 'none',
        }}/>
        {search && (
          <button onClick={() => setSearch('')} style={{ position: 'absolute', right: 6, top: 4, background: 'none', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', padding: 4 }}>
            <IconX size={10}/>
          </button>
        )}
      </div>}

      {/* Active tag pill */}
      {activeTag && <Chip onRemove={() => setActiveTag(null)}>#{activeTag}</Chip>}

      <div style={{ flex: 1 }}/>

      {/* Selection actions */}
      {selCount > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '2px 8px', background: 'var(--accent-soft)', borderRadius: 6, border: '1px solid var(--accent-dim)' }}>
          <span className="mono" style={{ fontSize: 11, color: 'var(--accent)', fontWeight: 500 }}>{selCount} selected</span>
          <Divider vertical style={{ background: 'var(--accent-dim)', opacity: 0.4 }}/>
          <Btn size="sm" onClick={onDlSel} icon={<IconDownload size={12}/>} title="Download ZIP">ZIP</Btn>
          <Btn size="sm" variant="danger" onClick={onDelSel} icon={<IconTrash size={12}/>} title="Delete selected"/>
        </div>
      )}

      <span className="mono" style={{ fontSize: 10.5, color: 'var(--ink-3)' }}>{totalShown} shown</span>
    </div>
  );
}

function ShortcutBar() {
  const [isMobile, setIsMobile] = React.useState(window.innerWidth < 768);
  React.useEffect(() => {
    const fn = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', fn);
    return () => window.removeEventListener('resize', fn);
  }, []);
  if (isMobile) return null;
  const shortcuts = [
    { k: 'P', l: 'Pick' }, { k: 'X', l: 'Reject' },
    { k: '1–5', l: 'Rate' }, { k: '6–9', l: 'Label' },
    { k: '←→', l: 'Navigate' }, { k: 'Z', l: 'Zoom' }, { k: 'E', l: 'Edit' },
    { k: '\\', l: 'Before/After' }, { k: 'G/L', l: 'View' },
  ];
  return (
    <div style={{
      height: 28, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 20, background: 'var(--bg-1)', borderTop: '1px solid var(--line-1)',
      fontSize: 10.5, color: 'var(--ink-3)',
    }}>
      {shortcuts.map((s, i) => (
        <span key={i} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <Kbd>{s.k}</Kbd>
          <span>{s.l}</span>
        </span>
      ))}
    </div>
  );
}

Object.assign(window, { CollectionsDrawer, Toolbar, ShortcutBar });
