// Reporting view — tabs, presets, burnup, gecikme dağılımı, verimlilik skoru
const RPIcons = window.Icons;
const { parseDateKey: rpDate, toDateKey: rpDateKey, COLUMNS: RP_COLS, isOverdue: rpIsOverdue } = window.PMStore;

// ── Donut chart — saf SVG ────────────────────────────────────
function rpPolarToCart(cx, cy, r, deg) {
  const rad = (deg - 90) * Math.PI / 180;
  return [cx + r * Math.cos(rad), cy + r * Math.sin(rad)];
}
function rpArcPath(cx, cy, R, r, s, e) {
  if (Math.abs(e - s) >= 360) e = s + 359.99;
  const [ax, ay] = rpPolarToCart(cx, cy, R, s);
  const [bx, by] = rpPolarToCart(cx, cy, R, e);
  const [ex, ey] = rpPolarToCart(cx, cy, r, e);
  const [fx, fy] = rpPolarToCart(cx, cy, r, s);
  const lg = (e - s) > 180 ? 1 : 0;
  return `M${ax},${ay}A${R},${R} 0 ${lg},1 ${bx},${by}L${ex},${ey}A${r},${r} 0 ${lg},0 ${fx},${fy}Z`;
}
function DonutChart({ segments, size = 168, thickness = 36, centerVal, centerLbl, onSlice }) {
  const [hov, setHov] = React.useState(null);
  const cx = size / 2, cy = size / 2;
  const R = size / 2 - 6, r = R - thickness;
  const total = segments.reduce((s, d) => s + d.value, 0);
  if (!total) return <div className="donut-empty">Veri yok</div>;
  let angle = 0;
  const slices = segments.map(seg => {
    const sweep = (seg.value / total) * 360;
    const path  = rpArcPath(cx, cy, R, r, angle, angle + sweep);
    angle += sweep;
    return { ...seg, path, pct: Math.round(seg.value / total * 100) };
  });
  const active = hov !== null ? slices[hov] : null;
  return (
    <div className="donut-wrap">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}
        style={{ overflow: 'visible', display: 'block', margin: '0 auto' }}>
        <circle cx={cx} cy={cy} r={(R + r) / 2} fill="none"
          stroke="var(--bg-sunken)" strokeWidth={thickness} />
        {slices.map((sl, i) => (
          <path key={i} d={sl.path} fill={sl.color}
            stroke="var(--panel)" strokeWidth={3}
            style={{ cursor: 'pointer', transition: 'opacity .14s, transform .14s',
              opacity: hov === null || hov === i ? 1 : 0.3,
              transformOrigin: `${cx}px ${cy}px`,
              transform: hov === i ? 'scale(1.05)' : 'scale(1)' }}
            onMouseEnter={() => setHov(i)}
            onMouseLeave={() => setHov(null)}
            onClick={() => { if (onSlice && sl.id) onSlice(sl.id); }} />
        ))}
        {active ? (
          <>
            <text x={cx} y={cy - 8} textAnchor="middle" fontSize={17} fontWeight={700} fill={active.color}>{active.value}</text>
            <text x={cx} y={cy + 8} textAnchor="middle" fontSize={9.5} fill="var(--text-muted)">
              {active.label.length > 15 ? active.label.slice(0, 14) + '…' : active.label}
            </text>
            <text x={cx} y={cy + 21} textAnchor="middle" fontSize={9} fill="var(--text-faint)">{active.pct}%</text>
          </>
        ) : (
          <>
            <text x={cx} y={cy - 4} textAnchor="middle" fontSize={26} fontWeight={700} fill="var(--text)"
              style={{ fontFamily: 'var(--font-display)', letterSpacing: '-0.02em' }}>{centerVal}</text>
            <text x={cx} y={cy + 14} textAnchor="middle" fontSize={10} fill="var(--text-faint)">{centerLbl}</text>
          </>
        )}
      </svg>
      <div className="donut-legend">
        {slices.map((sl, i) => (
          <div key={i} className={`donut-legend-row${hov === i ? ' active' : ''}`}
            onMouseEnter={() => setHov(i)} onMouseLeave={() => setHov(null)}>
            <span className="donut-legend-dot" style={{ background: sl.color }} />
            <span className="donut-legend-lbl">{sl.label}</span>
            <span className="donut-legend-val">{sl.value}</span>
            <span className="donut-legend-pct">{sl.pct}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── Burnup Chart (8 haftalık) ─────────────────────────────────
function BurnupChart({ tasks }) {
  const now = new Date(); now.setHours(0,0,0,0);
  let cumAdded = 0, cumDone = 0;
  const data = Array.from({ length: 8 }, (_, i) => {
    const wend = new Date(now);
    wend.setDate(now.getDate() - (7 - i - 1) * 7);
    const wstart = new Date(wend);
    wstart.setDate(wend.getDate() - 6);
    const added = tasks.filter(t => {
      if (!t.createdAt) return false;
      const d = new Date(t.createdAt);
      return d >= wstart && d <= wend;
    }).length;
    const done = tasks.filter(t => {
      if (t.status !== 'done') return false;
      const ts = t.completedAt || t.updatedAt;
      if (!ts) return false;
      const d = new Date(ts);
      return d >= wstart && d <= wend;
    }).length;
    cumAdded += added;
    cumDone  += done;
    return { cumAdded, cumDone, label: `${wend.getDate()}/${wend.getMonth()+1}` };
  });

  const maxVal = Math.max(...data.map(d => d.cumAdded), 1);
  const W = 500, H = 140, pL = 32, pR = 10, pT = 10, pB = 28;
  const cW = W - pL - pR, cH = H - pT - pB;
  const step = cW / (data.length - 1);
  const px = i => pL + i * step;
  const py = v => pT + cH - (v / maxVal) * cH;

  const addedPath = data.map((d, i) => `${i===0?'M':'L'}${px(i).toFixed(1)},${py(d.cumAdded).toFixed(1)}`).join(' ');
  const donePath  = data.map((d, i) => `${i===0?'M':'L'}${px(i).toFixed(1)},${py(d.cumDone).toFixed(1)}`).join(' ');

  return (
    <div>
      <div style={{ width: '100%', overflowX: 'auto' }}>
        <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', maxHeight: H, display: 'block' }}>
          {[0, 0.5, 1].map((r, i) => (
            <line key={i} x1={pL} y1={pT+cH*(1-r)} x2={W-pR} y2={pT+cH*(1-r)}
              stroke="var(--border)" strokeWidth={1} />
          ))}
          <path d={addedPath} fill="none" stroke="var(--accent)" strokeWidth={2}
            strokeDasharray="5 3" strokeLinecap="round" />
          <path d={donePath} fill="none" stroke="#22c55e" strokeWidth={2.5} strokeLinecap="round" />
          {data.map((d, i) => (
            <g key={i}>
              <circle cx={px(i)} cy={py(d.cumAdded)} r={3} fill="var(--accent)" />
              <circle cx={px(i)} cy={py(d.cumDone)}  r={3} fill="#22c55e" />
              <text x={px(i)} y={H-pB+14} textAnchor="middle" fontSize={9} fill="var(--text-faint)">{d.label}</text>
            </g>
          ))}
        </svg>
      </div>
      <div className="burnup-legend">
        <span className="burnup-leg added">— Eklenen (kümülatif)</span>
        <span className="burnup-leg done">—— Tamamlanan (kümülatif)</span>
      </div>
    </div>
  );
}

// ── Gecikme Dağılımı ─────────────────────────────────────────
function GecikmeDistribution({ tasks }) {
  const now = new Date(); now.setHours(0,0,0,0);
  const buckets = [
    { label: '1–3 gün',  color: '#f59e0b', count: 0 },
    { label: '4–7 gün',  color: '#f97316', count: 0 },
    { label: '8–14 gün', color: '#ef4444', count: 0 },
    { label: '14+ gün',  color: '#7f1d1d', count: 0 },
  ];
  tasks.forEach(t => {
    if (t.status === 'done' || !t.due) return;
    const due = rpDate(t.due); due.setHours(0,0,0,0);
    const diff = Math.round((now - due) / 86400000);
    if (diff <= 0) return;
    if (diff <= 3) buckets[0].count++;
    else if (diff <= 7) buckets[1].count++;
    else if (diff <= 14) buckets[2].count++;
    else buckets[3].count++;
  });
  const total = buckets.reduce((s, b) => s + b.count, 0);
  if (!total) return <div className="report-empty">Gecikmiş görev yok ✓</div>;
  const maxB = Math.max(...buckets.map(b => b.count), 1);
  return (
    <div className="gecikme-dist">
      {buckets.map((b, i) => (
        <div key={i} className="gecikme-row">
          <span className="gecikme-lbl">{b.label}</span>
          <div className="gecikme-track">
            <div className="gecikme-fill" style={{ width: `${(b.count/maxB)*100}%`, background: b.color }} />
          </div>
          <span className="gecikme-val" style={{ color: b.count > 0 ? b.color : 'var(--text-faint)' }}>
            {b.count}
          </span>
        </div>
      ))}
      <div className="gecikme-footer">{total} gecikmiş görev toplam</div>
    </div>
  );
}

// ── Gün × Saat Isı Haritası ──────────────────────────────────
function HeatmapChart({ tasks }) {
  const DAYS = ['Pzt','Sal','Çar','Per','Cum','Cmt','Paz'];
  const BLOCKS = ['00–04','04–08','08–12','12–16','16–20','20–24'];
  const grid = Array.from({ length: 7 }, () => Array(6).fill(0));
  let max = 0;
  tasks.forEach(t => {
    if (t.status !== 'done' || !t.completedAt) return;
    const d = new Date(t.completedAt);
    const day = (d.getDay() + 6) % 7;
    const block = Math.floor(d.getHours() / 4);
    grid[day][block]++;
    if (grid[day][block] > max) max = grid[day][block];
  });
  if (!max) return <div className="report-empty">Tamamlanma verisi yok</div>;
  return (
    <div className="rp-heatmap">
      <div className="rp-heatmap-row rp-heatmap-head">
        <span className="rp-heatmap-day" />
        {BLOCKS.map(b => <span key={b} className="rp-heatmap-col-lbl">{b}</span>)}
      </div>
      {DAYS.map((day, di) => (
        <div key={day} className="rp-heatmap-row">
          <span className="rp-heatmap-day">{day}</span>
          {grid[di].map((v, bi) => (
            <span key={bi} className="rp-heatmap-cell"
              title={`${day} ${BLOCKS[bi]}: ${v} görev`}
              style={{ background: v
                ? `color-mix(in srgb, var(--accent) ${20 + Math.round(v / max * 80)}%, var(--bg-sunken))`
                : 'var(--bg-sunken)' }} />
          ))}
        </div>
      ))}
    </div>
  );
}

// ── Dönem karşılaştırma rozeti ───────────────────────────────
function MetricDelta({ cur, prev, suffix, invert }) {
  if (prev === null || prev === undefined || cur === null || cur === undefined) return null;
  const c = parseFloat(cur), p = parseFloat(prev);
  if (isNaN(c) || isNaN(p)) return null;
  const diff = c - p;
  if (Math.abs(diff) < 0.05) return <span className="rp-delta flat">— önceki dönemle aynı</span>;
  const up = diff > 0;
  const good = invert ? !up : up;
  const txt = Number.isInteger(Math.abs(diff)) ? Math.abs(diff) : Math.abs(diff).toFixed(1);
  return (
    <span className={`rp-delta ${good ? 'good' : 'bad'}`}>
      {up ? '▲' : '▼'} {txt}{suffix || ''} önceki döneme göre
    </span>
  );
}

// ── Ana Rapor Görünümü ────────────────────────────────────────
function ReportView({ state, onSelectTask }) {
  const [tab,           setTab]          = React.useState('genel');
  const [projectFilter, setProjectFilter] = React.useState('all');
  const [dateFrom,      setDateFrom]     = React.useState('');
  const [dateTo,        setDateTo]       = React.useState('');
  const [activePreset,  setActivePreset] = React.useState('');

  const projects = state.projects || [];
  const allTasks = state.tasks    || [];
  const tags     = state.tags     || [];

  // Hızlı dönem presetleri
  const applyPreset = (preset) => {
    const now = new Date();
    const pad = n => String(n).padStart(2,'0');
    const fmt = d => `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}`;
    let from = '', to = '';
    if (preset === 'week') {
      const start = new Date(now); start.setDate(now.getDate() - ((now.getDay()+6)%7));
      const end   = new Date(start); end.setDate(start.getDate() + 6);
      from = fmt(start); to = fmt(end);
    } else if (preset === 'month') {
      from = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
      to   = fmt(new Date(now.getFullYear(), now.getMonth()+1, 0));
    } else if (preset === 'year') {
      from = `${now.getFullYear()}-01-01`;
      to   = `${now.getFullYear()}-12-31`;
    }
    setDateFrom(from); setDateTo(to);
    setActivePreset(from === '' && to === '' ? 'all' : preset);
  };

  const clearDates = () => { setDateFrom(''); setDateTo(''); setActivePreset('all'); };

  const fromDate = dateFrom ? new Date(dateFrom + 'T00:00:00') : null;
  const toDate   = dateTo   ? new Date(dateTo   + 'T23:59:59') : null;

  const tasks = allTasks.filter(t => {
    if (projectFilter !== 'all' && t.projectId !== projectFilter) return false;
    if (fromDate || toDate) {
      const ref = t.completedAt ? new Date(t.completedAt) : (t.createdAt ? new Date(t.createdAt) : null);
      if (!ref) return !fromDate;
      if (fromDate && ref < fromDate) return false;
      if (toDate   && ref > toDate)   return false;
    }
    return true;
  });

  const projById = Object.fromEntries(projects.map(p => [p.id, p]));
  const tagById  = Object.fromEntries(tags.map(t => [t.id, t]));
  const done     = tasks.filter(t => t.status === 'done');

  // Önceki dönem metrikleri — yalnızca tarih aralığı seçiliyken hesaplanır
  const prevMetrics = React.useMemo(() => {
    if (!fromDate || !toDate) return null;
    const span = toDate - fromDate;
    const prevTo   = new Date(fromDate.getTime() - 1);
    const prevFrom = new Date(fromDate.getTime() - span - 1);
    const prevTasks = allTasks.filter(t => {
      if (projectFilter !== 'all' && t.projectId !== projectFilter) return false;
      const ref = t.completedAt ? new Date(t.completedAt) : (t.createdAt ? new Date(t.createdAt) : null);
      return ref && ref >= prevFrom && ref <= prevTo;
    });
    const prevDone = prevTasks.filter(t => t.status === 'done');
    const prevTimes = prevDone
      .filter(t => t.createdAt && (t.completedAt || t.updatedAt))
      .map(t => (new Date(t.completedAt || t.updatedAt) - new Date(t.createdAt)) / 86400000);
    return {
      total: prevTasks.length,
      rate: prevTasks.length ? Math.round(prevDone.length / prevTasks.length * 100) : 0,
      avgDays: prevTimes.length ? (prevTimes.reduce((a, b) => a + b, 0) / prevTimes.length).toFixed(1) : null,
    };
  }, [dateFrom, dateTo, projectFilter, allTasks.length]);

  const doneTs = (t) => t.completedAt || t.updatedAt;
  const completionTimes = done
    .filter(t => t.createdAt && doneTs(t))
    .map(t => (new Date(doneTs(t)) - new Date(t.createdAt)) / 86400000);
  const avgDays = completionTimes.length
    ? (completionTimes.reduce((a, b) => a + b, 0) / completionTimes.length).toFixed(1)
    : null;

  const totalMinutes = tasks.reduce((s, t) => s + (t.timeLog || []).reduce((ss, e) => ss + (e.duration || 0), 0), 0);
  const fmtTime = (mins) => { if (!mins) return '0s'; const h = Math.floor(mins/60), m = mins%60; return m > 0 ? `${h}s ${m}dk` : `${h}s`; };

  const weeklyData = React.useMemo(() => {
    const weeks = [];
    const now = new Date(); now.setHours(0,0,0,0);
    for (let w = 7; w >= 0; w--) {
      const start = new Date(now); start.setDate(start.getDate() - w*7 - now.getDay() + 1);
      const end   = new Date(start); end.setDate(end.getDate() + 6); end.setHours(23,59,59);
      const label = `${start.getDate()}/${start.getMonth()+1}`;
      const count = done.filter(t => {
        const ts = doneTs(t); if (!ts) return false;
        const d = new Date(ts);
        return d >= start && d <= end;
      }).length;
      weeks.push({ label, count });
    }
    return weeks;
  }, [done.length, projectFilter, dateFrom, dateTo]);

  const maxWeekly = Math.max(...weeklyData.map(w => w.count), 1);

  const projectBreakdown = projects.map(p => {
    const ptasks = tasks.filter(t => t.projectId === p.id);
    const byStatus = {};
    RP_COLS.forEach(c => { byStatus[c.id] = ptasks.filter(t => t.status === c.id).length; });
    const timeMin = ptasks.reduce((s, t) => s + (t.timeLog||[]).reduce((ss,e) => ss+(e.duration||0), 0), 0);
    return { project: p, total: ptasks.length, byStatus, timeMin };
  }).filter(r => r.total > 0);

  // Etiket × durum çapraz analizi
  const tagStats = tags.map(tag => {
    const tt = tasks.filter(t => t.tags?.includes(tag.id));
    const doneC = tt.filter(t => t.status === 'done').length;
    const overC = tt.filter(t => t.status !== 'done' && rpIsOverdue(t.due, t.status)).length;
    return { tag, count: tt.length, doneC, overC, actC: tt.length - doneC - overC };
  }).filter(r => r.count > 0).sort((a,b) => b.count - a.count).slice(0, 10);
  const maxTag = Math.max(...tagStats.map(t => t.count), 1);

  const prioCounts = {
    high:   tasks.filter(t => t.priority === 'high').length,
    medium: tasks.filter(t => t.priority === 'medium').length,
    low:    tasks.filter(t => t.priority === 'low').length,
  };
  const prioTotal = Object.values(prioCounts).reduce((a,b) => a+b, 0) || 1;

  const recentDone = [...done]
    .filter(t => doneTs(t))
    .sort((a,b) => new Date(doneTs(b)) - new Date(doneTs(a)))
    .slice(0, 6);

  const completionRate = tasks.length ? Math.round(done.length / tasks.length * 100) : 0;

  const projectDonutData = [...projects]
    .map(p => ({ id: p.id, label: p.name, value: tasks.filter(t => t.projectId === p.id).length, color: p.color }))
    .filter(d => d.value > 0).sort((a,b) => b.value - a.value);

  const statusDonutData = [
    { label: 'Yapılacak',  value: tasks.filter(t => t.status === 'todo').length,   color: '#94a3b8' },
    { label: 'Devam Eden', value: tasks.filter(t => t.status === 'doing').length,  color: '#3b82f6' },
    { label: 'İncelemede', value: tasks.filter(t => t.status === 'review').length, color: '#a855f7' },
    { label: 'Tamamlandı', value: tasks.filter(t => t.status === 'done').length,   color: '#ff601f' },
  ].filter(d => d.value > 0);

  const prioDonutData = [
    { label: 'Yüksek', value: prioCounts.high,   color: '#ef4444' },
    { label: 'Orta',   value: prioCounts.medium, color: '#f59e0b' },
    { label: 'Düşük',  value: prioCounts.low,    color: '#3b82f6' },
  ].filter(d => d.value > 0);

  const timeByProject = projectBreakdown
    .filter(r => r.timeMin > 0).sort((a,b) => b.timeMin - a.timeMin).slice(0, 5);
  const maxTime = Math.max(...timeByProject.map(r => r.timeMin), 1);

  // Zamanında teslim — tamamlanan görevlerin kaçı teslim tarihini aşmadan bitti?
  const doneWithDue   = done.filter(t => t.due && doneTs(t));
  const onTimeCount   = doneWithDue.filter(t => rpDateKey(new Date(doneTs(t))) <= t.due).length;
  const lateDoneCount = doneWithDue.length - onTimeCount;
  const onTimeRate    = doneWithDue.length ? Math.round(onTimeCount / doneWithDue.length * 100) : null;

  // Verimlilik Skoru — gecikme bileşeni hem aktif gecikmeleri hem geç tamamlananları sayar
  const overdueCount = tasks.filter(t => t.status !== 'done' && rpIsOverdue(t.due, t.status)).length;
  const lateBlend    = tasks.length > 0 ? (overdueCount + lateDoneCount) / tasks.length : 0;
  const scoreCompletion = Math.round(completionRate * 0.4);
  const scoreTime       = avgDays ? Math.round(Math.max(0, (1 - Math.min(parseFloat(avgDays), 20)/20)) * 30) : 15;
  const scoreOverdue    = Math.round((1 - Math.min(lateBlend, 1)) * 30);
  const perfScore = scoreCompletion + scoreTime + scoreOverdue;
  const perfLabel = perfScore >= 80 ? 'Mükemmel 🏆' : perfScore >= 60 ? 'İyi 👍' : perfScore >= 40 ? 'Orta ⚡' : 'Geliştirilmeli ⚠️';
  const perfColor = perfScore >= 80 ? '#22c55e' : perfScore >= 60 ? '#3b82f6' : perfScore >= 40 ? '#f59e0b' : '#ef4444';

  // Verimlilik skoru geçmişi — haftalık snapshot (yalnızca filtresiz görünümde kaydedilir)
  const [perfHistory, setPerfHistory] = React.useState([]);
  React.useEffect(() => {
    let hist = [];
    try { hist = JSON.parse(localStorage.getItem('navia_perf_history') || '[]'); } catch (e) { hist = []; }
    if (projectFilter === 'all' && !dateFrom && !dateTo && allTasks.length > 0) {
      const monday = new Date(); monday.setHours(0,0,0,0);
      monday.setDate(monday.getDate() - ((monday.getDay() + 6) % 7));
      const wk = rpDateKey(monday);
      const last = hist[hist.length - 1];
      if (last && last.week === wk) last.score = perfScore;
      else hist.push({ week: wk, score: perfScore });
      if (hist.length > 12) hist = hist.slice(hist.length - 12);
      localStorage.setItem('navia_perf_history', JSON.stringify(hist));
    }
    setPerfHistory(hist);
  }, [perfScore, projectFilter, dateFrom, dateTo]);

  // Tahmini bitiş — son 4 haftanın tamamlama hızına göre
  const activeCount = tasks.filter(t => t.status !== 'done').length;
  const fourWeeksAgo = new Date(); fourWeeksAgo.setDate(fourWeeksAgo.getDate() - 28);
  const recentDoneCount = done.filter(t => doneTs(t) && new Date(doneTs(t)) >= fourWeeksAgo).length;
  const weeklyRate = recentDoneCount / 4;
  const forecastWeeks = weeklyRate > 0 && activeCount > 0 ? Math.ceil(activeCount / weeklyRate) : null;

  // Sprint hızı (velocity) — kapanmış sprintler
  const completedSprints = (state.sprints || [])
    .filter(sp => sp.status === 'completed' && sp.velocityPoints != null)
    .sort((a, b) => (a.endDate || '').localeCompare(b.endDate || ''))
    .slice(-8);
  const maxVel = Math.max(...completedSprints.map(sp => sp.velocityPoints), 1);
  const avgVel = completedSprints.length
    ? Math.round(completedSprints.reduce((s, sp) => s + sp.velocityPoints, 0) / completedSprints.length)
    : 0;

  // Gerçek kârlılık — finans işlemleri + işçilik maliyeti (saat ücreti × süre)
  const txInRange = (state.transactions || []).filter(tx => {
    if (projectFilter !== 'all' && tx.projectId !== projectFilter) return false;
    if (!fromDate && !toDate) return true;
    const d = new Date((tx.date || '1970-01-01') + 'T12:00:00');
    if (fromDate && d < fromDate) return false;
    if (toDate   && d > toDate)   return false;
    return true;
  });
  const profitRows = projects.map(p => {
    const ptx = txInRange.filter(tx => tx.projectId === p.id && (!tx.status || tx.status === 'done'));
    const income  = ptx.filter(tx => tx.type === 'income') .reduce((s, tx) => s + (tx.amount || 0), 0);
    const expense = ptx.filter(tx => tx.type === 'expense').reduce((s, tx) => s + (tx.amount || 0), 0);
    const pb = projectBreakdown.find(r => r.project.id === p.id);
    const laborCost = p.hourlyRate ? Math.round(((pb ? pb.timeMin : 0) / 60) * p.hourlyRate) : 0;
    return { project: p, income, expense, laborCost, net: income - expense - laborCost };
  }).filter(r => r.income > 0 || r.expense > 0 || r.laborCost > 0)
    .sort((a, b) => b.net - a.net);

  // PDF / yazdır — yazdırma sırasında geçici olarak aydınlık temaya geç
  const exportPDF = () => {
    const root = document.documentElement;
    const prevTheme = root.dataset.theme;
    root.dataset.theme = 'light';
    setTimeout(() => {
      window.print();
      root.dataset.theme = prevTheme;
    }, 100);
  };

  const exportCSV = () => {
    const rows = [
      ['Başlık','Firma','Durum','Öncelik','Teslim','Tamamlanma','Story Point','Toplam Süre (dk)'],
      ...tasks.map(t => [
        `"${(t.title||'').replace(/"/g,'""')}"`,
        `"${(projById[t.projectId]?.name||'').replace(/"/g,'""')}"`,
        t.status, t.priority, t.due||'',
        t.completedAt ? new Date(t.completedAt).toLocaleDateString('tr-TR') : '',
        t.storyPoints||'',
        (t.timeLog||[]).reduce((s,e) => s+(e.duration||0), 0),
      ].join(','))
    ];
    const blob = new Blob([rows.join('\n')], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url;
    a.download = `navia-rapor-${new Date().toISOString().slice(0,10)}.csv`;
    a.click(); URL.revokeObjectURL(url);
  };

  const TABS = [
    { id: 'genel',    label: 'Genel' },
    { id: 'gorevler', label: 'Görevler' },
    { id: 'firmalar', label: 'Firmalar' },
  ];
  const PRESETS = [
    { id: 'week',  label: 'Bu Hafta' },
    { id: 'month', label: 'Bu Ay' },
    { id: 'year',  label: 'Bu Yıl' },
    { id: 'all',   label: 'Tümü' },
  ];

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

      {/* ── Header ─────────────────────────────────────────── */}
      <div className="report-header">
        <h2 className="report-title">Raporlar</h2>
        <div className="report-filters">
          {/* Hızlı dönem butonları */}
          <div className="report-presets">
            {PRESETS.map(p => (
              <button key={p.id}
                className={`rp-preset-btn${activePreset === p.id ? ' active' : ''}`}
                onClick={() => { if (p.id === 'all') clearDates(); else applyPreset(p.id); }}>
                {p.label}
              </button>
            ))}
          </div>
          <select className="select-control" value={projectFilter} onChange={e => setProjectFilter(e.target.value)}>
            <option value="all">Tüm Firmalar</option>
            {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <input type="date" className="select-control" value={dateFrom} onChange={e => { setDateFrom(e.target.value); setActivePreset(''); }} title="Başlangıç tarihi" />
          <span style={{ color: 'var(--text-faint)', fontSize: 12 }}>—</span>
          <input type="date" className="select-control" value={dateTo}   onChange={e => { setDateTo(e.target.value);   setActivePreset(''); }} title="Bitiş tarihi" />
          {(dateFrom || dateTo) && (
            <button className="btn btn-ghost btn-sm" onClick={clearDates}>
              <RPIcons.X size={12} /> Temizle
            </button>
          )}
          <button className="btn btn-ghost btn-sm" onClick={exportCSV} title="CSV dışa aktar">
            <RPIcons.FileDown size={14} /> CSV
          </button>
          <button className="btn btn-ghost btn-sm" onClick={exportPDF} title="PDF olarak yazdır">
            <RPIcons.FileText size={14} /> PDF
          </button>
        </div>
      </div>

      {/* Cetvel imzası */}
      <div className="dash-rule" aria-hidden="true" />

      {/* ── Metric cards ───────────────────────────────────── */}
      <div className="report-metrics">
        <div className="report-metric">
          <span className="report-metric-val">{tasks.length}</span>
          <span className="report-metric-lbl">Toplam Görev</span>
          {prevMetrics && <MetricDelta cur={tasks.length} prev={prevMetrics.total} suffix=" görev" />}
        </div>
        <div className="report-metric accent">
          <span className="report-metric-val">{completionRate}%</span>
          <span className="report-metric-lbl">Tamamlanma Oranı</span>
          {prevMetrics && <MetricDelta cur={completionRate} prev={prevMetrics.rate} suffix=" puan" />}
        </div>
        <div className="report-metric">
          <span className="report-metric-val">{avgDays ?? '—'}</span>
          <span className="report-metric-lbl">Ort. Tamamlanma (gün)</span>
          {prevMetrics && avgDays !== null && prevMetrics.avgDays !== null &&
            <MetricDelta cur={avgDays} prev={prevMetrics.avgDays} suffix=" gün" invert />}
        </div>
        <div className="report-metric">
          <span className="report-metric-val">{onTimeRate !== null ? `${onTimeRate}%` : '—'}</span>
          <span className="report-metric-lbl">Zamanında Teslim</span>
          {onTimeRate !== null && <span style={{ fontSize: 10, color: 'var(--text-faint)' }}>{onTimeCount}/{doneWithDue.length} görev</span>}
        </div>
        <div className="report-metric">
          <span className="report-metric-val">{activeCount}</span>
          <span className="report-metric-lbl">Aktif Görev</span>
        </div>
        <div className="report-metric">
          <span className="report-metric-val">{fmtTime(totalMinutes)}</span>
          <span className="report-metric-lbl">Toplam Süre</span>
        </div>
        <div className="report-metric">
          <span className="report-metric-val" style={{ color: perfColor }}>{perfScore}</span>
          <span className="report-metric-lbl">Verimlilik Skoru</span>
          <span style={{ fontSize: 10, color: perfColor, fontWeight: 600 }}>{perfLabel}</span>
        </div>
      </div>

      {/* ── Sekmeler ───────────────────────────────────────── */}
      <div className="report-tabs">
        {TABS.map(t => (
          <button key={t.id} className={`report-tab-btn${tab === t.id ? ' active' : ''}`}
            onClick={() => setTab(t.id)}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Boş dönem uyarısı */}
      {tasks.length === 0 && (
        <div className="rp-empty-state">
          <RPIcons.Search size={28} />
          <div>Seçili filtrelerde görev bulunamadı</div>
          <button className="btn btn-ghost btn-sm" onClick={() => { clearDates(); setProjectFilter('all'); }}>
            Filtreleri temizle
          </button>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════
          SEKME 1: GENEL
         ══════════════════════════════════════════════════════ */}
      {tasks.length > 0 && tab === 'genel' && (
        <>
          {/* Donut üçlüsü */}
          <div className="report-donut-row">
            <div className="card report-donut-card">
              <div className="report-card-title">Firma Bazlı Dağılım <span style={{ fontWeight: 400, fontSize: 10, color: 'var(--text-faint)' }}>· dilime tıkla, filtrele</span></div>
              <DonutChart segments={projectDonutData} centerVal={projects.length} centerLbl="firma"
                onSlice={id => setProjectFilter(id)} />
            </div>
            <div className="card report-donut-card">
              <div className="report-card-title">Durum Özeti</div>
              <DonutChart segments={statusDonutData} centerVal={`%${completionRate}`} centerLbl="tamamlandı" />
            </div>
            <div className="card report-donut-card">
              <div className="report-card-title">Öncelik Analizi</div>
              <DonutChart segments={prioDonutData} centerVal={tasks.length} centerLbl="görev" />
            </div>
          </div>

          {/* Verimlilik detay + son tamamlananlar */}
          <div className="report-grid">
            <div className="card report-card">
              <div className="report-card-title"><RPIcons.TrendingUp size={13} style={{ marginRight: 6 }} />Verimlilik Analizi</div>
              <div className="perf-score-display">
                <div className="perf-score-circle" style={{ '--perf-color': perfColor }}>
                  <svg viewBox="0 0 80 80">
                    <circle cx="40" cy="40" r="32" fill="none" stroke="var(--border)" strokeWidth="6" />
                    <circle cx="40" cy="40" r="32" fill="none" stroke={perfColor} strokeWidth="6"
                      strokeDasharray={`${2*Math.PI*32}`}
                      strokeDashoffset={`${2*Math.PI*32*(1-perfScore/100)}`}
                      strokeLinecap="round"
                      style={{ transform: 'rotate(-90deg)', transformOrigin: '40px 40px', transition: 'stroke-dashoffset .6s' }} />
                  </svg>
                  <div className="perf-score-val" style={{ color: perfColor }}>{perfScore}</div>
                </div>
                <div className="perf-breakdown">
                  <div className="perf-row">
                    <span>Tamamlanma</span>
                    <div className="perf-mini-bar"><div style={{ width: `${scoreCompletion/40*100}%`, background: '#3b82f6' }} /></div>
                    <span>{scoreCompletion}/40</span>
                  </div>
                  <div className="perf-row">
                    <span>Hız</span>
                    <div className="perf-mini-bar"><div style={{ width: `${scoreTime/30*100}%`, background: '#8b5cf6' }} /></div>
                    <span>{scoreTime}/30</span>
                  </div>
                  <div className="perf-row">
                    <span>Gecikme</span>
                    <div className="perf-mini-bar"><div style={{ width: `${scoreOverdue/30*100}%`, background: overdueCount > 0 ? '#f59e0b' : '#22c55e' }} /></div>
                    <span>{scoreOverdue}/30</span>
                  </div>
                  <div className="perf-label">{perfLabel}</div>
                </div>
              </div>
              {perfHistory.length >= 2 && (
                <div className="rp-sparkline-wrap">
                  <svg viewBox="0 0 120 28" className="rp-sparkline">
                    <polyline fill="none" stroke={perfColor} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
                      points={perfHistory.map((h, i) => `${(i / (perfHistory.length - 1)) * 116 + 2},${26 - (h.score / 100) * 24}`).join(' ')} />
                  </svg>
                  <span className="rp-sparkline-lbl">Skor trendi · son {perfHistory.length} hafta</span>
                </div>
              )}
            </div>

            <div className="card report-card">
              <div className="report-card-title">Son Tamamlananlar</div>
              {recentDone.length === 0 ? (
                <div className="report-empty">Henüz tamamlanan görev yok</div>
              ) : (
                <div className="report-recent-list">
                  {recentDone.map(t => {
                    const proj = projById[t.projectId];
                    return (
                      <button key={t.id} className="report-recent-item" onClick={() => onSelectTask(t.id)}>
                        <span className="project-dot" style={{ background: proj?.color || 'var(--text-faint)' }} />
                        <span className="report-recent-title">{t.title}</span>
                        <span className="report-recent-date">
                          {t.completedAt ? new Date(t.completedAt).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' }) : ''}
                        </span>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </>
      )}

      {/* ══════════════════════════════════════════════════════
          SEKME 2: GÖREVLER
         ══════════════════════════════════════════════════════ */}
      {tasks.length > 0 && tab === 'gorevler' && (
        <div className="report-grid">
          {/* Haftalık tamamlanma */}
          <div className="card report-card">
            <div className="report-card-title">Son 8 Hafta — Tamamlanan Görevler</div>
            <div className="report-bar-chart">
              {weeklyData.map((w, i) => (
                <div key={i} className="report-bar-col">
                  <div className="report-bar-wrap">
                    <div className="report-bar-fill" style={{ height: `${(w.count/maxWeekly)*100}%` }} title={`${w.count} görev`} />
                  </div>
                  <span className="report-bar-val">{w.count}</span>
                  <span className="report-bar-lbl">{w.label}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Burnup */}
          <div className="card report-card">
            <div className="report-card-title">
              <RPIcons.TrendingUp size={13} style={{ marginRight: 6 }} />
              Burnup — Eklenen vs Tamamlanan (8 hafta)
            </div>
            <BurnupChart tasks={tasks} />
            <div className="rp-forecast">
              {forecastWeeks !== null
                ? <>Mevcut hızla (~{weeklyRate.toFixed(1)} görev/hafta) aktif {activeCount} görev <strong>~{forecastWeeks} hafta</strong> içinde tamamlanır.</>
                : activeCount === 0
                  ? 'Aktif görev yok — her şey tamamlandı 🎉'
                  : 'Tahmin için son 4 haftada yeterli tamamlama verisi yok.'}
            </div>
          </div>

          {/* Gün × saat ısı haritası */}
          <div className="card report-card">
            <div className="report-card-title">Üretkenlik Isı Haritası — Gün × Saat</div>
            <HeatmapChart tasks={tasks} />
          </div>

          {/* Sprint velocity */}
          {completedSprints.length > 0 && (
            <div className="card report-card">
              <div className="report-card-title"><RPIcons.Zap size={13} style={{ marginRight: 6 }} />Sprint Hızı (Velocity)</div>
              <div className="report-bar-chart">
                {completedSprints.map(sp => (
                  <div key={sp.id} className="report-bar-col">
                    <div className="report-bar-wrap">
                      <div className="report-bar-fill" style={{ height: `${(sp.velocityPoints / maxVel) * 100}%` }}
                        title={`${sp.name || 'Sprint'}: ${sp.velocityPoints} puan`} />
                    </div>
                    <span className="report-bar-val">{sp.velocityPoints}</span>
                    <span className="report-bar-lbl">{(sp.name || 'Sprint').slice(0, 8)}</span>
                  </div>
                ))}
              </div>
              <div className="gecikme-footer">Ortalama {avgVel} puan / sprint</div>
            </div>
          )}

          {/* Gecikme dağılımı */}
          <div className="card report-card">
            <div className="report-card-title">
              <RPIcons.AlertCircle size={13} style={{ marginRight: 6, color: 'var(--p-high)' }} />
              Gecikme Dağılımı
            </div>
            <GecikmeDistribution tasks={tasks} />
          </div>

          {/* Öncelik */}
          <div className="card report-card">
            <div className="report-card-title">Öncelik Dağılımı</div>
            <div className="report-prio-bars">
              {[
                { key: 'high', label: 'Yüksek', color: 'var(--p-high)' },
                { key: 'medium', label: 'Orta', color: 'var(--p-med)' },
                { key: 'low', label: 'Düşük', color: 'var(--p-low)' },
              ].map(({ key, label, color }) => (
                <div key={key} className="report-hbar-row">
                  <span className="report-hbar-lbl">{label}</span>
                  <div className="report-hbar-track">
                    <div className="report-hbar-fill" style={{ width: `${(prioCounts[key]/prioTotal)*100}%`, background: color }} />
                  </div>
                  <span className="report-hbar-val">{prioCounts[key]}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Etiket × durum */}
          <div className="card report-card">
            <div className="report-card-title">Etiket Analizi — Durum Dağılımı</div>
            {tagStats.length === 0 ? (
              <div className="report-empty">Henüz etiket yok</div>
            ) : (
              <div className="report-hbars">
                {tagStats.map(r => (
                  <div key={r.tag.id} className="report-hbar-row">
                    <span className="report-hbar-lbl">{r.tag.name}</span>
                    <div className="report-hbar-track rp-tagstack"
                      title={`Tamamlanan ${r.doneC} · Aktif ${r.actC} · Gecikmiş ${r.overC}`}>
                      {r.doneC > 0 && <div className="report-hbar-fill" style={{ width: `${(r.doneC/maxTag)*100}%`, background: '#22c55e' }} />}
                      {r.actC  > 0 && <div className="report-hbar-fill" style={{ width: `${(r.actC /maxTag)*100}%`, background: '#3b82f6' }} />}
                      {r.overC > 0 && <div className="report-hbar-fill" style={{ width: `${(r.overC/maxTag)*100}%`, background: '#ef4444' }} />}
                    </div>
                    <span className="report-hbar-val">{r.doneC}/{r.count}</span>
                  </div>
                ))}
                <div className="rp-tagstack-legend">
                  <span><i style={{ background: '#22c55e' }} />Tamamlanan</span>
                  <span><i style={{ background: '#3b82f6' }} />Aktif</span>
                  <span><i style={{ background: '#ef4444' }} />Gecikmiş</span>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════════════════
          SEKME 3: FİRMALAR
         ══════════════════════════════════════════════════════ */}
      {tasks.length > 0 && tab === 'firmalar' && (
        <div className="report-grid">

          {/* Kârlılık — gerçek gelir ÷ harcanan süre = efektif saatlik kazanç */}
          {(() => {
            const inRange = (dstr) => {
              if (!dstr) return false;
              const d = new Date(dstr + 'T12:00:00');
              if (fromDate && d < fromDate) return false;
              if (toDate && d > toDate) return false;
              return true;
            };
            const rows = projects
              .filter(p => !p.archived && (projectFilter === 'all' || p.id === projectFilter))
              .map(p => {
                const revenue = (state.transactions || [])
                  .filter(tx => tx.projectId === p.id && tx.type === 'income' && (tx.status || 'done') === 'done')
                  .filter(tx => (!fromDate && !toDate) || inRange(tx.date))
                  .reduce((s, tx) => s + (tx.amount || 0), 0);
                const mins = allTasks.filter(t => t.projectId === p.id)
                  .reduce((s, t) => s + (t.timeLog || [])
                    .filter(e => (!fromDate && !toDate) || inRange(e.date))
                    .reduce((a, e) => a + (e.duration || 0), 0), 0);
                const effective = mins > 0 ? revenue / (mins / 60) : null;
                return { project: p, revenue, mins, effective, target: p.hourlyRate || null };
              })
              .filter(r => r.revenue > 0 || r.mins > 0)
              .sort((a, b) => (b.effective ?? -1) - (a.effective ?? -1));
            if (rows.length === 0) return null;
            const money = v => Math.round(v).toLocaleString('tr-TR') + ' ₺';
            const best = rows.find(r => r.effective !== null);
            return (
              <div className="card report-card report-card-wide">
                <div className="report-card-title">
                  <RPIcons.Wallet size={13} style={{ marginRight: 6 }} />
                  Kârlılık — Efektif Saatlik Kazanç
                </div>
                {best && (
                  <div className="profit-insight">
                    En kârlı: <strong>{best.project.name}</strong> · saatte {money(best.effective)}
                  </div>
                )}
                <div className="profit-table">
                  <div className="profit-row profit-row-head">
                    <span>Firma</span>
                    <span>Gelir</span>
                    <span>Süre</span>
                    <span>₺ / saat</span>
                    <span>Hedef</span>
                  </div>
                  {rows.map(r => {
                    const underTarget = r.effective !== null && r.target && r.effective < r.target;
                    return (
                      <div key={r.project.id} className="profit-row">
                        <span className="profit-name">
                          <span className="project-dot" style={{ background: r.project.color }} />
                          {r.project.name}
                        </span>
                        <span className="profit-num">{r.revenue > 0 ? money(r.revenue) : '—'}</span>
                        <span className="profit-num">{r.mins > 0 ? fmtTime(r.mins) : <em className="profit-hint">süre kaydı yok</em>}</span>
                        <span className={`profit-eff${underTarget ? ' under' : ''}`}>
                          {r.effective !== null ? money(r.effective) : '—'}
                        </span>
                        <span className="profit-num profit-target">
                          {r.target
                            ? <React.Fragment>{money(r.target)}{r.effective !== null && (underTarget ? ' ▼' : ' ▲')}</React.Fragment>
                            : '—'}
                        </span>
                      </div>
                    );
                  })}
                </div>
                <div className="profit-foot">Gelir: tahsil edilmiş işlemler · Süre: görevlere işlenen zaman kayıtları{(fromDate || toDate) ? ' · seçili dönem' : ''}</div>
              </div>
            );
          })()}

          {/* Firma durum dağılımı */}
          <div className="card report-card report-card-wide">
            <div className="report-card-title">Firma Bazlı Durum Dağılımı</div>
            {projectBreakdown.length === 0 ? (
              <div className="report-empty">Görev yok</div>
            ) : (
              <div className="report-project-bars">
                {projectBreakdown.map(({ project, total, byStatus, timeMin }) => (
                  <div key={project.id} className="report-proj-row">
                    <div className="report-proj-name">
                      <span className="project-dot" style={{ background: project.color }} />
                      <span>{project.name}</span>
                      <span className="report-proj-total">{total}</span>
                      {timeMin > 0 && <span style={{ fontSize: 11, color: 'var(--text-faint)', marginLeft: 'auto' }}>{fmtTime(timeMin)}</span>}
                    </div>
                    <div className="report-stacked-bar">
                      {RP_COLS.map(c => {
                        const w = byStatus[c.id] / total * 100;
                        if (!w) return null;
                        return <div key={c.id} className="report-stacked-seg" style={{ width: `${w}%`, background: c.color }}
                          title={`${c.label}: ${byStatus[c.id]}`} />;
                      })}
                    </div>
                    <div className="report-stacked-legend">
                      {RP_COLS.map(c => byStatus[c.id] > 0 && (
                        <span key={c.id} className="report-stacked-lbl">
                          <span style={{ background: c.color, width: 8, height: 8, borderRadius: 2, display: 'inline-block' }} />
                          {c.label} {byStatus[c.id]}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Firma bazlı süre */}
          {timeByProject.length > 0 && (
            <div className="card report-card">
              <div className="report-card-title"><RPIcons.Timer size={13} style={{ marginRight: 6 }} />Firma Bazlı Süre</div>
              <div className="report-hbars">
                {timeByProject.map(({ project, timeMin }) => (
                  <div key={project.id} className="report-hbar-row">
                    <span className="report-hbar-lbl">
                      <span className="project-dot" style={{ background: project.color }} />
                      {project.name}
                    </span>
                    <div className="report-hbar-track">
                      <div className="report-hbar-fill" style={{ width: `${(timeMin/maxTime)*100}%`, background: project.color }} />
                    </div>
                    <span className="report-hbar-val">{fmtTime(timeMin)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Bütçe & Karlılık */}
          {projectBreakdown.some(r => r.project.budget) && (
            <div className="card report-card report-card-wide">
              <div className="report-card-title"><RPIcons.TrendingUp size={13} style={{ marginRight: 6 }} />Bütçe & Karlılık</div>
              <div className="budget-table">
                {projectBreakdown.filter(r => r.project.budget).map(({ project, timeMin }) => {
                  const budget     = project.budget || 0;
                  const hourlyRate = project.hourlyRate || 0;
                  const spent      = hourlyRate ? Math.round((timeMin/60) * hourlyRate) : 0;
                  const pct        = budget ? Math.round((spent/budget)*100) : 0;
                  const over       = pct > 100;
                  return (
                    <div key={project.id} className="budget-row">
                      <span className="project-dot" style={{ background: project.color }} />
                      <span className="budget-proj-name">{project.name}</span>
                      <div className="budget-bar-wrap">
                        <div className="budget-bar-fill" style={{ width: `${Math.min(pct,100)}%`, background: over ? 'var(--p-high)' : project.color }} />
                      </div>
                      <span className={`budget-amount ${over ? 'over' : ''}`}>
                        {hourlyRate ? `${spent.toLocaleString('tr-TR')} / ${budget.toLocaleString('tr-TR')} ₺` : `${budget.toLocaleString('tr-TR')} ₺ bütçe`}
                      </span>
                      {over  && <span className="budget-over-badge">Aşıldı!</span>}
                      {!over && pct > 0 && <span className="budget-pct">{pct}%</span>}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* Gerçek kârlılık — finans verisiyle */}
          {profitRows.length > 0 && (
            <div className="card report-card report-card-wide">
              <div className="report-card-title"><RPIcons.Wallet size={13} style={{ marginRight: 6 }} />Gerçek Kârlılık — Finans Verisi</div>
              <div>
                <div className="rp-profit-row rp-profit-head">
                  <span className="rp-profit-name">Firma</span>
                  <span className="rp-profit-cell">Gelir</span>
                  <span className="rp-profit-cell">Gider</span>
                  <span className="rp-profit-cell">İşçilik</span>
                  <span className="rp-profit-net">Net</span>
                </div>
                {profitRows.map(r => (
                  <div key={r.project.id} className="rp-profit-row">
                    <span className="rp-profit-name">
                      <span className="project-dot" style={{ background: r.project.color }} />
                      {r.project.name}
                    </span>
                    <span className="rp-profit-cell inc">{r.income  ? `+${r.income.toLocaleString('tr-TR')} ₺`  : '—'}</span>
                    <span className="rp-profit-cell exp">{r.expense ? `−${r.expense.toLocaleString('tr-TR')} ₺` : '—'}</span>
                    <span className="rp-profit-cell lab">{r.laborCost ? `−${r.laborCost.toLocaleString('tr-TR')} ₺` : '—'}</span>
                    <span className="rp-profit-net" style={{ color: r.net >= 0 ? '#22c55e' : '#ef4444' }}>
                      {r.net >= 0 ? '+' : '−'}{Math.abs(r.net).toLocaleString('tr-TR')} ₺
                    </span>
                  </div>
                ))}
              </div>
              <div className="gecikme-footer">İşçilik = kaydedilen süre × firma saat ücreti · yalnızca gerçekleşen işlemler</div>
            </div>
          )}
        </div>
      )}

    </div>
  );
}

window.ReportView = ReportView;
