// Linke Sidebar: Stücke + Phase-Übersicht

function SidebarLeft({ state, dispatch, onUploadPdf }) {
  const fileRef = React.useRef(null);
  const piece = state.pieces.find(p => p.id === state.activePieceId);
  const ann = state.annotations[state.activePieceId] || { strokes: [], pins: [], checklist: {}, rehearsals: [] };

  const phaseStats = window.PHASE_ORDER.map(p => {
    const checks = window.CHECKLISTS[p];
    const naCount = checks.filter((_, i) => ann.checklist[`${p}-${i}-na`]).length;
    const total = checks.length - naCount;
    const done = checks.filter((_, i) => ann.checklist[`${p}-${i}`]).length;
    const pinCount = ann.pins.filter(pin => pin.phase === p).length;
    return { phase: p, total, done, pinCount };
  });

  const onFile = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    if (file.type !== 'application/pdf') {
      alert('Bitte eine PDF-Datei hochladen.');
      return;
    }
    onUploadPdf(file);
    e.target.value = '';
  };

  return (
    <aside className="sidebar-left">
      <div className="sidebar-section">
        <div className="sidebar-section-title">
          <span>Stücke</span>
          <button className="btn-add" onClick={() => fileRef.current.click()}>
            <Icon name="upload" size={12} stroke={2.5} /> PDF
          </button>
          <input ref={fileRef} type="file" accept="application/pdf" hidden onChange={onFile} />
        </div>
        {state.pieces.map(p => (
          <div
            key={p.id}
            className={`piece-card ${p.id === state.activePieceId ? 'active' : ''}`}
            onClick={() => dispatch({ type: 'select-piece', id: p.id })}
          >
            <div className="piece-thumb">
              <Icon name="music" size={16} />
            </div>
            <div className="piece-info">
              <div className="piece-title">{p.title}</div>
              <div className="piece-meta">
                {p.composer ? `${p.composer} · ` : ''}
                {(state.annotations[p.id]?.pins.length || 0)} Kommentar{(state.annotations[p.id]?.pins.length || 0) === 1 ? '' : 'e'}
              </div>
            </div>
            {state.pieces.length > 1 && (
              <button
                className="piece-delete"
                onClick={(e) => {
                  e.stopPropagation();
                  if (confirm(`"${p.title}" wirklich löschen?`)) {
                    dispatch({ type: 'delete-piece', id: p.id });
                  }
                }}
                title="Stück löschen"
              >
                <Icon name="trash" size={14} />
              </button>
            )}
          </div>
        ))}
      </div>

      <div className="sidebar-section" style={{ borderTop: '1px solid var(--border)' }}>
        <div className="sidebar-section-title">4-V Fortschritt</div>
        <div className="phase-progress">
          {phaseStats.map(({ phase, total, done, pinCount }) => {
            const meta = window.PHASES[phase];
            const pct = total ? (done / total) * 100 : 0;
            const isActive = state.activePhaseFilter === phase;
            return (
              <div
                key={phase}
                className={`phase-row ${isActive ? 'active' : ''}`}
                onClick={() => dispatch({
                  type: 'set-filter',
                  phase: isActive ? null : phase,
                })}
              >
                <div className="phase-badge" style={{ background: meta.color }}>
                  {phase}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="phase-name">{meta.name}</div>
                  <div className="phase-sub">
                    {done}/{total} Punkte · {pinCount} Pin{pinCount === 1 ? '' : 's'}
                  </div>
                  <div className="phase-progress-bar">
                    <div className="phase-progress-fill" style={{ width: `${pct}%`, background: meta.color }} />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        {state.activePhaseFilter && (
          <button
            className="btn-add"
            style={{ marginTop: 10, width: '100%', justifyContent: 'center' }}
            onClick={() => dispatch({ type: 'set-filter', phase: null })}
          >
            Filter zurücksetzen
          </button>
        )}
      </div>
    </aside>
  );
}

window.SidebarLeft = SidebarLeft;
