// Sidebar — sessions, collections, smart filters
// On mobile (< 768px): slide-over drawer with backdrop
// On desktop: inline sidebar

function Sidebar({ open, setOpen,
  events, activeEvent, setActiveEvent, activeShootId, onCreateEvent, onActivateEvent, onDeleteEvent,
  collections, activeCollection, setActiveCollection, onDeleteCollection,
  tagFilter, setTagFilter, ratingFilter, setRatingFilter,
  flagFilter, setFlagFilter, fileTypeFilter, setFileTypeFilter,
  tagCounts, stats, onNewCollection, shareCount,
  onOpenShares, onOpenWatermark, onOpenShortcuts, onOpenBranding,
  displayName, profilePhotoUrl, onOpenProfile, onLogout }) {

  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);
  }, []);

  // Auto-close on mobile when a filter row is clicked
  const mobileClose = () => { if (isMobile) setOpen(false); };

  const inner = (
    <div style={{ width: isMobile ? '100%' : 240, display: 'flex', flexDirection: 'column', height: '100%', flex: 1, minHeight: 0, overflowY: 'auto' }}>
      {/* Brand */}
      <div style={{ padding: '14px 16px 12px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid var(--line-1)', flexShrink: 0 }}>
        <div style={{ width: 26, height: 26, borderRadius: 5, background: 'var(--accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#1a1200' }}>
          <IconCamera size={14}/>
        </div>
        <div style={{ flex: 1 }}>
          <div className="mono" style={{ fontSize: 8.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.16 }}>Studio</div>
          <div style={{ fontSize: 12, color: 'var(--ink-0)', fontWeight: 600, letterSpacing: -0.1 }}>Dashboard</div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10, color: 'var(--ink-3)', fontFamily: 'var(--mono)' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#88ddaa', animation: 'pulse-dot 2s infinite' }}/>
          Live
        </div>
        {/* Close button — mobile only */}
        {isMobile && (
          <button onClick={() => setOpen(false)} style={{ background: 'none', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', display: 'flex', padding: 4, marginLeft: 4 }}>
            <IconX size={16}/>
          </button>
        )}
      </div>

      {/* Events */}
      <Section title="Events" action={
        <button onClick={onCreateEvent} style={{ background: 'transparent', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', display: 'flex', alignItems: 'center' }} title="New event">
          <IconPlus size={11}/>
        </button>
      }>
        <Row active={!activeEvent}
          onClick={() => { setActiveEvent(null); mobileClose(); }}
          icon={<IconGrid size={12}/>} label="All events"
          badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{stats.total}</span>}/>
        {stats.unassigned > 0 && (
          <Row active={activeEvent === '_unassigned'}
            onClick={() => { setActiveEvent('_unassigned'); mobileClose(); }}
            icon={<span style={{ width: 10, height: 10, borderRadius: 2, border: '1.5px dashed var(--ink-4)' }}/>}
            label="Unassigned"
            badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{stats.unassigned}</span>}/>
        )}
        {(events || []).map(e => (
          <EventRow key={e.id} event={e}
            active={activeEvent === e.id}
            isLive={e.id === activeShootId}
            onClick={() => { setActiveEvent(e.id); mobileClose(); }}
            onActivate={() => onActivateEvent(e.id)}
            onDeactivate={() => onActivateEvent(null)}
            onDelete={() => onDeleteEvent(e.id)}
          />
        ))}
        {(!events || events.length === 0) && (
          <div style={{ padding: '6px 14px 4px', fontSize: 11, color: 'var(--ink-4)', fontStyle: 'italic' }}>
            No events yet — click + to create one
          </div>
        )}
      </Section>

      {/* Flag filters */}
      <Section title="Filter">
        <Row active={flagFilter === 'all'} onClick={() => { setFlagFilter('all'); mobileClose(); }} icon={<IconGrid size={12}/>} label="All photos" badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{stats.total}</span>}/>
        <Row active={flagFilter === 'picks'} onClick={() => { setFlagFilter('picks'); mobileClose(); }}
          icon={<span style={{ width: 10, height: 10, borderRadius: 2, background: 'var(--accent)' }}/>} label="Picks"
          badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--accent)' }}>{stats.picks}</span>}/>
        <Row active={flagFilter === 'rejects'} onClick={() => { setFlagFilter('rejects'); mobileClose(); }}
          icon={<span style={{ width: 10, height: 10, borderRadius: 2, background: 'var(--reject)' }}/>} label="Rejects"
          badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--reject)' }}>{stats.rejects}</span>}/>
        <Row active={flagFilter === 'unflagged'} onClick={() => { setFlagFilter('unflagged'); mobileClose(); }}
          icon={<span style={{ width: 10, height: 10, borderRadius: 2, border: '1.5px solid var(--ink-3)' }}/>} label="Unflagged"
          badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{stats.unflagged}</span>}/>
      </Section>

      <Section title="Rating">
        <div style={{ padding: '2px 12px' }}>
          <div style={{ display: 'flex', gap: 3 }}>
            {[0,1,2,3,4,5].map(r => (
              <button key={r} onClick={() => { setRatingFilter(r); mobileClose(); }} style={{
                flex: 1, height: 28, fontSize: 10.5,
                background: ratingFilter === r ? 'var(--bg-3)' : 'transparent',
                color: ratingFilter === r ? 'var(--accent)' : 'var(--ink-2)',
                border: `1px solid ${ratingFilter === r ? 'var(--line-3)' : 'var(--line-1)'}`,
                borderRadius: 3, cursor: 'pointer', fontFamily: 'var(--mono)',
              }}>{r === 0 ? 'All' : `≥${r}★`}</button>
            ))}
          </div>
        </div>
      </Section>

      <Section title="File type">
        <div style={{ padding: '2px 12px', display: 'flex', gap: 4 }}>
          {['all','RAW','JPG'].map(t => (
            <button key={t} onClick={() => { setFileTypeFilter(t); mobileClose(); }} style={{
              flex: 1, height: 28, fontSize: 10,
              background: fileTypeFilter === t ? 'var(--bg-3)' : 'transparent',
              color: fileTypeFilter === t ? 'var(--ink-0)' : 'var(--ink-2)',
              border: `1px solid ${fileTypeFilter === t ? 'var(--line-3)' : 'var(--line-1)'}`,
              borderRadius: 3, cursor: 'pointer', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: 0.06,
            }}>{t}</button>
          ))}
        </div>
      </Section>

      {/* Collections */}
      <Section title="Collections" action={
        <button onClick={onNewCollection} style={{ background: 'transparent', border: 'none', color: 'var(--ink-3)', cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
          <IconPlus size={11}/>
        </button>
      }>
        <Row active={!activeCollection} onClick={() => { setActiveCollection(null); mobileClose(); }}
          icon={<IconStack size={12}/>} label="None"/>
        {collections.map(c => (
          <DeletableRow key={c.name} active={activeCollection === c.name}
            onClick={() => { setActiveCollection(c.name); mobileClose(); }}
            icon={<IconStack size={12}/>} label={c.name}
            badge={<span className="mono" style={{ fontSize: 9.5, color: 'var(--ink-3)' }}>{c.count || (c.files && c.files.length) || 0}</span>}
            onDelete={onDeleteCollection ? () => onDeleteCollection(c.name) : null}/>
        ))}
      </Section>

      {/* Tags */}
      {Object.keys(tagCounts).length > 0 && (
        <Section title="Tags">
          <div style={{ padding: '2px 12px', display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            {Object.entries(tagCounts).sort((a,b) => b[1] - a[1]).map(([tag, count]) => (
              <button key={tag} onClick={() => { setTagFilter(tagFilter === tag ? null : tag); mobileClose(); }}
                style={{
                  fontSize: 10.5, padding: '2px 8px', borderRadius: 99,
                  background: tagFilter === tag ? 'var(--accent-soft)' : 'var(--bg-2)',
                  color: tagFilter === tag ? 'var(--accent)' : 'var(--ink-2)',
                  border: `1px solid ${tagFilter === tag ? 'var(--accent-dim)' : 'var(--line-1)'}`,
                  cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5,
                }}>
                {tag} <span className="mono" style={{ fontSize: 9, opacity: 0.7 }}>{count}</span>
              </button>
            ))}
          </div>
        </Section>
      )}

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

      {/* Footer actions */}
      <div style={{ padding: '10px 12px', borderTop: '1px solid var(--line-1)', display: 'flex', flexDirection: 'column', gap: 3, flexShrink: 0 }}>
        <Row icon={<IconLink size={12}/>} label={`Share links · ${shareCount}`} onClick={() => { onOpenShares(); mobileClose(); }}/>
        <Row icon={<IconWatermark size={12}/>} label="Watermark" onClick={() => { onOpenWatermark(); mobileClose(); }}/>
        <Row icon={<IconCamera size={12}/>} label="Branding" onClick={() => { onOpenBranding(); mobileClose(); }}/>
        <Row icon={<IconBolt size={12}/>} label="Shortcuts" onClick={() => { onOpenShortcuts(); mobileClose(); }}/>
      </div>

      {/* Profile footer */}
      <div style={{ padding: '10px 14px', borderTop: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
        <button onClick={() => { onOpenProfile(); mobileClose(); }} title="Change profile photo" style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', flexShrink: 0 }}>
          <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--accent)', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, color: '#1a1200' }}>
            {profilePhotoUrl
              ? <img src={profilePhotoUrl} style={{ width: '100%', height: '100%', objectFit: 'cover' }} onError={e => { e.target.style.display='none'; }}/>
              : (displayName || '?')[0].toUpperCase()}
          </div>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--ink-0)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{displayName}</div>
          <button onClick={onLogout} style={{ background: 'none', border: 'none', padding: 0, fontSize: 10, color: 'var(--ink-3)', cursor: 'pointer', fontFamily: 'inherit' }}>Sign out</button>
        </div>
      </div>
    </div>
  );

  // ── Mobile: slide-over drawer ──────────────────────────────────────────────
  if (isMobile) {
    return (
      <>
        {/* Backdrop */}
        {open && (
          <div onClick={() => setOpen(false)} style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.55)',
            zIndex: 290, backdropFilter: 'blur(2px)',
            animation: 'fade-in 160ms',
          }}/>
        )}
        {/* Drawer */}
        <aside style={{
          position: 'fixed', top: 0, left: 0, bottom: 0,
          width: Math.min(window.innerWidth * 0.82, 300),
          zIndex: 300,
          background: 'var(--bg-0)', borderRight: '1px solid var(--line-1)',
          display: 'flex', flexDirection: 'column',
          transform: open ? 'translateX(0)' : 'translateX(-110%)',
          transition: 'transform 240ms cubic-bezier(0.3,0.9,0.3,1)',
          overflowY: 'auto',
          boxShadow: open ? '4px 0 32px rgba(0,0,0,0.5)' : 'none',
        }}>
          {inner}
        </aside>
      </>
    );
  }

  // ── Desktop: inline sidebar ────────────────────────────────────────────────
  return (
    <aside style={{
      width: open ? 240 : 0, flexShrink: 0,
      background: 'var(--bg-0)', borderRight: '1px solid var(--line-1)',
      transition: 'width 220ms cubic-bezier(0.3,0.9,0.3,1)',
      overflow: 'hidden', display: 'flex', flexDirection: 'column',
    }}>
      {inner}
    </aside>
  );
}

function Section({ title, action, children }) {
  return (
    <div style={{ padding: '14px 0 6px', flexShrink: 0 }}>
      <div style={{ padding: '0 16px 6px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span className="mono" style={{ fontSize: 8.5, color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: 0.18, fontWeight: 600 }}>{title}</span>
        {action}
      </div>
      {children}
    </div>
  );
}

function Row({ icon, label, badge, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: 'calc(100% - 16px)', margin: '1px 8px',
      padding: '7px 10px', display: 'flex', alignItems: 'center', gap: 9,
      background: active ? 'var(--bg-3)' : 'transparent',
      color: active ? 'var(--ink-0)' : 'var(--ink-1)',
      border: 'none', borderRadius: 4,
      cursor: 'pointer', fontSize: 13, textAlign: 'left',
      transition: 'background 100ms',
    }}
      onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-2)'; }}
      onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}
    >
      <span style={{ color: active ? 'var(--accent)' : 'var(--ink-3)', display: 'flex', width: 14 }}>{icon}</span>
      <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
      {badge}
    </button>
  );
}

function DeletableRow({ icon, label, badge, active, onClick, onDelete }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ display: 'flex', alignItems: 'center', margin: '1px 8px', borderRadius: 4,
        background: active ? 'var(--bg-3)' : hover ? 'var(--bg-2)' : 'transparent',
        transition: 'background 100ms', cursor: 'pointer' }}
      onClick={onClick}>
      <span style={{ color: active ? 'var(--accent)' : 'var(--ink-3)', display: 'flex', width: 14, marginLeft: 10 }}>{icon}</span>
      <span style={{ flex: 1, padding: '7px 8px', fontSize: 13, color: active ? 'var(--ink-0)' : 'var(--ink-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
      {badge && !hover && badge}
      {hover && onDelete && (
        <button onClick={e => { e.stopPropagation(); onDelete(); }}
          style={{ width: 22, height: 22, borderRadius: 3, background: 'transparent', border: 'none',
            color: 'var(--reject)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', marginRight: 4 }}>
          <IconTrash size={10}/>
        </button>
      )}
    </div>
  );
}

function EventRow({ event, active, isLive, onClick, onActivate, onDeactivate, onDelete }) {
  const [hover, setHover] = React.useState(false);
  return (
    <div
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={onClick}
      style={{
        position: 'relative', display: 'flex', alignItems: 'center',
        margin: '1px 8px', borderRadius: 4,
        background: active ? 'var(--bg-3)' : hover ? 'var(--bg-2)' : 'transparent',
        transition: 'background 100ms', cursor: 'pointer',
      }}>
      <div style={{ flex: 1, padding: '6px 10px', display: 'flex', alignItems: 'center', gap: 9, minWidth: 0 }}>
        {isLive
          ? <span style={{ width: 8, height: 8, borderRadius: '50%', background: '#88ddaa', animation: 'pulse-dot 1.4s infinite', flexShrink: 0 }}/>
          : <IconFolder size={12} style={{ color: active ? 'var(--accent)' : 'var(--ink-3)', flexShrink: 0 }}/>
        }
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, color: active ? 'var(--ink-0)' : 'var(--ink-1)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {isLive && <span style={{ color: '#88ddaa', fontFamily: 'var(--mono)', fontSize: 9, textTransform: 'uppercase', letterSpacing: 0.1, marginRight: 5 }}>Live</span>}
            {event.name}
          </div>
          <div className="mono" style={{ fontSize: 9, color: 'var(--ink-4)', marginTop: 1 }}>
            {event.date} · {event.count || 0}
          </div>
        </div>
      </div>
      {hover && (
        <div style={{ display: 'flex', gap: 2, paddingRight: 6, flexShrink: 0 }} onClick={e => e.stopPropagation()}>
          {isLive ? (
            <button title="Stop receiving photos" onClick={onDeactivate}
              style={{ height: 22, padding: '0 6px', borderRadius: 3, background: 'rgba(136,221,170,0.12)', border: '1px solid rgba(136,221,170,0.25)', color: '#88ddaa', cursor: 'pointer', fontSize: 9, fontFamily: 'var(--mono)', letterSpacing: 0.06 }}>
              LIVE
            </button>
          ) : (
            <button title="Activate — new photos go here" onClick={onActivate}
              style={{ height: 22, padding: '0 6px', borderRadius: 3, background: 'transparent', border: '1px solid var(--line-2)', color: 'var(--ink-3)', cursor: 'pointer', fontSize: 9, fontFamily: 'var(--mono)', letterSpacing: 0.06 }}>
              ⚡ SET LIVE
            </button>
          )}
          <button title="Delete event" onClick={onDelete}
            style={{ width: 22, height: 22, borderRadius: 3, background: 'transparent', border: 'none', color: 'var(--reject)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <IconTrash size={10}/>
          </button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { Sidebar });
