// Sprint view: Backlog + Sprint board + Burndown + Story points + Review modal + Velocity
const SPIcons = window.Icons;
const { COLUMNS: SP_COLS, parseDateKey: spDate, relativeDate: spRel, isOverdue: spOver } = window.PMStore;
const { Tag: SPTag, Priority: SPPriority } = window.UI;

const SP_POINTS = [1, 2, 3, 5, 8, 13];
const PRIORITY_ORDER = { high: 0, medium: 1, low: 2 };

function SprintView({ state, onSelectTask, onUpdateTask, onAddTask,
                      onAddSprint, onUpdateSprint, onDeleteSprint, onCloseSprint, onMoveToSprint }) {
  const sprints      = (state.sprints || []).filter(s => s.projectId === state.activeProjectId);
  const activeSprint = sprints.find(s => s.status === 'active') || sprints.find(s => s.status === 'planning') || null;

  const [selectedSprintId, setSelectedSprintId] = React.useState(() => activeSprint?.id || null);
  const [showCreate, setShowCreate] = React.useState(false);
  const [showEdit,   setShowEdit]   = React.useState(false);
  const [showReview, setShowReview] = React.useState(false);
  const [dragTaskId, setDragTaskId] = React.useState(null);
  const [dragTarget, setDragTarget] = React.useState(null);
  const [backlogSort, setBacklogSort] = React.useState('order');

  React.useEffect(() => {
    const active = sprints.find(s => s.status === 'active') || sprints.find(s => s.status === 'planning');
    if (active && !selectedSprintId) setSelectedSprintId(active.id);
  }, [state.activeProjectId]);

  const sprint = sprints.find(s => s.id === selectedSprintId) || null;

  const projectTasks = state.tasks.filter(t => t.projectId === state.activeProjectId && !t.archived);
  const backlogTasksRaw = projectTasks.filter(t => !t.sprintId);
  const backlogTasks = [...backlogTasksRaw].sort((a, b) => {
    if (backlogSort === 'priority') return (PRIORITY_ORDER[a.priority] ?? 1) - (PRIORITY_ORDER[b.priority] ?? 1);
    if (backlogSort === 'due') {
      if (!a.due && !b.due) return 0;
      if (!a.due) return 1;
      if (!b.due) return -1;
      return spDate(a.due) - spDate(b.due);
    }
    return (a.order ?? 0) - (b.order ?? 0);
  });
  const sprintTasks  = sprint ? projectTasks.filter(t => t.sprintId === sprint.id) : [];
  const usePoints    = sprintTasks.some(t => t.storyPoints);
  const plannedPts   = sprintTasks.reduce((s, t) => s + (t.storyPoints || 0), 0);
  const donePts      = sprintTasks.filter(t => t.status === 'done').reduce((s, t) => s + (t.storyPoints || 0), 0);
  const capacity     = sprint?.capacity || 0;
  const completedSprints = sprints.filter(s => s.status === 'completed' && s.velocityPoints != null).slice(-6);

  const handleDrop = (target) => {
    if (!dragTaskId) return;
    const spId = target === 'backlog' ? null : target;
    onMoveToSprint ? onMoveToSprint(dragTaskId, spId) : onUpdateTask(dragTaskId, { sprintId: spId });
    setDragTaskId(null);
    setDragTarget(null);
  };

  const handleMoveTask = (taskId, spId) => {
    onMoveToSprint ? onMoveToSprint(taskId, spId) : onUpdateTask(taskId, { sprintId: spId });
  };

  const handleStartSprint = () => onUpdateSprint(sprint.id, { status: 'active' });

  const handleReviewConfirm = ({ taskDisposition, velocityPoints }) => {
    onCloseSprint(sprint.id, { velocityPoints, taskDisposition });
    setShowReview(false);
    setSelectedSprintId(null);
  };

  return (
    <div className="content sprint-content">

      {/* ── Sprint seçici + meta ─────────────────────────────── */}
      <div className="sprint-header">
        <div className="sprint-selector">
          <select className="select-control" value={selectedSprintId || ''} onChange={e => setSelectedSprintId(e.target.value || null)}>
            <option value="">— Sprint seçin —</option>
            {sprints.map(s => (
              <option key={s.id} value={s.id}>
                {s.name} {s.status === 'active' ? '🟢' : s.status === 'completed' ? '✓' : '○'}
              </option>
            ))}
          </select>
          <button className="btn btn-ghost btn-sm" onClick={() => setShowCreate(true)}>
            <SPIcons.Plus size={14} /> Yeni Sprint
          </button>
          {sprint && sprint.status !== 'completed' && (
            <button className="btn btn-ghost btn-sm" onClick={() => setShowEdit(true)}>
              <SPIcons.Edit size={13} /> Düzenle
            </button>
          )}
        </div>

        {sprint && (
          <div className="sprint-meta">
            <span className={`sprint-status-badge sprint-status-${sprint.status}`}>
              {sprint.status === 'planning' ? 'Planlama' : sprint.status === 'active' ? 'Aktif' : 'Tamamlandı'}
            </span>
            {sprint.startDate && sprint.endDate && (
              <span className="sprint-dates">{sprint.startDate} → {sprint.endDate}</span>
            )}
            {sprint.goal && <span className="sprint-goal">"{sprint.goal}"</span>}
            {capacity > 0 && (
              <span className="sprint-capacity">
                <SPIcons.Zap size={12} />
                <span style={{ color: plannedPts > capacity ? 'var(--p-high)' : undefined }}>
                  {plannedPts}/{capacity} SP
                </span>
              </span>
            )}
            {!capacity && usePoints && (
              <span className="sprint-capacity">
                <SPIcons.Zap size={12} /> {plannedPts} SP · {donePts} tamamlandı
              </span>
            )}
            <div style={{ flex: 1 }} />
            {sprint.status === 'planning' && (
              <button className="btn btn-primary btn-sm" onClick={handleStartSprint}>
                <SPIcons.Play size={13} /> Başlat
              </button>
            )}
            {sprint.status === 'active' && (
              <button className="btn btn-ghost btn-sm" onClick={() => setShowReview(true)}>
                <SPIcons.Check size={13} /> Sprinti Kapat
              </button>
            )}
          </div>
        )}
      </div>

      {/* ── Burndown + velocity ──────────────────────────────── */}
      {sprint && sprint.startDate && sprint.endDate && (
        <div className="card sprint-burndown-card">
          <div className="sprint-burndown-header">
            <span className="dash-section-title" style={{ margin: 0 }}>Burndown</span>
            <SprintStats tasks={sprintTasks} usePoints={usePoints} />
          </div>
          <BurndownChart sprint={sprint} tasks={sprintTasks} usePoints={usePoints} />
          {completedSprints.length > 0 && <VelocityBar sprints={completedSprints} />}
        </div>
      )}

      {/* ── Backlog | Sprint board ───────────────────────────── */}
      <div className="sprint-board">

        {/* Backlog */}
        <div
          className={`sprint-col ${dragTarget === 'backlog' ? 'drag-over' : ''}`}
          onDragOver={e => { e.preventDefault(); setDragTarget('backlog'); }}
          onDragLeave={() => setDragTarget(null)}
          onDrop={() => handleDrop('backlog')}
        >
          <div className="sprint-col-header">
            <span className="sprint-col-title">Backlog</span>
            <span className="sprint-col-count">{backlogTasks.length}</span>
            <select
              className="sprint-sort-select"
              value={backlogSort}
              onChange={e => setBacklogSort(e.target.value)}
              onClick={e => e.stopPropagation()}
              title="Sıralama"
            >
              <option value="order">Varsayılan</option>
              <option value="priority">Öncelik</option>
              <option value="due">Son tarih</option>
            </select>
            <button className="icon-btn icon-btn-sm"
              onClick={() => onAddTask({ projectId: state.activeProjectId, sprintId: null })}
              title="Backlog'a görev ekle">
              <SPIcons.Plus size={14} />
            </button>
          </div>
          <div className="sprint-col-body">
            {backlogTasks.length === 0 && <div className="sprint-empty">Backlog boş</div>}
            {backlogTasks.map(t => (
              <SprintTaskCard
                key={t.id}
                task={t}
                state={state}
                onSelect={() => onSelectTask(t.id)}
                onDragStart={() => setDragTaskId(t.id)}
                onDragEnd={() => { setDragTaskId(null); setDragTarget(null); }}
                onMoveToSprint={sprint ? () => handleMoveTask(t.id, sprint.id) : null}
                onUpdatePoints={(pts) => onUpdateTask(t.id, { storyPoints: pts })}
              />
            ))}
          </div>
        </div>

        {/* Sprint */}
        <div
          className={`sprint-col sprint-col-active ${dragTarget === (sprint?.id || 'sprint') ? 'drag-over' : ''}`}
          onDragOver={e => { e.preventDefault(); setDragTarget(sprint?.id || 'sprint'); }}
          onDragLeave={() => setDragTarget(null)}
          onDrop={() => sprint && handleDrop(sprint.id)}
        >
          <div className="sprint-col-header">
            <span className="sprint-col-title">{sprint?.name || 'Sprint'}</span>
            <span className="sprint-col-count">{sprintTasks.length}</span>
            {sprint && (
              <button className="icon-btn icon-btn-sm"
                onClick={() => onAddTask({ projectId: state.activeProjectId, sprintId: sprint.id })}
                title="Sprint'e görev ekle">
                <SPIcons.Plus size={14} />
              </button>
            )}
          </div>
          {!sprint ? (
            <div className="sprint-empty">Sprint seçin veya oluşturun</div>
          ) : (
            <div className="sprint-col-body">
              {sprintTasks.length === 0 && (
                <div className="sprint-empty">Sprint boş — backlog'dan görev sürükleyin</div>
              )}
              {SP_COLS.map(col => {
                const colTasks = sprintTasks.filter(t => t.status === col.id);
                if (!colTasks.length) return null;
                return (
                  <div key={col.id} className="sprint-status-group">
                    <div className="sprint-status-label">
                      <span className="project-dot" style={{ background: col.color }} />
                      {col.label} <span className="sprint-col-count">{colTasks.length}</span>
                    </div>
                    {colTasks.map(t => (
                      <SprintTaskCard
                        key={t.id}
                        task={t}
                        state={state}
                        onSelect={() => onSelectTask(t.id)}
                        onDragStart={() => setDragTaskId(t.id)}
                        onDragEnd={() => { setDragTaskId(null); setDragTarget(null); }}
                        onMoveToSprint={() => handleMoveTask(t.id, null)}
                        moveLabel="Backlog'a taşı"
                        onUpdatePoints={(pts) => onUpdateTask(t.id, { storyPoints: pts })}
                      />
                    ))}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* ── Modals ──────────────────────────────────────────── */}
      {showCreate && (
        <SprintModal
          title="Yeni Sprint"
          projectId={state.activeProjectId}
          onSave={(data) => { onAddSprint(data); setShowCreate(false); }}
          onClose={() => setShowCreate(false)}
        />
      )}

      {showEdit && sprint && (
        <SprintModal
          title="Sprint Düzenle"
          initial={sprint}
          projectId={state.activeProjectId}
          onSave={(data) => { onUpdateSprint(sprint.id, data); setShowEdit(false); }}
          onClose={() => setShowEdit(false)}
          onDelete={() => { onDeleteSprint(sprint.id); setSelectedSprintId(null); setShowEdit(false); }}
          onCloseSprint={sprint.status === 'active' ? () => { setShowEdit(false); setShowReview(true); } : null}
        />
      )}

      {showReview && sprint && (
        <SprintReviewModal
          sprint={sprint}
          tasks={sprintTasks}
          nextSprints={sprints.filter(s => s.id !== sprint.id && s.status !== 'completed')}
          onConfirm={handleReviewConfirm}
          onClose={() => setShowReview(false)}
        />
      )}
    </div>
  );
}

/* ── Sprint istatistik satırı ──────────────────────────────── */
function SprintStats({ tasks, usePoints }) {
  const done  = tasks.filter(t => t.status === 'done').length;
  const total = tasks.length;
  const pct   = total ? Math.round(done / total * 100) : 0;
  const donePts  = tasks.filter(t => t.status === 'done').reduce((s, t) => s + (t.storyPoints || 0), 0);
  const totalPts = tasks.reduce((s, t) => s + (t.storyPoints || 0), 0);
  return (
    <div className="sprint-stats">
      <span><strong>{done}</strong>/{total} görev</span>
      {usePoints && <span><strong>{donePts}</strong>/{totalPts} SP</span>}
      <span className="sprint-stats-pct">{pct}%</span>
    </div>
  );
}

/* ── Burndown grafiği ──────────────────────────────────────── */
function BurndownChart({ sprint, tasks, usePoints }) {
  const start = new Date(sprint.startDate + 'T00:00:00');
  const end   = new Date(sprint.endDate   + 'T23:59:59');
  const totalDays = Math.max(1, Math.round((end - start) / 86400000));

  const val = (t) => usePoints ? (t.storyPoints || 1) : 1;
  const totalValue = tasks.reduce((s, t) => s + val(t), 0);
  if (!totalValue) return (
    <div className="sprint-empty" style={{ padding: '20px 0' }}>
      Sprint'e görev eklendikçe burndown grafiği görünecek.
    </div>
  );

  const today = new Date();
  const points = [];
  for (let d = 0; d <= totalDays; d++) {
    const dayEnd = new Date(start);
    dayEnd.setDate(dayEnd.getDate() + d);
    dayEnd.setHours(23, 59, 59);
    const remaining = tasks.reduce((s, t) => {
      if (!t.completedAt) return s + val(t);
      return new Date(t.completedAt) > dayEnd ? s + val(t) : s;
    }, 0);
    points.push({ d, remaining });
  }

  const W = 500, H = 150, pL = 32, pR = 12, pT = 8, pB = 24;
  const cW = W - pL - pR, cH = H - pT - pB;
  const x = (d) => pL + (d / totalDays) * cW;
  const y = (v) => pT + cH - (v / totalValue) * cH;
  const todayDay   = Math.min(totalDays, Math.max(0, Math.round((today - start) / 86400000)));
  const idealPath  = `M ${x(0)} ${y(totalValue)} L ${x(totalDays)} ${y(0)}`;
  const actualPts  = points.filter(p => p.d <= todayDay);
  const actualPath = actualPts.map((p, i) => `${i === 0 ? 'M' : 'L'} ${x(p.d)} ${y(p.remaining)}`).join(' ');

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', maxHeight: 160, overflow: 'visible' }}>
      {[0, 0.5, 1].map(v => (
        <line key={v} x1={pL} y1={y(v * totalValue)} x2={W - pR} y2={y(v * totalValue)}
          stroke="var(--border)" strokeWidth={1} />
      ))}
      {[totalValue, Math.round(totalValue / 2), 0].map(v => (
        <text key={v} x={pL - 5} y={y(v) + 4} textAnchor="end" fontSize={9} fill="var(--text-faint)">{v}</text>
      ))}
      <path d={idealPath} stroke="var(--text-faint)" strokeWidth={1.5} strokeDasharray="5 4" fill="none" />
      {actualPath && <path d={actualPath} stroke="var(--accent)" strokeWidth={2.5} fill="none" strokeLinecap="round" strokeLinejoin="round" />}
      {todayDay > 0 && todayDay < totalDays && (
        <line x1={x(todayDay)} y1={pT} x2={x(todayDay)} y2={H - pB}
          stroke="var(--accent)" strokeWidth={1} strokeDasharray="3 3" opacity={0.5} />
      )}
      <line x1={pL} y1={pT} x2={pL} y2={H - pB} stroke="var(--border-strong)" strokeWidth={1.5} />
      <line x1={pL} y1={H - pB} x2={W - pR} y2={H - pB} stroke="var(--border-strong)" strokeWidth={1.5} />
      <text x={pL} y={H - 6} fontSize={9} fill="var(--text-faint)">{sprint.startDate?.slice(5)}</text>
      <text x={W - pR} y={H - 6} fontSize={9} fill="var(--text-faint)" textAnchor="end">{sprint.endDate?.slice(5)}</text>
      <line x1={W - 140} y1={pT + 8} x2={W - 120} y2={pT + 8} stroke="var(--text-faint)" strokeWidth={1.5} strokeDasharray="5 4" />
      <text x={W - 116} y={pT + 12} fontSize={9} fill="var(--text-faint)">İdeal</text>
      <line x1={W - 90} y1={pT + 8} x2={W - 70} y2={pT + 8} stroke="var(--accent)" strokeWidth={2} />
      <text x={W - 66} y={pT + 12} fontSize={9} fill="var(--text-faint)">Gerçek</text>
    </svg>
  );
}

/* ── Velocity çubuk grafiği ────────────────────────────────── */
function VelocityBar({ sprints }) {
  const max = Math.max(...sprints.map(s => s.velocityPoints || 0), 1);
  const avg = Math.round(sprints.reduce((s, sp) => s + sp.velocityPoints, 0) / sprints.length);
  return (
    <div className="velocity-section">
      <div className="velocity-header">
        <span className="velocity-label">Sprint hızı</span>
        <span className="velocity-avg">Ort. {avg}</span>
      </div>
      <div className="velocity-bars">
        {sprints.map(s => (
          <div key={s.id} className="velocity-bar-item" title={`${s.name}: ${s.velocityPoints}`}>
            <div className="velocity-bar-track">
              <div className="velocity-bar-fill" style={{ height: `${Math.round((s.velocityPoints / max) * 100)}%` }} />
            </div>
            <div className="velocity-bar-val">{s.velocityPoints}</div>
            <div className="velocity-bar-name">{s.name.length > 7 ? s.name.slice(0, 7) + '…' : s.name}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── Sprint görev kartı ────────────────────────────────────── */
function SprintTaskCard({ task, state, onSelect, onDragStart, onDragEnd, onMoveToSprint, moveLabel, onUpdatePoints }) {
  const tagById  = Object.fromEntries(state.tags.map(t => [t.id, t]));
  const taskTags = (task.tags || []).map(id => tagById[id]).filter(Boolean);
  const overdue  = spOver(task.due, task.status);
  const [showPts, setShowPts] = React.useState(false);
  const ptsRef = React.useRef(null);

  React.useEffect(() => {
    if (!showPts) return;
    const close = (e) => {
      if (ptsRef.current && !ptsRef.current.contains(e.target)) setShowPts(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [showPts]);

  return (
    <div
      className={`sprint-task-card ${task.status === 'done' ? 'done' : ''}`}
      draggable
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      onClick={onSelect}
    >
      <div className="sprint-task-header">
        <div className="sprint-task-title">{task.title}</div>
        <div className="sp-badge-wrap" ref={ptsRef} onClick={e => { e.stopPropagation(); setShowPts(v => !v); }}>
          <span className={`sp-badge ${task.storyPoints ? 'has-pts' : ''}`}>
            {task.storyPoints ?? '?'}
          </span>
          {showPts && (
            <div className="sp-picker">
              <button
                className={`sp-btn ${!task.storyPoints ? 'active' : ''}`}
                onClick={e => { e.stopPropagation(); onUpdatePoints(null); setShowPts(false); }}
              >—</button>
              {SP_POINTS.map(p => (
                <button
                  key={p}
                  className={`sp-btn ${task.storyPoints === p ? 'active' : ''}`}
                  onClick={e => { e.stopPropagation(); onUpdatePoints(p); setShowPts(false); }}
                >{p}</button>
              ))}
            </div>
          )}
        </div>
      </div>

      {taskTags.length > 0 && (
        <div className="sprint-task-tags">
          {taskTags.slice(0, 3).map(tag => <SPTag key={tag.id} tag={tag} />)}
        </div>
      )}

      <div className="sprint-task-meta">
        <SPPriority value={task.priority} />
        {task.due && (
          <span className={`sprint-task-due ${overdue ? 'overdue' : ''}`}>
            <SPIcons.Clock size={11} /> {spRel(task.due)}
          </span>
        )}
        {onMoveToSprint && (
          <button
            className="sprint-move-btn"
            onClick={e => { e.stopPropagation(); onMoveToSprint(); }}
            title={moveLabel || "Sprint'e taşı"}
          >
            {moveLabel ? <SPIcons.ArchiveRestore size={12} /> : <SPIcons.ArrowRight size={12} />}
          </button>
        )}
      </div>
    </div>
  );
}

/* ── Sprint oluştur / düzenle modal ───────────────────────── */
function SprintModal({ title, initial, projectId, onSave, onClose, onDelete, onCloseSprint }) {
  const [name,     setName]  = React.useState(initial?.name || '');
  const [goal,     setGoal]  = React.useState(initial?.goal || '');
  const [startDate, setStart] = React.useState(initial?.startDate || '');
  const [endDate,   setEnd]   = React.useState(initial?.endDate || '');
  const [capacity,  setCap]   = React.useState(initial?.capacity || '');

  const save = () => {
    if (!name.trim()) return;
    onSave({
      projectId,
      name: name.trim(),
      goal: goal.trim(),
      startDate: startDate || null,
      endDate: endDate || null,
      capacity: capacity ? parseInt(capacity, 10) : null,
    });
  };

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="sprint-modal" onClick={e => e.stopPropagation()}>
        <div className="sprint-modal-header">
          <h3>{title}</h3>
          <button className="icon-btn icon-btn-sm" onClick={onClose}><SPIcons.X size={16} /></button>
        </div>
        <div className="sprint-modal-body">
          <label className="login-field">
            <span>Sprint Adı</span>
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="Sprint 1" autoFocus />
          </label>
          <label className="login-field">
            <span>Hedef</span>
            <input className="input" value={goal} onChange={e => setGoal(e.target.value)} placeholder="Bu sprintte ne bitecek?" />
          </label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <label className="login-field">
              <span>Başlangıç</span>
              <input type="date" className="input" value={startDate} onChange={e => setStart(e.target.value)} />
            </label>
            <label className="login-field">
              <span>Bitiş</span>
              <input type="date" className="input" value={endDate} onChange={e => setEnd(e.target.value)} />
            </label>
          </div>
          <label className="login-field">
            <span>Kapasite (story point)</span>
            <input type="number" className="input" value={capacity} onChange={e => setCap(e.target.value)}
              placeholder="Örn: 40 — takım kapasitesi" min="0" />
          </label>
        </div>
        <div className="sprint-modal-footer">
          {onDelete && (
            <button className="btn btn-ghost btn-sm" style={{ color: 'var(--p-high)' }} onClick={onDelete}>Sil</button>
          )}
          {onCloseSprint && (
            <button className="btn btn-ghost btn-sm" onClick={onCloseSprint}>Sprintti Kapat</button>
          )}
          <div style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Vazgeç</button>
          <button className="btn btn-primary btn-sm" onClick={save}>Kaydet</button>
        </div>
      </div>
    </div>
  );
}

/* ── Sprint kapanış review modal ──────────────────────────── */
function SprintReviewModal({ sprint, tasks, nextSprints, onConfirm, onClose }) {
  const done       = tasks.filter(t => t.status === 'done');
  const unfinished = tasks.filter(t => t.status !== 'done');
  const usePoints  = tasks.some(t => t.storyPoints);
  const donePts    = done.reduce((s, t) => s + (t.storyPoints || 0), 0);
  const totalPts   = tasks.reduce((s, t) => s + (t.storyPoints || 0), 0);
  const velocity   = usePoints ? donePts : done.length;

  const [disposition, setDisposition] = React.useState(
    () => Object.fromEntries(unfinished.map(t => [t.id, 'backlog']))
  );
  const allToBacklog = () =>
    setDisposition(Object.fromEntries(unfinished.map(t => [t.id, 'backlog'])));
  const allRollover = (spId) =>
    setDisposition(Object.fromEntries(unfinished.map(t => [t.id, spId])));

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="sprint-modal sprint-review-modal" onClick={e => e.stopPropagation()}>
        <div className="sprint-modal-header">
          <SPIcons.CheckCircle size={17} style={{ color: 'var(--accent)' }} />
          <h3>Sprint Kapanışı · {sprint.name}</h3>
          <button className="icon-btn icon-btn-sm" onClick={onClose}><SPIcons.X size={16} /></button>
        </div>

        <div className="sprint-modal-body">
          {/* Özet istatistikler */}
          <div className="sprint-review-summary">
            <div className="sprint-review-stat">
              <strong style={{ color: 'var(--accent)' }}>{done.length}</strong>
              <span>Tamamlandı</span>
            </div>
            <div className="sprint-review-stat">
              <strong style={{ color: unfinished.length ? 'var(--p-high)' : undefined }}>{unfinished.length}</strong>
              <span>Tamamlanmadı</span>
            </div>
            {usePoints && (
              <div className="sprint-review-stat">
                <strong>{donePts}/{totalPts}</strong>
                <span>Story point</span>
              </div>
            )}
            <div className="sprint-review-stat sprint-review-stat-accent">
              <strong>{velocity}</strong>
              <span>{usePoints ? 'SP hızı' : 'Görev hızı'}</span>
            </div>
          </div>

          {/* Tamamlanmayan görevler */}
          {unfinished.length > 0 && (
            <div>
              <div className="sprint-review-section-header">
                <span className="sprint-review-label">Tamamlanmayan görevler</span>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button className="btn btn-ghost btn-sm" style={{ fontSize: 11 }} onClick={allToBacklog}>
                    Tümü → Backlog
                  </button>
                  {nextSprints.slice(0, 1).map(ns => (
                    <button key={ns.id} className="btn btn-ghost btn-sm" style={{ fontSize: 11 }}
                      onClick={() => allRollover(ns.id)}>
                      Tümü → {ns.name}
                    </button>
                  ))}
                </div>
              </div>
              <div className="sprint-review-task-list">
                {unfinished.map(t => (
                  <div key={t.id} className="sprint-review-row">
                    <span className="sprint-review-task-title">{t.title}</span>
                    {t.storyPoints && <span className="sp-badge has-pts" style={{ fontSize: 10 }}>{t.storyPoints}</span>}
                    <div className="sprint-review-actions">
                      <button
                        className={`sprint-review-btn ${disposition[t.id] === 'backlog' ? 'active' : ''}`}
                        onClick={() => setDisposition(d => ({ ...d, [t.id]: 'backlog' }))}
                      >Backlog</button>
                      {nextSprints.map(ns => (
                        <button
                          key={ns.id}
                          className={`sprint-review-btn ${disposition[t.id] === ns.id ? 'active' : ''}`}
                          onClick={() => setDisposition(d => ({ ...d, [t.id]: ns.id }))}
                        >{ns.name}</button>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="sprint-modal-footer">
          <div style={{ flex: 1 }} />
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Vazgeç</button>
          <button className="btn btn-primary btn-sm" onClick={() => onConfirm({ taskDisposition: disposition, velocityPoints: velocity })}>
            <SPIcons.Check size={13} /> Sprintti Kapat
          </button>
        </div>
      </div>
    </div>
  );
}

window.SprintView = SprintView;
