'use client'

import { useState } from 'react'
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip,
  ResponsiveContainer, Cell,
} from 'recharts'
import { Todo } from '@/lib/notion-pm'
import { KritischData } from '../page'

// ── MC CI ─────────────────────────────────────────────────────────────────────
const MC_BLUE   = '#3B82F6'
const MC_PURPLE = '#8B5CF6'

const KAT_COLOR: Record<string, string> = {
  'Kundenarbeit':         '#3B82F6',
  'Produkt & Launch':     '#8B5CF6',
  'Marketing & Content':  '#EC4899',
  'Vertrieb & Akquise':   '#F97316',
  'Technik & Tools':      '#6B7280',
  'Finanzen & Recht':     '#EAB308',
  'Organisation & Admin': '#A16207',
  'Privat':               '#22C55E',
  'Diana':                '#EF4444',
  'Me Time':              '#94A3B8',
}
function kc(k: string | null) { return k ? (KAT_COLOR[k] ?? MC_BLUE) : MC_BLUE }

// ── Capacity constants ────────────────────────────────────────────────────────
// Business: Mo–Fr 7h/Tag × 5 = 35h + WE Standard 5h = 40h/Woche
// Privat:   Mo–Fr 1.5h/Tag × 5 = 7.5h + WE 7h (3–4h/Tag) = 14.5h/Woche
const BUSINESS_CAP = 40
const PRIVAT_CAP   = 14.5
const REAL_CAP     = BUSINESS_CAP + PRIVAT_CAP  // 54.5h gesamt (für Machbarkeit)

const BUSINESS_KAT = new Set([
  'Kundenarbeit', 'Produkt & Launch', 'Marketing & Content',
  'Vertrieb & Akquise', 'Technik & Tools', 'Finanzen & Recht', 'Organisation & Admin',
])
const PRIVAT_KAT = new Set(['Privat', 'Diana', 'Me Time'])

// ── Helpers ───────────────────────────────────────────────────────────────────
const isErledigt = (t: Todo) => (t.status ?? '').toLowerCase().includes('erledigt')
const daysFromNow = (d: string) => {
  const now = new Date(); now.setHours(0,0,0,0)
  return Math.floor((new Date(d).getTime() - now.getTime()) / 86_400_000)
}
const round1 = (n: number) => Math.round(n * 10) / 10

// Wochenplan-Filter: Geplanter Tag muss in den nächsten 7 Tagen liegen.
// Kein Geplanter Tag aber Im Wochenplan = true → manuell gesetzt, zählt trotzdem.
const isThisWeek = (t: Todo) => {
  if (!t.geplanterTag) return t.imWochenplan
  const d = daysFromNow(t.geplanterTag)
  return d >= 0 && d <= 6
}

// ── Analytics ─────────────────────────────────────────────────────────────────

function kapazitaet(todos: Todo[]) {
  const week = todos.filter(t => isThisWeek(t) && !isErledigt(t))

  const businessH = round1(week.filter(t => BUSINESS_KAT.has(t.kategorie ?? '')).reduce((s,t) => s + (t.zeitH ?? 0), 0))
  const privatH   = round1(week.filter(t => PRIVAT_KAT.has(t.kategorie ?? '')).reduce((s,t) => s + (t.zeitH ?? 0), 0))

  const businessPct = Math.round((businessH / BUSINESS_CAP) * 100)
  const privatPct   = Math.round((privatH   / PRIVAT_CAP)   * 100)

  const bColor = businessPct <= 80 ? '#22C55E' : businessPct <= 100 ? '#EAB308' : '#EF4444'
  const pColor = privatPct   <= 80 ? '#22C55E' : privatPct   <= 100 ? '#EAB308' : '#EF4444'

  // legacy compat for other functions that use .geplant/.pct/.color/.label
  const geplant = round1(businessH + privatH)
  const pct     = Math.round((geplant / REAL_CAP) * 100)
  const color   = pct <= 80 ? '#22C55E' : pct <= 100 ? '#EAB308' : '#EF4444'
  const label   = pct <= 80 ? 'Im Rahmen' : pct <= 100 ? 'Grenzwertig' : 'Überlastet'

  return { businessH, privatH, businessPct, privatPct, bColor, pColor, geplant, pct, color, label }
}

function machbarkeit(todos: Todo[]) {
  const week = todos
    .filter(t => isThisWeek(t) && !isErledigt(t))
    .sort((a,b) => {
      // höchste Prio zuerst
      const prio = (x: Todo) => x.prioritaet === 'Hoch' ? 0 : x.prioritaet === 'Mittel' ? 1 : 2
      return prio(a) - prio(b)
    })

  let budget = REAL_CAP
  const machbar: Todo[] = []
  const overflow: Todo[] = []

  for (const t of week) {
    const h = t.zeitH ?? 0.5
    if (budget >= h) { machbar.push(t); budget -= h }
    else overflow.push(t)
  }

  const score = week.length === 0 ? 100
    : Math.round((machbar.length / week.length) * 100)

  return { machbar, overflow, score, restH: round1(budget) }
}

function energiebloecke(todos: Todo[]) {
  const open = todos.filter(t => !isErledigt(t) && isThisWeek(t))
  const fokus  = open.filter(t => (t.zeitH ?? 0) >= 2 || t.prioritaet === 'Hoch')
  const leicht = open.filter(t => !fokus.includes(t) && (t.zeitH ?? 1) < 1)
  const mittel = open.filter(t => !fokus.includes(t) && !leicht.includes(t))
  return { fokus, mittel, leicht }
}

function carryoverRate(todos: Todo[]) {
  // Todos mit vergangener Deadline die NICHT erledigt sind
  const withDeadline = todos.filter(t => t.deadline)
  const overdue = withDeadline.filter(t => !isErledigt(t) && daysFromNow(t.deadline!) < 0)
  const rate = withDeadline.length === 0 ? 0
    : Math.round((overdue.length / withDeadline.length) * 100)
  return { rate, overdueCount: overdue.length, total: withDeadline.length }
}

function deadlineRisiko(todos: Todo[]) {
  const projekte: Record<string, {riskCount: number; total: number}> = {}
  for (const t of todos.filter(t => !isErledigt(t))) {
    if (!projekte[t.projekt]) projekte[t.projekt] = { riskCount: 0, total: 0 }
    projekte[t.projekt].total++
    if (t.deadline) {
      const d = daysFromNow(t.deadline)
      if (d < 0 || d <= 7) projekte[t.projekt].riskCount++
    }
  }
  return Object.entries(projekte)
    .map(([p, v]) => ({
      projekt: p,
      risikoPct: v.total === 0 ? 0 : Math.round((v.riskCount / v.total) * 100),
      riskCount: v.riskCount,
    }))
    .filter(r => r.riskCount > 0)
    .sort((a,b) => b.risikoPct - a.risikoPct)
    .slice(0, 5)
}

interface AthenaEmpfehlung {
  icon: string
  text: string
  color: string
  items?: string[]  // aufklappbare Liste — eine Aufgabe pro Zeile
}

// Sortiert nach nächstem anstehendem Datum (geplanterTag → deadline → hinten)
function sortByNextDate(a: Todo, b: Todo): number {
  const dateOf = (t: Todo) => t.geplanterTag ?? t.deadline ?? null
  const da = dateOf(a), db = dateOf(b)
  if (da && db) return new Date(da).getTime() - new Date(db).getTime()
  if (da) return -1
  if (db) return 1
  return 0
}

function athenaEmpfehlungen(todos: Todo[]): AthenaEmpfehlung[] {
  const tips: AthenaEmpfehlung[] = []
  const kap = kapazitaet(todos)
  const mb  = machbarkeit(todos)
  const cr  = carryoverRate(todos)

  // 1. Überlastung
  if (kap.pct > 100) {
    const overflow = mb.overflow
    if (overflow.length > 0) {
      tips.push({
        icon: '↩',
        text: `${overflow.length} Todo${overflow.length > 1 ? 's' : ''} auf nächste Woche verschieben`,
        color: '#EF4444',
        items: overflow.map(t => `${t.name.slice(0,50)} (${t.zeitH ?? '?'}h)`),
      })
    }
  }

  // 2. Hohe Carry-over Rate
  if (cr.rate > 30) {
    tips.push({
      icon: '⚡',
      text: `Carry-over Rate ${cr.rate}% — ${cr.overdueCount} überfällige Todos priorisieren`,
      color: '#EAB308',
    })
  }

  // 3. Kundenarbeit unterrepräsentiert
  const weekH = (kat: string) => todos
    .filter(t => isThisWeek(t) && !isErledigt(t) && t.kategorie === kat)
    .reduce((s,t) => s + (t.zeitH ?? 0), 0)
  const kundenH = weekH('Kundenarbeit')
  const totalWeekH = todos.filter(t => isThisWeek(t) && !isErledigt(t))
    .reduce((s,t) => s + (t.zeitH ?? 0), 0)
  if (totalWeekH > 0 && kundenH / totalWeekH < 0.25) {
    tips.push({
      icon: '👥',
      text: `Kundenarbeit nur ${Math.round((kundenH/totalWeekH)*100)}% — prüfe ob Kunden-Todos fehlen`,
      color: MC_BLUE,
    })
  }

  // 4. Fokus-Todos ohne feste Zeit
  const fokusOhneZeit = todos.filter(t =>
    isThisWeek(t) && !isErledigt(t) && t.prioritaet === 'Hoch' && !t.zeitH
  )
  if (fokusOhneZeit.length > 0) {
    tips.push({
      icon: '🎯',
      text: `${fokusOhneZeit.length} Hoch-Prio Todos ohne Zeitschätzung`,
      color: MC_PURPLE,
      items: fokusOhneZeit.map(t => t.name.slice(0, 52)),
    })
  }

  // 5. Me Time fehlt
  const meTodos = todos.filter(t => !isErledigt(t) && t.kategorie === 'Me Time')
  if (meTodos.length === 0) {
    tips.push({
      icon: '🧘',
      text: `Me Time Zeitslot noch offen — bitte definieren`,
      color: '#94A3B8',
    })
  }

  // 6. Business-Puffer: nächstanstehende Todos vorschlagen
  const businessRest = round1(BUSINESS_CAP - kap.businessH)
  if (businessRest >= 1) {
    const kandidaten = todos
      .filter(t => !isErledigt(t) && !isThisWeek(t) && BUSINESS_KAT.has(t.kategorie ?? '') && (t.zeitH ?? 0) <= businessRest)
      .sort(sortByNextDate)
      .slice(0, 8)
    if (kandidaten.length > 0) {
      tips.push({
        icon: '➕',
        text: `Business: ${businessRest}h Puffer frei — nächstanstehende Vorschläge`,
        color: '#22C55E',
        items: kandidaten.map(t => {
          const datum = t.geplanterTag ?? t.deadline
          const datumStr = datum ? ` · ${datum.slice(5)}` : ''
          return `${t.name.slice(0,50)} (${t.zeitH ?? '?'}h${datumStr})`
        }),
      })
    }
  }

  // 7. Privat-Puffer: nächstanstehende Todos vorschlagen
  const privatRest = round1(PRIVAT_CAP - kap.privatH)
  if (privatRest >= 0.5) {
    const kandidaten = todos
      .filter(t => !isErledigt(t) && !isThisWeek(t) && PRIVAT_KAT.has(t.kategorie ?? '') && (t.zeitH ?? 0) <= privatRest)
      .sort(sortByNextDate)
      .slice(0, 6)
    if (kandidaten.length > 0) {
      tips.push({
        icon: '🏠',
        text: `Privat: ${privatRest}h Puffer frei — nächstanstehende Vorschläge`,
        color: '#8B5CF6',
        items: kandidaten.map(t => {
          const datum = t.geplanterTag ?? t.deadline
          const datumStr = datum ? ` · ${datum.slice(5)}` : ''
          return `${t.name.slice(0,50)} (${t.zeitH ?? '?'}h${datumStr})`
        }),
      })
    }
  }

  // 8. Alles gut
  if (tips.length === 0) {
    tips.push({ icon: '✓', text: `Alles im Rahmen — Kapazität ${kap.pct}%, Carry-over ${cr.rate}%. Weiter so!`, color: '#22C55E' })
  }

  return tips
}

function kategorienData(todos: Todo[]) {
  const map: Record<string, number> = {}
  for (const t of todos) {
    if (!t.kategorie || isErledigt(t)) continue
    map[t.kategorie] = (map[t.kategorie] ?? 0) + (t.zeitH ?? 0)
  }
  return Object.entries(map)
    .map(([name, stunden]) => ({ name, stunden: round1(stunden) }))
    .sort((a,b) => b.stunden - a.stunden)
}

function top5(todos: Todo[]) {
  return todos
    .filter(t => !isErledigt(t) && t.deadline)
    .sort((a,b) => new Date(a.deadline!).getTime() - new Date(b.deadline!).getTime())
    .slice(0, 5)
    .map(t => ({ ...t, daysLeft: daysFromNow(t.deadline!) }))
}

function fruehwarnung(todos: Todo[]) {
  const active = todos.filter(t => !isErledigt(t) && t.deadline)
  return {
    overdue:  active.filter(t => daysFromNow(t.deadline!) < 0),
    upcoming: active.filter(t => { const d = daysFromNow(t.deadline!); return d >= 0 && d <= 3 }),
  }
}

function zeitdifferenz(todos: Todo[]) {
  const map: Record<string, {geplant: number; tatsaechlich: number}> = {}
  for (const t of todos) {
    if (!map[t.projekt]) map[t.projekt] = { geplant: 0, tatsaechlich: 0 }
    map[t.projekt].geplant      += t.zeitH ?? 0
    map[t.projekt].tatsaechlich += t.tatsaechlicheZeitH ?? 0
  }
  return Object.entries(map)
    .map(([p, v]) => ({
      projekt: p,
      geplant: round1(v.geplant),
      tatsaechlich: round1(v.tatsaechlich),
      diff: round1(v.geplant - v.tatsaechlich),
    }))
    .filter(r => r.geplant > 0 || r.tatsaechlich > 0)
}

function meilensteinKetten(todos: Todo[]) {
  const map: Record<string, {projekt: string; todos: Todo[]; overdueCount: number}> = {}
  for (const t of todos.filter(t => !isErledigt(t) && t.meilenstein)) {
    const key = `${t.projekt} › ${t.meilenstein}`
    if (!map[key]) map[key] = { projekt: t.projekt, todos: [], overdueCount: 0 }
    map[key].todos.push(t)
    if (t.deadline && daysFromNow(t.deadline) < 0) map[key].overdueCount++
  }
  return Object.entries(map)
    .map(([label, v]) => ({ label, ...v }))
    .sort((a,b) => b.overdueCount - a.overdueCount)
    .slice(0, 6)
}

// ── UI Primitives ─────────────────────────────────────────────────────────────

function Card({ children, className }: { children: React.ReactNode; className?: string }) {
  return (
    <div className={className} style={{ background:'#1e293b', border:'1px solid #334155', borderRadius:'0.75rem', padding:'1.25rem' }}>
      {children}
    </div>
  )
}

function Label({ children }: { children: React.ReactNode }) {
  return (
    <p style={{ fontSize:'0.65rem', fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'#475569', marginBottom:'0.75rem', margin:'0 0 0.75rem' }}>
      {children}
    </p>
  )
}

function Badge({ color, children }: { color: string; children: React.ReactNode }) {
  return (
    <span style={{ background: color+'22', color, fontSize:'0.65rem', fontWeight:700, padding:'0.1rem 0.4rem', borderRadius:'0.25rem', letterSpacing:'0.05em' }}>
      {children}
    </span>
  )
}

// ── Section: Kapazität + Puffer ───────────────────────────────────────────────
function KapazitaetsAmpel({ todos }: { todos: Todo[] }) {
  const { businessH, privatH, businessPct, privatPct, bColor, pColor } = kapazitaet(todos)

  function Bar({ label, geplant, cap, pct, color, hint }: {
    label: string; geplant: number; cap: number; pct: number; color: string; hint: string
  }) {
    const barW = Math.min(pct, 100)
    const statusLabel = pct <= 80 ? 'Im Rahmen' : pct <= 100 ? 'Grenzwertig' : 'Überlastet'
    return (
      <div style={{ marginBottom:'0.875rem' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:'0.2rem' }}>
          <span style={{ fontSize:'0.68rem', fontWeight:700, color:'#475569', textTransform:'uppercase', letterSpacing:'0.08em' }}>{label}</span>
          <span style={{ fontSize:'0.65rem', color:'#475569' }}>{hint}</span>
        </div>
        <div style={{ display:'flex', alignItems:'baseline', gap:'0.4rem', marginBottom:'0.3rem' }}>
          <span style={{ fontSize:'1.75rem', fontWeight:800, color }}>{geplant}h</span>
          <span style={{ color:'#475569', fontSize:'0.8rem' }}>/ {cap}h</span>
        </div>
        <div style={{ background:'#0f172a', borderRadius:'9999px', height:'7px', marginBottom:'0.25rem', overflow:'hidden' }}>
          <div style={{ width:`${barW}%`, height:'100%', background:color, borderRadius:'9999px', transition:'width 0.5s ease' }} />
        </div>
        <div style={{ display:'flex', justifyContent:'space-between' }}>
          <span style={{ fontSize:'0.7rem', color, fontWeight:600 }}>{statusLabel} ({pct}%)</span>
          <Badge color={color}>{pct <= 80 ? '🟢' : pct <= 100 ? '🟡' : '🔴'}</Badge>
        </div>
      </div>
    )
  }

  return (
    <Card>
      <Label>Kapazität diese Woche</Label>
      <Bar label="Business" geplant={businessH} cap={BUSINESS_CAP} pct={businessPct} color={bColor} hint="Mo–Fr 35h + WE 5h" />
      <Bar label="Privat" geplant={privatH} cap={PRIVAT_CAP} pct={privatPct} color={pColor} hint="Mo–Fr 7.5h + WE 7h" />
      <div style={{ background:'#0f172a', borderRadius:'0.5rem', padding:'0.4rem 0.75rem', fontSize:'0.68rem', color:'#475569', marginTop:'0.25rem' }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:'0.2rem' }}>
          <span>Business (35h Mo–Fr + 5h WE)</span><span style={{ color:'#3B82F6' }}>{BUSINESS_CAP}h</span>
          <span>Privat (7.5h Mo–Fr + 7h WE)</span><span style={{ color:'#8B5CF6' }}>{PRIVAT_CAP}h</span>
          <span>3 Wochenendtage/Monat frei</span><span style={{ color:'#64748b' }}>blockiert</span>
        </div>
      </div>
    </Card>
  )
}

// ── Section: Machbarkeitsanalyse ──────────────────────────────────────────────
function Machbarkeit({ todos }: { todos: Todo[] }) {
  const { machbar, overflow, score } = machbarkeit(todos)
  const scoreColor = score >= 80 ? '#22C55E' : score >= 50 ? '#EAB308' : '#EF4444'
  const scoreLabel = score >= 80 ? 'Machbar' : score >= 50 ? 'Knapp' : 'Nicht machbar'

  return (
    <Card>
      <Label>Machbarkeitsanalyse</Label>
      <div style={{ display:'flex', alignItems:'center', gap:'1rem', marginBottom:'0.75rem' }}>
        <div style={{ textAlign:'center' }}>
          <div style={{ fontSize:'2rem', fontWeight:800, color:scoreColor }}>{score}%</div>
          <div style={{ fontSize:'0.7rem', color:scoreColor, fontWeight:600 }}>{scoreLabel}</div>
        </div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:'0.75rem', color:'#94a3b8', marginBottom:'0.25rem' }}>
            <span style={{ color:'#22C55E', fontWeight:600 }}>{machbar.length} Todos</span> passen rein
            {overflow.length > 0 && <span> · <span style={{ color:'#EF4444', fontWeight:600 }}>{overflow.length} fallen raus</span></span>}
          </div>
          <div style={{ background:'#0f172a', borderRadius:'9999px', height:'6px', overflow:'hidden' }}>
            <div style={{ width:`${score}%`, height:'100%', background:scoreColor }} />
          </div>
        </div>
      </div>

      {overflow.length > 0 && (
        <div>
          <p style={{ fontSize:'0.65rem', color:'#EF4444', fontWeight:700, marginBottom:'0.375rem', textTransform:'uppercase', letterSpacing:'0.05em' }}>
            Passt diese Woche nicht rein:
          </p>
          {overflow.slice(0, 4).map(t => (
            <div key={t.id} style={{ display:'flex', justifyContent:'space-between', background:'#0f172a', borderRadius:'0.375rem', padding:'0.3rem 0.5rem', marginBottom:'0.25rem', fontSize:'0.75rem' }}>
              <span style={{ color:'#f1f5f9' }}>{t.name.slice(0,42)}</span>
              <span style={{ color:'#EF4444', fontWeight:600, marginLeft:'0.5rem', whiteSpace:'nowrap' }}>{t.zeitH ?? '?'}h</span>
            </div>
          ))}
          {overflow.length > 4 && <p style={{ fontSize:'0.7rem', color:'#475569', marginTop:'0.25rem' }}>+{overflow.length-4} weitere…</p>}
        </div>
      )}
    </Card>
  )
}

// ── Section: ATHENA Empfehlungen ──────────────────────────────────────────────
function AthenaEmpfehlungen({ todos }: { todos: Todo[] }) {
  const tips = athenaEmpfehlungen(todos)
  const [expanded, setExpanded] = useState<Record<number, boolean>>({})
  const SHOW = 3

  return (
    <Card>
      <Label>ATHENA Empfehlungen</Label>
      <div style={{ display:'flex', flexDirection:'column', gap:'0.5rem' }}>
        {tips.map((tip, i) => {
          const hasItems = tip.items && tip.items.length > 0
          const isOpen = expanded[i] ?? false
          const visible = hasItems ? (isOpen ? tip.items! : tip.items!.slice(0, SHOW)) : []
          const hiddenCount = hasItems ? tip.items!.length - SHOW : 0

          return (
            <div key={i} style={{ borderLeft:`3px solid ${tip.color}`, background:'#0f172a', borderRadius:'0 0.375rem 0.375rem 0', padding:'0.5rem 0.625rem 0.5rem 0.75rem' }}>
              <div style={{ display:'flex', gap:'0.5rem', alignItems:'flex-start' }}>
                <span style={{ fontSize:'0.9rem', flexShrink:0 }}>{tip.icon}</span>
                <span style={{ fontSize:'0.78rem', color:'#cbd5e1', lineHeight:1.4, flex:1 }}>{tip.text}</span>
              </div>
              {hasItems && (
                <div style={{ marginTop:'0.375rem', paddingLeft:'1.5rem' }}>
                  {visible.map((item, j) => (
                    <div key={j} style={{ fontSize:'0.72rem', color:'#94a3b8', padding:'0.2rem 0', borderTop:'1px solid #1e293b', lineHeight:1.4 }}>
                      {item}
                    </div>
                  ))}
                  {hiddenCount > 0 && !isOpen && (
                    <button
                      onClick={() => setExpanded(e => ({ ...e, [i]: true }))}
                      style={{ fontSize:'0.68rem', color:tip.color, background:'none', border:'none', cursor:'pointer', padding:'0.2rem 0', marginTop:'0.1rem' }}
                    >
                      +{hiddenCount} weitere anzeigen
                    </button>
                  )}
                  {isOpen && tip.items!.length > SHOW && (
                    <button
                      onClick={() => setExpanded(e => ({ ...e, [i]: false }))}
                      style={{ fontSize:'0.68rem', color:'#475569', background:'none', border:'none', cursor:'pointer', padding:'0.2rem 0', marginTop:'0.1rem' }}
                    >
                      weniger anzeigen
                    </button>
                  )}
                </div>
              )}
            </div>
          )
        })}
      </div>
    </Card>
  )
}

// ── Section: Predictive Analytics ────────────────────────────────────────────
function PredictiveAnalytics({ todos }: { todos: Todo[] }) {
  const cr = carryoverRate(todos)
  const risks = deadlineRisiko(todos)
  const trend = cr.rate === 0 ? { label:'Kein Rückstand', color:'#22C55E', icon:'↗' }
    : cr.rate < 20 ? { label:'Stabil', color:'#22C55E', icon:'→' }
    : cr.rate < 40 ? { label:'Leichter Rückstand', color:'#EAB308', icon:'↘' }
    : { label:'Kritischer Rückstand', color:'#EF4444', icon:'↓' }

  return (
    <Card>
      <Label>Predictive Analytics</Label>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'0.75rem', marginBottom:'0.75rem' }}>
        {/* Carry-over Rate */}
        <div style={{ background:'#0f172a', borderRadius:'0.5rem', padding:'0.625rem' }}>
          <p style={{ fontSize:'0.65rem', color:'#475569', margin:'0 0 0.25rem', textTransform:'uppercase', letterSpacing:'0.05em' }}>Carry-over Rate</p>
          <p style={{ fontSize:'1.5rem', fontWeight:800, color: cr.rate === 0 ? '#22C55E' : cr.rate < 30 ? '#EAB308' : '#EF4444', margin:0 }}>{cr.rate}%</p>
          <p style={{ fontSize:'0.65rem', color:'#64748b', margin:'0.1rem 0 0' }}>{cr.overdueCount} / {cr.total} Todos überfällig</p>
        </div>
        {/* Trend */}
        <div style={{ background:'#0f172a', borderRadius:'0.5rem', padding:'0.625rem' }}>
          <p style={{ fontSize:'0.65rem', color:'#475569', margin:'0 0 0.25rem', textTransform:'uppercase', letterSpacing:'0.05em' }}>Trend</p>
          <p style={{ fontSize:'1.5rem', fontWeight:800, color:trend.color, margin:0 }}>{trend.icon}</p>
          <p style={{ fontSize:'0.65rem', color:trend.color, margin:'0.1rem 0 0', fontWeight:600 }}>{trend.label}</p>
        </div>
      </div>

      {/* Deadline-Risiko je Projekt */}
      {risks.length > 0 && (
        <>
          <p style={{ fontSize:'0.65rem', color:'#475569', textTransform:'uppercase', letterSpacing:'0.05em', margin:'0 0 0.375rem' }}>Deadline-Risiko je Projekt</p>
          {risks.map(r => (
            <div key={r.projekt} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', background:'#0f172a', borderRadius:'0.375rem', padding:'0.3rem 0.5rem', marginBottom:'0.25rem' }}>
              <span style={{ fontSize:'0.75rem', color:'#cbd5e1' }}>{r.projekt}</span>
              <div style={{ display:'flex', alignItems:'center', gap:'0.375rem' }}>
                <div style={{ background:'#334155', borderRadius:'9999px', width:'60px', height:'5px', overflow:'hidden' }}>
                  <div style={{ width:`${r.risikoPct}%`, height:'100%', background: r.risikoPct > 50 ? '#EF4444' : '#EAB308' }} />
                </div>
                <span style={{ fontSize:'0.7rem', color: r.risikoPct > 50 ? '#EF4444' : '#EAB308', fontWeight:700, width:'2.5rem', textAlign:'right' }}>{r.risikoPct}%</span>
              </div>
            </div>
          ))}
        </>
      )}
    </Card>
  )
}

// ── Section: Energieblöcke ────────────────────────────────────────────────────
function Energiebloecke({ todos }: { todos: Todo[] }) {
  const { fokus, mittel, leicht } = energiebloecke(todos)

  function Block({ label, color, items, hint }: { label:string; color:string; items:Todo[]; hint:string }) {
    return (
      <div style={{ flex:1 }}>
        <div style={{ display:'flex', alignItems:'center', gap:'0.375rem', marginBottom:'0.375rem' }}>
          <div style={{ width:'10px', height:'10px', borderRadius:'50%', background:color, flexShrink:0 }} />
          <span style={{ fontSize:'0.7rem', fontWeight:700, color, textTransform:'uppercase', letterSpacing:'0.08em' }}>{label}</span>
          <span style={{ fontSize:'0.65rem', color:'#475569' }}>({items.length})</span>
        </div>
        <div style={{ fontSize:'0.65rem', color:'#475569', marginBottom:'0.375rem' }}>{hint}</div>
        {items.slice(0,3).map(t => (
          <div key={t.id} style={{ background:'#0f172a', borderRadius:'0.375rem', padding:'0.25rem 0.5rem', marginBottom:'0.2rem', display:'flex', justifyContent:'space-between', gap:'0.5rem' }}>
            <span style={{ fontSize:'0.72rem', color:'#94a3b8' }}>{t.name.slice(0,32)}</span>
            <span style={{ fontSize:'0.65rem', color:'#475569', whiteSpace:'nowrap' }}>{t.zeitH ? `${t.zeitH}h` : '?h'}</span>
          </div>
        ))}
        {items.length > 3 && <p style={{ fontSize:'0.65rem', color:'#334155', margin:'0.2rem 0 0 0.5rem' }}>+{items.length-3} weitere</p>}
      </div>
    )
  }

  return (
    <Card>
      <Label>Energieblöcke (Wochenplan)</Label>
      <div style={{ display:'flex', gap:'0.75rem' }}>
        <Block label="Fokus" color="#EF4444" items={fokus} hint="≥2h · Hoch-Prio · morgens" />
        <Block label="Mittel" color="#EAB308" items={mittel} hint="1–2h · Mittel-Prio" />
        <Block label="Leicht" color="#22C55E" items={leicht} hint="<1h · flexibel" />
      </div>
    </Card>
  )
}

// ── Section: Abhängigkeits-Tracker ────────────────────────────────────────────
function AbhaengigkeitsTracker({ todos }: { todos: Todo[] }) {
  const ketten = meilensteinKetten(todos)
  return (
    <Card>
      <Label>Abhängigkeits-Tracker (Meilenstein-Ketten)</Label>
      {ketten.length === 0
        ? <p style={{ color:'#475569', fontSize:'0.875rem' }}>Keine offenen Meilensteine</p>
        : ketten.map(k => (
          <div key={k.label} style={{ marginBottom:'0.625rem' }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'0.25rem' }}>
              <span style={{ fontSize:'0.75rem', color:'#94a3b8', fontWeight:600 }}>{k.label}</span>
              {k.overdueCount > 0 && <Badge color="#EF4444">{k.overdueCount} überfällig</Badge>}
            </div>
            <div style={{ paddingLeft:'0.5rem', borderLeft:'2px solid #334155' }}>
              {k.todos.slice(0,3).map(t => (
                <div key={t.id} style={{ display:'flex', alignItems:'center', gap:'0.375rem', marginBottom:'0.2rem' }}>
                  <span style={{ width:'6px', height:'6px', borderRadius:'50%', background: t.deadline && daysFromNow(t.deadline) < 0 ? '#EF4444' : '#334155', flexShrink:0, display:'block' }} />
                  <span style={{ fontSize:'0.72rem', color:'#64748b' }}>{t.name.slice(0,44)}</span>
                </div>
              ))}
              {k.todos.length > 3 && <p style={{ fontSize:'0.65rem', color:'#334155', margin:'0.1rem 0 0 0.875rem' }}>+{k.todos.length-3} weitere</p>}
            </div>
          </div>
        ))
      }
    </Card>
  )
}

// ── Section: Kategorien-Chart ─────────────────────────────────────────────────
function KategorienChart({ todos }: { todos: Todo[] }) {
  const data = kategorienData(todos)
  return (
    <Card>
      <Label>Stunden je Kategorie (offen)</Label>
      {data.length === 0
        ? <p style={{ color:'#475569', fontSize:'0.875rem' }}>Keine Daten</p>
        : <ResponsiveContainer width="100%" height={240}>
            <BarChart data={data} margin={{ top:4, right:8, left:-16, bottom:60 }}>
              <CartesianGrid strokeDasharray="3 3" stroke="#0f172a" />
              <XAxis dataKey="name" tick={{ fontSize:9, fill:'#64748b' }} angle={-40} textAnchor="end" interval={0} />
              <YAxis tick={{ fontSize:9, fill:'#64748b' }} unit="h" />
              <Tooltip contentStyle={{ background:'#1e293b', border:'1px solid #334155', borderRadius:'0.5rem' }} labelStyle={{ color:'#f1f5f9', fontWeight:600 }} itemStyle={{ color:'#94a3b8' }} formatter={(v) => [`${v}h`, 'Stunden']} />
              <Bar dataKey="stunden" radius={[4,4,0,0]}>
                {data.map(e => <Cell key={e.name} fill={kc(e.name)} />)}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
      }
    </Card>
  )
}

// ── Section: Top 5 Deadlines ──────────────────────────────────────────────────
function Top5({ todos }: { todos: Todo[] }) {
  const items = top5(todos)
  function dl(days: number) {
    if (days < 0)  return { text:`${Math.abs(days)}d überfällig`, color:'#EF4444' }
    if (days === 0) return { text:'Heute',      color:'#EAB308' }
    if (days <= 3)  return { text:`in ${days}d`, color:'#EAB308' }
    return { text:`in ${days}d`, color:'#22C55E' }
  }
  return (
    <Card>
      <Label>Top 5 — nächste Deadlines</Label>
      {items.length === 0
        ? <p style={{ color:'#475569', fontSize:'0.875rem' }}>Keine offenen Todos mit Deadline</p>
        : items.map((t,i) => {
            const d = dl(t.daysLeft)
            return (
              <div key={t.id} style={{ display:'flex', gap:'0.625rem', background:'#0f172a', borderRadius:'0.5rem', padding:'0.5rem 0.625rem', marginBottom:'0.375rem' }}>
                <span style={{ fontSize:'0.7rem', fontWeight:700, color:'#475569', width:'1rem', flexShrink:0 }}>{i+1}.</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <p style={{ color:'#f1f5f9', fontSize:'0.78rem', fontWeight:600, margin:0, lineHeight:1.3 }}>{t.name.slice(0,48)}</p>
                  <p style={{ color:'#475569', fontSize:'0.7rem', margin:'0.15rem 0 0' }}>{t.projekt}{t.meilenstein ? ` · ${t.meilenstein}` : ''}</p>
                </div>
                <span style={{ fontSize:'0.7rem', fontWeight:700, color:d.color, flexShrink:0, whiteSpace:'nowrap' }}>{d.text}</span>
              </div>
            )
          })
      }
    </Card>
  )
}

// ── Section: Frühwarnsystem ───────────────────────────────────────────────────
function Fruehwarnsystem({ todos }: { todos: Todo[] }) {
  const { overdue, upcoming } = fruehwarnung(todos)
  const kap = kapazitaet(todos)
  const warnings = []
  if (overdue.length > 0)   warnings.push({ text:`${overdue.length} überfällige Todos`, color:'#EF4444' })
  if (upcoming.length > 0)  warnings.push({ text:`${upcoming.length} Todos fällig in ≤ 3 Tagen`, color:'#EAB308' })
  if (kap.pct > 100)        warnings.push({ text:`Überlastet: ${kap.pct}% der Kapazität`, color:'#EF4444' })
  else if (kap.pct > 80)    warnings.push({ text:`Grenzwertig: ${kap.pct}% der Kapazität`, color:'#EAB308' })

  return (
    <Card>
      <Label>Frühwarnsystem</Label>
      {warnings.length === 0
        ? <p style={{ color:'#22C55E', fontSize:'0.875rem' }}>✓ Alles im Rahmen</p>
        : <div style={{ display:'flex', flexDirection:'column', gap:'0.375rem', marginBottom:'0.75rem' }}>
            {warnings.map((w,i) => (
              <div key={i} style={{ borderLeft:`3px solid ${w.color}`, paddingLeft:'0.625rem', background:'#0f172a', borderRadius:'0 0.375rem 0.375rem 0', padding:'0.375rem 0.5rem 0.375rem 0.625rem', fontSize:'0.78rem', color:w.color }}>
                {w.text}
              </div>
            ))}
          </div>
      }
      {overdue.slice(0,3).map(t => (
        <p key={t.id} style={{ fontSize:'0.72rem', color:'#EF4444', margin:'0.1rem 0' }}>· {t.name.slice(0,46)} ({t.projekt})</p>
      ))}
    </Card>
  )
}

// ── Section: Diana ────────────────────────────────────────────────────────────
function DianaSection({ todos }: { todos: Todo[] }) {
  const diana = todos.filter(t => t.kategorie === 'Diana' && !isErledigt(t))
  if (diana.length === 0) return null
  return (
    <Card>
      <Label>Diana</Label>
      {diana.map(t => (
        <div key={t.id} style={{ display:'flex', justifyContent:'space-between', background:'#0f172a', borderRadius:'0.375rem', padding:'0.3rem 0.5rem', marginBottom:'0.25rem', fontSize:'0.75rem' }}>
          <span style={{ color:'#f1f5f9' }}>{t.name.slice(0,48)}</span>
          {t.deadline && <span style={{ color: daysFromNow(t.deadline) < 0 ? '#EF4444' : '#94a3b8', fontSize:'0.7rem', whiteSpace:'nowrap', marginLeft:'0.5rem' }}>{t.deadline.slice(5)}</span>}
        </div>
      ))}
    </Card>
  )
}

// ── Section: Me Time ──────────────────────────────────────────────────────────
function MeTime({ todos }: { todos: Todo[] }) {
  const meTodos = todos.filter(t => t.kategorie === 'Me Time' && !isErledigt(t))
  return (
    <Card>
      <Label>Me Time</Label>
      <div style={{ background:'#EAB30822', border:'1px solid #EAB30866', borderRadius:'0.5rem', padding:'0.625rem 0.75rem', marginBottom:'0.5rem' }}>
        <p style={{ fontSize:'0.85rem', fontWeight:700, color:'#EAB308', margin:'0 0 0.2rem' }}>⚠ Noch nicht definiert</p>
        <p style={{ fontSize:'0.7rem', color:'#92700a', margin:0 }}>Zeitslot für Me Time ist noch offen — bitte planen</p>
      </div>
      {meTodos.length === 0
        ? <p style={{ fontSize:'0.72rem', color:'#475569' }}>Keine Me-Time-Todos diese Woche</p>
        : <p style={{ fontSize:'0.72rem', color:'#22C55E' }}>{meTodos.length} Me-Time-Todos eingetragen</p>
      }
    </Card>
  )
}

// ── Section: Zeitdifferenz ────────────────────────────────────────────────────
function Zeitdifferenz({ todos }: { todos: Todo[] }) {
  const rows = zeitdifferenz(todos).sort((a,b) => Math.abs(b.diff) - Math.abs(a.diff))
  return (
    <Card>
      <Label>Zeitdifferenz je Projekt</Label>
      {rows.map(r => {
        const dc = r.diff >= 0 ? '#22C55E' : '#EF4444'
        const ds = r.diff >= 0 ? '+' : ''
        return (
          <div key={r.projekt} style={{ display:'grid', gridTemplateColumns:'1fr auto auto auto', gap:'0.5rem', alignItems:'center', background:'#0f172a', borderRadius:'0.375rem', padding:'0.3rem 0.5rem', marginBottom:'0.2rem', fontSize:'0.72rem' }}>
            <span style={{ color:'#cbd5e1', fontWeight:500 }}>{r.projekt}</span>
            <span style={{ color:'#475569' }}>{r.geplant}h</span>
            <span style={{ color:'#475569' }}>{r.tatsaechlich}h</span>
            <span style={{ color:dc, fontWeight:700, textAlign:'right' }}>{ds}{r.diff}h</span>
          </div>
        )
      })}
      <div style={{ display:'grid', gridTemplateColumns:'1fr auto auto auto', gap:'0.5rem', padding:'0.2rem 0.5rem', fontSize:'0.62rem', color:'#334155' }}>
        <span /><span>Geplant</span><span>Tatsächl.</span><span>Diff</span>
      </div>
    </Card>
  )
}

// ── Section: Kritische Stellen ────────────────────────────────────────────────
function KritischeStellen({ data }: { data: KritischData }) {
  const uhrzeit = new Date(data.stand).toLocaleString('de-DE', {
    day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit'
  })

  if (data.allesOk) {
    return (
      <div style={{ background:'#052e16', border:'1px solid #166534', borderRadius:'0.75rem', padding:'0.875rem 1.25rem', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <div style={{ display:'flex', alignItems:'center', gap:'0.625rem' }}>
          <span style={{ fontSize:'1rem' }}>✓</span>
          <span style={{ fontSize:'0.85rem', fontWeight:700, color:'#22C55E' }}>Alles im Rahmen — keine kritischen Stellen</span>
        </div>
        <span style={{ fontSize:'0.65rem', color:'#166534' }}>Stand: {uhrzeit} Uhr</span>
      </div>
    )
  }

  const farbenMap: Record<string, string> = { rot: '#EF4444', gelb: '#EAB308' }
  const typIcon: Record<string, string> = {
    ueberfallig: '🔴', deadline: '⚠', meilenstein: '🎯', kapazitaet: '📊'
  }

  return (
    <div style={{ background:'#1a0a0a', border:'1px solid #7f1d1d', borderRadius:'0.75rem', padding:'0.875rem 1.25rem' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'0.625rem' }}>
        <span style={{ fontSize:'0.72rem', fontWeight:700, letterSpacing:'0.1em', textTransform:'uppercase', color:'#EF4444' }}>
          Kritische Stellen ({data.kritisch.length})
        </span>
        <span style={{ fontSize:'0.65rem', color:'#7f1d1d' }}>Stand: {uhrzeit} Uhr</span>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:'0.375rem' }}>
        {data.kritisch.map((e, i) => {
          const color = farbenMap[e.farbe] ?? '#EF4444'
          return (
            <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:'0.625rem', background:'#0f172a', borderRadius:'0.375rem', padding:'0.4rem 0.625rem', borderLeft:`3px solid ${color}` }}>
              <span style={{ fontSize:'0.8rem', flexShrink:0 }}>{typIcon[e.typ] ?? '⚠'}</span>
              <div style={{ flex:1, minWidth:0 }}>
                <span style={{ fontSize:'0.72rem', color:'#94a3b8', fontWeight:600, marginRight:'0.375rem' }}>{e.projekt}</span>
                <span style={{ fontSize:'0.72rem', color:'#cbd5e1' }}>{e.text}</span>
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}

// ── Main ──────────────────────────────────────────────────────────────────────

export default function DashboardClient({ todos, fetchedAt, kritischData }: { todos: Todo[]; fetchedAt: string; kritischData: KritischData }) {
  const totalOpen = todos.filter(t => !isErledigt(t)).length
  const uhrzeit = new Date(fetchedAt).toLocaleTimeString('de-DE', { hour:'2-digit', minute:'2-digit' })

  return (
    <div style={{ minHeight:'100vh', background:'#0f172a', fontFamily:'var(--font-geist-sans, system-ui, sans-serif)', color:'#f1f5f9' }}>

      {/* Header */}
      <div style={{ background:`linear-gradient(135deg, ${MC_BLUE} 0%, ${MC_PURPLE} 100%)`, padding:'1.25rem 2rem' }}>
        <div style={{ maxWidth:'1400px', margin:'0 auto', display:'flex', justifyContent:'space-between', alignItems:'flex-end', flexWrap:'wrap', gap:'0.5rem' }}>
          <div>
            <h1 style={{ fontSize:'1.4rem', fontWeight:900, color:'#fff', margin:0, letterSpacing:'-0.02em' }}>ATHENA PM Dashboard</h1>
            <p style={{ color:'rgba(255,255,255,0.7)', fontSize:'0.75rem', margin:'0.2rem 0 0' }}>Market Compass · Live Notion PM</p>
          </div>
          <div style={{ textAlign:'right' }}>
            <p style={{ color:'rgba(255,255,255,0.6)', fontSize:'0.7rem', margin:0 }}>Aktualisiert: {uhrzeit} Uhr</p>
            <p style={{ color:'rgba(255,255,255,0.6)', fontSize:'0.7rem', margin:'0.1rem 0 0' }}>{totalOpen} offene Todos · 10 Projekte</p>
          </div>
        </div>
      </div>

      {/* Grid */}
      <div style={{ maxWidth:'1400px', margin:'0 auto', padding:'1.5rem 2rem', display:'flex', flexDirection:'column', gap:'1rem' }}>

        {/* Row 0: Kritische Stellen */}
        <KritischeStellen data={kritischData} />

        {/* Row 1: Kapazität + Machbarkeit + ATHENA Empfehlungen */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'1rem' }}>
          <KapazitaetsAmpel todos={todos} />
          <Machbarkeit todos={todos} />
          <AthenaEmpfehlungen todos={todos} />
        </div>

        {/* Row 2: Predictive Analytics + Energieblöcke + Me Time */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'1rem' }}>
          <PredictiveAnalytics todos={todos} />
          <Energiebloecke todos={todos} />
          <div style={{ display:'flex', flexDirection:'column', gap:'1rem' }}>
            <MeTime todos={todos} />
            <DianaSection todos={todos} />
          </div>
        </div>

        {/* Row 3: Kategorien-Chart + Top 5 */}
        <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:'1rem' }}>
          <KategorienChart todos={todos} />
          <Top5 todos={todos} />
        </div>

        {/* Row 4: Frühwarnsystem + Zeitdifferenz + Abhängigkeiten */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:'1rem' }}>
          <Fruehwarnsystem todos={todos} />
          <Zeitdifferenz todos={todos} />
          <AbhaengigkeitsTracker todos={todos} />
        </div>

      </div>
    </div>
  )
}
