// Topbar — view switcher, sort, selection controls, capture indicator, analytics toggle

function Topbar({
  view, setView, sort, setSort, density, setDensity,
  selected, onSelectAll, onClearSelect, onBulkPick, onBulkReject, onBulkShare, onBulkDownload, onBulkDelete,
  onSearch, searchQuery,
  stats, capturing, lastCapture,
  analyticsOpen, setAnalyticsOpen,
  onToggleSidebar, onOpenCollections, onShare, onShareView,
  onOpenShortcuts, onSecondScreen,
}) {
  const bulkMode = selected.size > 0;

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 20,
      height: 44, flexShrink: 0,
      background: 'var(--topbar-bg)', backdropFilter: 'blur(16px)',
      borderBottom: '1px solid var(--line-1)',
      display: 'flex', alignItems: 'center', gap: 6, padding: '0 14px',
    }}>
      <button onClick={onToggleSidebar} style={iconBtnS} title="Toggle sidebar">
        <IconMenu size={14}/>
      </button>
      {onOpenCollections && (
        <button onClick={onOpenCollections} style={iconBtnS} title="Collections drawer">
          <IconStack size={14}/>
        </button>
      )}
      <Divider vertical/>

      {bulkMode ? (
        <>
          <span style={{ fontSize: 12, color: 'var(--ink-0)', fontWeight: 500 }}>
            <span className="mono" style={{ color: 'var(--accent)' }}>{selected.size}</span> selected
          </span>
          <Btn size="sm" onClick={onBulkPick}><IconCheck size={11}/> Pick</Btn>
          <Btn size="sm" onClick={onBulkReject}><IconX size={11}/> Reject</Btn>
          <Divider vertical/>
          <Btn size="sm" onClick={onBulkShare} icon={<IconLink size={12}/>}>Share</Btn>
          <Btn size="sm" onClick={onBulkDownload} icon={<IconDownload size={12}/>}>Download</Btn>
          <Btn size="sm" variant="danger" onClick={onBulkDelete} icon={<IconTrash size={12}/>}/>
          <div style={{ flex: 1 }}/>
          <Btn size="sm" variant="ghost" onClick={onClearSelect}>Clear</Btn>
        </>
      ) : (
        <>
          {/* View switcher */}
          <div style={{ display: 'flex', background: 'var(--bg-2)', borderRadius: 4, border: '1px solid var(--line-1)', padding: 1 }}>
            {[['grid', <IconGrid size={11}/>], ['list', <IconList size={11}/>]].map(([v, icon]) => (
              <button key={v} onClick={() => setView(v)} title={v} style={{
                height: 22, padding: '0 8px', fontSize: 10.5,
                background: view === v ? 'var(--bg-4)' : 'transparent',
                color: view === v ? 'var(--ink-0)' : 'var(--ink-3)',
                border: 'none', borderRadius: 3, cursor: 'pointer',
                display: 'flex', alignItems: 'center', gap: 5, textTransform: 'capitalize',
                fontFamily: 'var(--mono)', letterSpacing: 0.04,
              }}>{icon} {v}</button>
            ))}
          </div>

          {view === 'grid' && (
            <div style={{ display: 'flex', background: 'var(--bg-2)', borderRadius: 4, border: '1px solid var(--line-1)', padding: 1, marginLeft: 2 }}>
              {['tight','normal','loose'].map(d => (
                <button key={d} onClick={() => setDensity(d)} title={`Density: ${d}`} style={{
                  height: 22, width: 22, fontSize: 10,
                  background: density === d ? 'var(--bg-4)' : 'transparent',
                  color: density === d ? 'var(--ink-0)' : 'var(--ink-3)',
                  border: 'none', borderRadius: 3, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--mono)',
                }}>{d === 'tight' ? '▦' : d === 'normal' ? '▤' : '▢'}</button>
              ))}
            </div>
          )}

          {/* Sort */}
          <Divider vertical style={{ margin: '0 4px' }}/>
          <Btn size="sm" variant="ghost">
            <span className="mono" style={{ fontSize: 10, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.06 }}>Sort</span>
            <select value={sort} onChange={e => setSort(e.target.value)} style={{
              background: 'transparent', color: 'var(--ink-1)', border: 'none',
              fontSize: 11.5, cursor: 'pointer', outline: 'none',
            }}>
              <option value="capture_desc">Newest first</option>
              <option value="capture_asc">Oldest first</option>
              <option value="rating_desc">Highest rated</option>
              <option value="filename_asc">Filename A–Z</option>
              <option value="size_desc">Largest first</option>
            </select>
          </Btn>

          {/* Search */}
          <div style={{ flex: 1, maxWidth: 300, margin: '0 8px', position: 'relative' }}>
            <IconSearch size={11} style={{ position: 'absolute', left: 9, top: 7, color: 'var(--ink-3)' }}/>
            <input value={searchQuery} onChange={e => onSearch(e.target.value)}
              placeholder="Search filename, tag, EXIF…"
              style={{
                width: '100%', height: 26,
                background: 'var(--bg-2)', border: '1px solid var(--line-1)',
                borderRadius: 4, padding: '0 8px 0 26px',
                color: 'var(--ink-0)', fontSize: 11.5, outline: 'none',
              }}/>
            {searchQuery && (
              <button onClick={() => onSearch('')} style={{
                position: 'absolute', right: 6, top: 4, background: 'transparent', border: 'none',
                color: 'var(--ink-3)', cursor: 'pointer', padding: 4,
              }}><IconX size={10}/></button>
            )}
          </div>

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

          {/* Capture indicator */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6, padding: '3px 9px',
            background: capturing ? 'rgba(136,221,170,0.1)' : 'var(--bg-2)',
            border: `1px solid ${capturing ? 'rgba(136,221,170,0.3)' : 'var(--line-1)'}`,
            borderRadius: 99,
            fontFamily: 'var(--mono)', fontSize: 10, color: capturing ? '#88ddaa' : 'var(--ink-3)',
            letterSpacing: 0.06,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%',
              background: capturing ? '#88ddaa' : 'var(--ink-3)',
              animation: capturing ? 'pulse-dot 1.2s infinite' : 'none',
            }}/>
            {capturing ? 'CAPTURING' : 'TETHER IDLE'}
            {lastCapture && <span style={{ color: 'var(--ink-3)' }}>· {lastCapture}</span>}
          </div>

          <Btn size="sm" variant="ghost" onClick={() => setAnalyticsOpen(!analyticsOpen)}
            icon={<IconChart size={12}/>} active={analyticsOpen} title="Review stats"/>
          <Btn size="sm" variant="ghost" onClick={onOpenShortcuts} title="Shortcuts (?)"><span className="mono" style={{ fontSize: 11 }}>?</span></Btn>
          {onSecondScreen && (
            <Btn size="sm" variant="ghost" onClick={onSecondScreen} title="Open second screen monitor" icon={
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>
              </svg>
            }/>
          )}
          <Btn size="sm" variant="ghost" onClick={onShareView} icon={<IconEye size={12}/>} title="Preview as client"/>
          <Btn size="sm" variant="accent" onClick={onShare} icon={<IconLink size={12}/>}>Share</Btn>
        </>
      )}
    </header>
  );
}

const iconBtnS = {
  width: 28, height: 26, borderRadius: 4,
  background: 'transparent', border: '1px solid transparent',
  color: 'var(--ink-2)', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
};

function AnalyticsBar({ stats, open }) {
  if (!open) return null;
  const pickPct = stats.total ? Math.round((stats.picks / stats.total) * 100) : 0;
  const rejectPct = stats.total ? Math.round((stats.rejects / stats.total) * 100) : 0;
  const reviewPct = stats.total ? Math.round(((stats.picks + stats.rejects) / stats.total) * 100) : 0;
  return (
    <div style={{
      padding: '12px 20px', background: 'var(--bg-1)',
      borderBottom: '1px solid var(--line-1)',
      display: 'flex', alignItems: 'center', gap: 28, flexShrink: 0,
      animation: 'fade-up 160ms ease', flexWrap: 'wrap',
    }}>
      <Stat label="Total" value={stats.total} hint={stats.total > 0 ? `${stats.total} files` : ''}/>
      <Stat label="Picks" value={stats.picks} hint={`${pickPct}% of shoot`} color="var(--accent)"/>
      <Stat label="Rejected" value={stats.rejects} hint={`${rejectPct}% of shoot`} color="var(--reject)"/>
      <Stat label="Rated 3★+" value={stats.rated3 || 0} hint="retouch-worthy"/>
      <Stat label="Unreviewed" value={stats.unreviewed || 0} hint="needs eyes"/>
      {(stats.blurred || 0) > 0 && <Stat label="Soft focus" value={stats.blurred} hint="auto-flagged"/>}
      <div style={{ flex: 1, maxWidth: 260, display: 'flex', flexDirection: 'column', gap: 5 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: 0.1 }}>
          <span>Review progress</span>
          <span style={{ color: 'var(--ink-0)' }}>{reviewPct}%</span>
        </div>
        <div style={{ position: 'relative', height: 4, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
          <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${pickPct}%`, background: 'var(--accent)' }}/>
          <div style={{ position: 'absolute', left: `${pickPct}%`, top: 0, bottom: 0, width: `${rejectPct}%`, background: 'var(--reject)' }}/>
        </div>
      </div>
      <Stat label="Session size" value={stats.sessionSize}/>
    </div>
  );
}

function Stat({ label, value, hint, sub, color }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 52 }}>
      <span className="mono" style={{ fontSize: 8.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.14 }}>{label}</span>
      <span className="serif" style={{ fontSize: 28, lineHeight: 1, letterSpacing: -0.5, color: color || 'var(--ink-0)', fontWeight: 400 }}>{value}</span>
      {(hint || sub) && <span style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>{hint || sub}</span>}
    </div>
  );
}

function ShortcutsModal({ onClose }) {
  const groups = [
    { title: 'Navigation', items: [
      ['←/→', 'Previous / Next photo'],
      ['↑/↓', 'Row up / down (grid)'],
      ['⏎', 'Open lightbox'],
      ['Esc', 'Close lightbox / clear selection'],
    ]},
    { title: 'Culling', items: [
      ['P', 'Pick'], ['X', 'Reject'], ['U', 'Clear flag'],
      ['1–5', 'Rate stars'], ['0', 'Clear rating'],
      ['6/7/8/9', 'Color label red/yellow/green/blue'],
    ]},
    { title: 'View', items: [
      ['Z', 'Zoom 100% toggle'],
      ['I', 'Show EXIF'],
      ['E', 'Develop panel'],
      ['\\', 'Before/After compare'],
      ['G', 'Grid view'], ['L', 'List view'],
    ]},
    { title: 'Selection', items: [
      ['⌘/Ctrl + A', 'Select all'],
      ['⌘/Ctrl + D', 'Deselect'],
      ['Shift + click', 'Range select'],
      ['⌘/Ctrl + S', 'Create share link'],
      ['?', 'This help'],
    ]},
  ];
  return (
    <Modal onClose={onClose} width={600}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18 }}>
        <div>
          <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.14 }}>Studio</div>
          <div className="serif" style={{ fontSize: 28, letterSpacing: -0.5, color: 'var(--ink-0)', marginTop: 2 }}>Keyboard shortcuts</div>
        </div>
        <Btn size="sm" onClick={onClose} icon={<IconX size={13}/>}/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '18px 28px' }}>
        {groups.map(g => (
          <div key={g.title}>
            <div className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.14, marginBottom: 8 }}>{g.title}</div>
            {g.items.map(([k, desc]) => (
              <div key={k} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 0', fontSize: 12 }}>
                <span style={{ color: 'var(--ink-1)' }}>{desc}</span>
                <kbd style={{
                  fontFamily: 'var(--mono)', fontSize: 10.5,
                  background: 'var(--bg-3)', color: 'var(--ink-0)',
                  padding: '2px 7px', borderRadius: 3, border: '1px solid var(--line-2)',
                  boxShadow: '0 1px 0 var(--line-1)',
                }}>{k}</kbd>
              </div>
            ))}
          </div>
        ))}
      </div>
    </Modal>
  );
}

Object.assign(window, { Topbar, AnalyticsBar, ShortcutsModal });
