// DIACARA Finanz-Cockpit
// React-Komponente: Einnahmen/Ausgaben, Unternehmerlohn (Privatentnahme), Gewinn vor/nach Entnahme,
// Steuer-Vorausschau (ESt + GewSt), monatliche Rücklage-Empfehlung, Kategorien-Analyse
//
// Modul 4 der team.diacara.com Plattform-Vision
// Wichtig: Übersichtstool, KEINE Buchhaltung. Offizielle Buchführung läuft über DATEV / Steuerberater.
//
// Quelle: Claude.ai Artefakt von Diana, gesichert 2026-05-13

import { useState, useEffect, useMemo } from "react";

const C = {
  red: "#E51932", redLight: "#FFF0F2",
  blue: "#0081C2", blueLight: "#E8F4FA",
  dark: "#16192B", darkCard: "#1E2139",
  g50: "#FAFBFC", g100: "#F3F4F7", g200: "#E5E7ED", g300: "#CDD1DB", g400: "#969BB0", g500: "#6B7084", g700: "#3A3E52",
  white: "#FFFFFF",
  green: "#10B981", greenLight: "#ECFDF5", greenDark: "#059669",
  amber: "#F59E0B", amberLight: "#FFFBEB", amberDark: "#D97706",
  violet: "#7C3AED", violetLight: "#F3EEFF",
  urgent: "#EF4444",
};

const EXPENSE_CATEGORIES = [
  { id: "gehalt", label: "Gehälter & Löhne", icon: "👥", color: "#6366F1" },
  { id: "lohnnebenkosten", label: "Lohnnebenkosten", icon: "📊", color: "#8B5CF6" },
  { id: "freelancer", label: "Freie Mitarbeiter / Honorare", icon: "🤝", color: "#A78BFA" },
  { id: "fahrzeuge", label: "Fahrzeuge (Leasing, Tanken, Reparatur)", icon: "🚗", color: C.blue },
  { id: "versicherung_kfz", label: "KFZ-Versicherung", icon: "🛡", color: "#0EA5E9" },
  { id: "buero_miete", label: "Büromiete & Nebenkosten", icon: "🏢", color: C.amber },
  { id: "buero_material", label: "Büromaterial & Papier", icon: "📎", color: "#F97316" },
  { id: "getraenke", label: "Getränke & Verpflegung", icon: "☕", color: "#FB923C" },
  { id: "telefon_it", label: "Telefon, Internet & IT", icon: "📱", color: "#14B8A6" },
  { id: "software", label: "Software & Lizenzen", icon: "💻", color: "#06B6D4" },
  { id: "versicherung", label: "Versicherungen (Betrieb)", icon: "🛡", color: "#64748B" },
  { id: "steuerberater", label: "Steuerberater & Beratung", icon: "📋", color: "#78716C" },
  { id: "fortbildung", label: "Fortbildungen & Schulungen", icon: "📚", color: C.violet },
  { id: "marketing", label: "Marketing & Werbung", icon: "📢", color: C.red },
  { id: "patienten", label: "Patientengeschenke & Geburtstage", icon: "🎂", color: "#EC4899" },
  { id: "sonstiges", label: "Sonstiges", icon: "📦", color: C.g500 },
];

const OWNER_CATEGORY = { id: "unternehmerlohn", label: "Unternehmerlohn (Privatentnahme)", icon: "👩‍💼", color: "#BE185D" };

const INCOME_CATEGORIES = [
  { id: "sgb_xi", label: "SGB XI (Pflegeversicherung)", icon: "🏥", color: C.green },
  { id: "sgb_v", label: "SGB V (Krankenversicherung)", icon: "💚", color: "#34D399" },
  { id: "privat", label: "Privatzahler", icon: "👤", color: "#6EE7B7" },
  { id: "beratung", label: "Beratung §37.3 / §45", icon: "💬", color: "#059669" },
  { id: "sonstige_ein", label: "Sonstige Einnahmen", icon: "📥", color: C.blue },
];

const MONTHS = ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];

// Demo data
function generateDemoData() {
  const entries = [];
  let id = 1;
  for (let m = 0; m < 3; m++) {
    const month = `2026-${String(m + 1).padStart(2, "0")}`;
    // Income
    entries.push({ id: id++, type: "income", category: "sgb_xi", amount: 85000 + Math.round(Math.random() * 10000), date: `${month}-05`, note: "Pflegekassen-Abrechnung" });
    entries.push({ id: id++, type: "income", category: "sgb_v", amount: 32000 + Math.round(Math.random() * 5000), date: `${month}-05`, note: "KV-Abrechnung" });
    entries.push({ id: id++, type: "income", category: "privat", amount: 4500 + Math.round(Math.random() * 2000), date: `${month}-10`, note: "Privatzahler" });
    entries.push({ id: id++, type: "income", category: "beratung", amount: 2800 + Math.round(Math.random() * 800), date: `${month}-15`, note: "Beratungseinsätze" });
    // Expenses
    entries.push({ id: id++, type: "expense", category: "gehalt", amount: 52000 + Math.round(Math.random() * 3000), date: `${month}-28`, note: "Gehälter Team" });
    entries.push({ id: id++, type: "expense", category: "lohnnebenkosten", amount: 14500 + Math.round(Math.random() * 1000), date: `${month}-28`, note: "AG-Anteile SV" });
    entries.push({ id: id++, type: "expense", category: "freelancer", amount: 8200 + Math.round(Math.random() * 2000), date: `${month}-25`, note: "Freie Pflegekräfte" });
    entries.push({ id: id++, type: "expense", category: "fahrzeuge", amount: 6800 + Math.round(Math.random() * 1500), date: `${month}-15`, note: "Leasing + Tanken" });
    entries.push({ id: id++, type: "expense", category: "versicherung_kfz", amount: 1800, date: `${month}-01`, note: "KFZ-Versicherung Flotte" });
    entries.push({ id: id++, type: "expense", category: "buero_miete", amount: 2200, date: `${month}-01`, note: "Miete Fahrenberg" });
    entries.push({ id: id++, type: "expense", category: "buero_material", amount: 280 + Math.round(Math.random() * 150), date: `${month}-12`, note: "Papier, Toner, etc." });
    entries.push({ id: id++, type: "expense", category: "getraenke", amount: 120 + Math.round(Math.random() * 80), date: `${month}-10`, note: "Getränke Büro" });
    entries.push({ id: id++, type: "expense", category: "telefon_it", amount: 890, date: `${month}-01`, note: "Webex, Internet, Handys" });
    entries.push({ id: id++, type: "expense", category: "software", amount: 650, date: `${month}-01`, note: "CuraSoft, M365, Alfima, etc." });
    entries.push({ id: id++, type: "expense", category: "versicherung", amount: 580, date: `${month}-01`, note: "Betriebshaftpflicht etc." });
    entries.push({ id: id++, type: "expense", category: "steuerberater", amount: 850, date: `${month}-20`, note: "Monatl. Buchhaltung" });
    entries.push({ id: id++, type: "expense", category: "marketing", amount: 350 + Math.round(Math.random() * 300), date: `${month}-08`, note: "FB Ads, Canva Pro" });
    entries.push({ id: id++, type: "expense", category: "patienten", amount: 150 + Math.round(Math.random() * 100), date: `${month}-18`, note: "Geburtstagskarten, Blumen" });
    entries.push({ id: id++, type: "expense", category: "unternehmerlohn", amount: 800000, date: `${month}-01`, note: "Privatentnahme Diana" });
  }
  return entries;
}

const DEMO_ENTRIES = generateDemoData();

const fmt = (n) => new Intl.NumberFormat("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(n / 100);
const fmtK = (n) => {
  const abs = Math.abs(n);
  if (abs >= 100000) return (n / 100000).toFixed(1) + "k";
  return fmt(n);
};
const fmtShort = (n) => new Intl.NumberFormat("de-DE", { minimumFractionDigits: 0, maximumFractionDigits: 0 }).format(n / 100);

// ─── UI ─────────────────────────────────────────────────────────────

const Card = ({ children, style }) => (
  <div style={{ background: C.white, borderRadius: 14, border: `1px solid ${C.g200}`, padding: 22, boxShadow: "0 1px 3px rgba(0,0,0,0.03)", ...style }}>{children}</div>
);

const Badge = ({ children, color, bg }) => (
  <span style={{ display: "inline-flex", alignItems: "center", padding: "3px 10px", borderRadius: 20, fontSize: 11, fontWeight: 600, color: color || C.g700, background: bg || C.g100 }}>{children}</span>
);

const ProgressBar = ({ value, max, color, h = 8 }) => (
  <div style={{ width: "100%", height: h, borderRadius: h, background: C.g200, overflow: "hidden" }}>
    <div style={{ width: `${Math.min(100, (value / max) * 100)}%`, height: "100%", borderRadius: h, background: color, transition: "width 0.5s" }} />
  </div>
);

// ─── PAGES ──────────────────────────────────────────────────────────

function DashboardPage({ entries, selectedMonth, setSelectedMonth }) {
  const monthEntries = useMemo(() => {
    if (selectedMonth === "alle") return entries;
    return entries.filter(e => e.date.startsWith(selectedMonth));
  }, [entries, selectedMonth]);

  const totalIncome = monthEntries.filter(e => e.type === "income").reduce((s, e) => s + e.amount, 0);
  const totalExpenseAll = monthEntries.filter(e => e.type === "expense").reduce((s, e) => s + e.amount, 0);
  const ownerDraw = monthEntries.filter(e => e.type === "expense" && e.category === "unternehmerlohn").reduce((s, e) => s + e.amount, 0);
  const totalExpense = totalExpenseAll - ownerDraw; // Betriebsausgaben OHNE Unternehmerlohn
  const profitBeforeOwner = totalIncome - totalExpense;
  const profit = profitBeforeOwner - ownerDraw; // Was wirklich übrig bleibt
  const margin = totalIncome > 0 ? (profitBeforeOwner / totalIncome) * 100 : 0;

  // Tax estimate (Einzelunternehmen: ESt + Soli + GewSt)
  // Steuer wird auf den Gewinn VOR Privatentnahme berechnet!
  const yearProfit = selectedMonth === "alle" ? profitBeforeOwner : profitBeforeOwner * (12 / 3);
  const estIncome = Math.max(0, yearProfit);
  // Simplified progressive tax estimate
  const calcTax = (annual) => {
    const a = annual / 100;
    if (a <= 11604) return 0;
    if (a <= 62809) return Math.round(a * 0.30) * 100; // ~30% avg
    return Math.round(a * 0.38) * 100; // ~38% avg higher bracket
  };
  const estTax = calcTax(estIncome);
  const gewerbesteuer = Math.max(0, Math.round((estIncome / 100 - 24500) * 0.14)) * 100; // Freibetrag 24.500, ~14% Hebesatz
  const totalTaxYear = estTax + gewerbesteuer;
  const monthlyReserve = Math.round(totalTaxYear / 12);

  // Category breakdown
  const expenseByCategory = [...EXPENSE_CATEGORIES, OWNER_CATEGORY].map(cat => ({
    ...cat,
    total: monthEntries.filter(e => e.type === "expense" && e.category === cat.id).reduce((s, e) => s + e.amount, 0),
  })).filter(c => c.total > 0).sort((a, b) => b.total - a.total);

  const incomeByCategory = INCOME_CATEGORIES.map(cat => ({
    ...cat,
    total: monthEntries.filter(e => e.type === "income" && e.category === cat.id).reduce((s, e) => s + e.amount, 0),
  })).filter(c => c.total > 0).sort((a, b) => b.total - a.total);

  const maxExpense = expenseByCategory[0]?.total || 1;

  // Monthly trend
  const monthlyTrend = ["2026-01", "2026-02", "2026-03"].map(m => {
    const me = entries.filter(e => e.date.startsWith(m));
    const inc = me.filter(e => e.type === "income").reduce((s, e) => s + e.amount, 0);
    const exp = me.filter(e => e.type === "expense").reduce((s, e) => s + e.amount, 0);
    return { month: m, income: inc, expense: exp, profit: inc - exp };
  });
  const maxTrend = Math.max(...monthlyTrend.map(t => Math.max(t.income, t.expense)));

  const isAll = selectedMonth === "alle";
  const periodLabel = isAll ? "Q1 2026 (Jan–Mär)" : MONTHS[parseInt(selectedMonth.split("-")[1]) - 1] + " 2026";

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 22 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 800, color: C.dark, margin: 0 }}>Finanz-Cockpit</h1>
          <p style={{ color: C.g500, margin: "4px 0 0", fontSize: 13 }}>DIACARA Ambulanter Pflegedienst · Einzelunternehmen</p>
        </div>
        <div style={{ display: "flex", gap: 4, padding: 3, background: C.g100, borderRadius: 10 }}>
          {[
            { id: "alle", label: "Q1 Gesamt" },
            { id: "2026-01", label: "Jan" },
            { id: "2026-02", label: "Feb" },
            { id: "2026-03", label: "Mär" },
          ].map(m => (
            <button key={m.id} onClick={() => setSelectedMonth(m.id)} style={{
              padding: "7px 14px", borderRadius: 8, border: "none", cursor: "pointer",
              background: selectedMonth === m.id ? C.white : "transparent",
              boxShadow: selectedMonth === m.id ? "0 1px 4px rgba(0,0,0,0.08)" : "none",
              color: selectedMonth === m.id ? C.dark : C.g400, fontSize: 12, fontWeight: 600, fontFamily: "inherit",
            }}>{m.label}</button>
          ))}
        </div>
      </div>

      {/* KPI Cards Row 1 */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 12 }}>
        <Card style={{ background: `linear-gradient(135deg, ${C.greenLight}, ${C.white})`, borderColor: `${C.green}30` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>EINNAHMEN</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: C.greenDark, marginTop: 4 }}>{fmt(totalIncome)} €</div>
          <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>{periodLabel}</div>
        </Card>
        <Card style={{ background: `linear-gradient(135deg, ${C.redLight}, ${C.white})`, borderColor: `${C.red}30` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>BETRIEBSAUSGABEN</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: C.red, marginTop: 4 }}>{fmt(totalExpense)} €</div>
          <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>ohne Unternehmerlohn</div>
        </Card>
        <Card style={{ background: `linear-gradient(135deg, ${C.blueLight}, ${C.white})`, borderColor: `${C.blue}30` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>GEWINN (vor Entnahme & Steuer)</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: C.blue, marginTop: 4 }}>{fmt(profitBeforeOwner)} €</div>
          <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>Marge: {margin.toFixed(1)}%</div>
        </Card>
      </div>

      {/* KPI Cards Row 2 */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, marginBottom: 20 }}>
        <Card style={{ background: `linear-gradient(135deg, #FDF2F8, ${C.white})`, borderColor: "#BE185D30" }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>👩‍💼 DEIN UNTERNEHMERLOHN</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: "#BE185D", marginTop: 4 }}>{fmt(ownerDraw)} €</div>
          <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>Privatentnahme {periodLabel}</div>
        </Card>
        <Card style={{ background: `linear-gradient(135deg, ${C.violetLight}, ${C.white})`, borderColor: `${C.violet}30` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>STEUER-RÜCKLAGE / Monat</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: C.violet, marginTop: 4 }}>{fmt(monthlyReserve)} €</div>
          <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>Geschätzt (ESt + GewSt)</div>
        </Card>
        <Card style={{ background: `linear-gradient(135deg, ${profit > 0 ? C.amberLight : "#FEF2F2"}, ${C.white})`, borderColor: `${profit > 0 ? C.amber : C.urgent}30` }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>VERBLEIBEND (nach allem)</div>
          <div style={{ fontSize: 26, fontWeight: 900, color: profit > 0 ? C.amberDark : C.urgent, marginTop: 4 }}>{fmt(profit)} €</div>
          <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>Einnahmen − Ausgaben − Lohn − Steuer</div>
        </Card>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 18 }}>
        {/* Expense breakdown */}
        <Card>
          <h3 style={{ fontSize: 14, fontWeight: 700, color: C.dark, margin: "0 0 14px" }}>📊 Ausgaben nach Kategorie</h3>
          {expenseByCategory.map(cat => (
            <div key={cat.id} style={{ marginBottom: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{ fontSize: 14 }}>{cat.icon}</span>
                  <span style={{ fontSize: 12, fontWeight: 500, color: C.g700 }}>{cat.label}</span>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 12, fontWeight: 700, color: C.dark }}>{fmt(cat.total)} €</span>
                  <span style={{ fontSize: 10, color: C.g400, minWidth: 32, textAlign: "right" }}>{(cat.total / totalExpense * 100).toFixed(0)}%</span>
                </div>
              </div>
              <ProgressBar value={cat.total} max={maxExpense} color={cat.color} h={5} />
            </div>
          ))}
        </Card>

        {/* Income breakdown */}
        <Card>
          <h3 style={{ fontSize: 14, fontWeight: 700, color: C.dark, margin: "0 0 14px" }}>💰 Einnahmen nach Quelle</h3>
          {incomeByCategory.map(cat => (
            <div key={cat.id} style={{ marginBottom: 14 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 4 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                  <span style={{ fontSize: 14 }}>{cat.icon}</span>
                  <span style={{ fontSize: 12, fontWeight: 500, color: C.g700 }}>{cat.label}</span>
                </div>
                <span style={{ fontSize: 12, fontWeight: 700, color: C.dark }}>{fmt(cat.total)} €</span>
              </div>
              <ProgressBar value={cat.total} max={totalIncome} color={cat.color} h={5} />
            </div>
          ))}

          <div style={{ marginTop: 20, padding: "14px 16px", borderRadius: 10, background: C.g50, border: `1px solid ${C.g200}` }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: C.dark, marginBottom: 8 }}>📐 Einnahmen-Mix</div>
            <div style={{ display: "flex", height: 16, borderRadius: 8, overflow: "hidden" }}>
              {incomeByCategory.map(cat => (
                <div key={cat.id} style={{ width: `${(cat.total / totalIncome) * 100}%`, background: cat.color, height: "100%" }} title={`${cat.label}: ${(cat.total / totalIncome * 100).toFixed(0)}%`} />
              ))}
            </div>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 8 }}>
              {incomeByCategory.map(cat => (
                <div key={cat.id} style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 10, color: C.g500 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: cat.color, display: "inline-block" }} />
                  {cat.label} ({(cat.total / totalIncome * 100).toFixed(0)}%)
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {/* Monthly trend */}
        <Card>
          <h3 style={{ fontSize: 14, fontWeight: 700, color: C.dark, margin: "0 0 14px" }}>📈 Monatlicher Verlauf</h3>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 16, height: 150, padding: "0 10px" }}>
            {monthlyTrend.map(t => {
              const mLabel = MONTHS[parseInt(t.month.split("-")[1]) - 1];
              return (
                <div key={t.month} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                  <div style={{ display: "flex", gap: 3, alignItems: "flex-end", height: 110 }}>
                    <div style={{ width: 18, height: `${(t.income / maxTrend) * 100}%`, background: C.green, borderRadius: "4px 4px 0 0", minHeight: 4 }} title={`Einnahmen: ${fmt(t.income)} €`} />
                    <div style={{ width: 18, height: `${(t.expense / maxTrend) * 100}%`, background: C.red, borderRadius: "4px 4px 0 0", minHeight: 4 }} title={`Ausgaben: ${fmt(t.expense)} €`} />
                  </div>
                  <span style={{ fontSize: 11, fontWeight: 600, color: C.g500 }}>{mLabel}</span>
                  <span style={{ fontSize: 10, fontWeight: 700, color: t.profit > 0 ? C.greenDark : C.urgent }}>+{fmtShort(t.profit)} €</span>
                </div>
              );
            })}
          </div>
          <div style={{ display: "flex", gap: 16, justifyContent: "center", marginTop: 10 }}>
            <span style={{ fontSize: 11, color: C.g400 }}><span style={{ display: "inline-block", width: 10, height: 10, borderRadius: 2, background: C.green, marginRight: 4 }} />Einnahmen</span>
            <span style={{ fontSize: 11, color: C.g400 }}><span style={{ display: "inline-block", width: 10, height: 10, borderRadius: 2, background: C.red, marginRight: 4 }} />Ausgaben</span>
          </div>
        </Card>

        {/* Tax planning */}
        <Card style={{ background: C.dark, border: "none" }}>
          <h3 style={{ fontSize: 14, fontWeight: 700, color: C.white, margin: "0 0 4px" }}>🏦 Steuer-Vorausschau 2026</h3>
          <p style={{ fontSize: 11, color: C.g400, margin: "0 0 16px" }}>Geschätzte Werte basierend auf bisherigem Verlauf · Einzelunternehmen</p>

          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              { label: "Hochgerechneter Jahresgewinn", value: fmt(yearProfit), color: C.blue },
              { label: "Geschätzte Einkommensteuer", value: fmt(estTax), color: C.amber },
              { label: "Geschätzte Gewerbesteuer", value: fmt(Math.max(0, gewerbesteuer)), color: C.amber, note: "Freibetrag 24.500 €" },
              { label: "Solidaritätszuschlag", value: "entfällt (< Grenze)", color: C.g400, noAmount: true },
            ].map(r => (
              <div key={r.label} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 12px", borderRadius: 8, background: "rgba(255,255,255,0.04)" }}>
                <div>
                  <span style={{ fontSize: 12, color: C.g400 }}>{r.label}</span>
                  {r.note && <span style={{ fontSize: 10, color: C.g500, marginLeft: 6 }}>({r.note})</span>}
                </div>
                <span style={{ fontSize: 14, fontWeight: 700, color: r.color }}>{r.noAmount ? r.value : `${r.value} €`}</span>
              </div>
            ))}
          </div>

          <div style={{ marginTop: 16, padding: "14px 16px", borderRadius: 10, background: `${C.violet}20`, border: `1px solid ${C.violet}40` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 700, color: C.white }}>💡 Monatlich zurücklegen</div>
                <div style={{ fontSize: 11, color: C.g400, marginTop: 2 }}>Damit am Jahresende keine Überraschung kommt</div>
              </div>
              <div style={{ fontSize: 28, fontWeight: 900, color: C.violet }}>{fmt(monthlyReserve)} €</div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
}

function BuchungenPage({ entries, setEntries }) {
  const [showForm, setShowForm] = useState(false);
  const [formType, setFormType] = useState("expense");
  const [formCat, setFormCat] = useState("");
  const [formAmount, setFormAmount] = useState("");
  const [formDate, setFormDate] = useState("2026-03-21");
  const [formNote, setFormNote] = useState("");
  const [filter, setFilter] = useState("alle");

  const categories = formType === "income" ? INCOME_CATEGORIES : [...EXPENSE_CATEGORIES, OWNER_CATEGORY];
  const filtered = filter === "alle" ? entries : entries.filter(e => e.type === filter);
  const sorted = [...filtered].sort((a, b) => b.date.localeCompare(a.date));

  const handleAdd = () => {
    if (!formCat || !formAmount) return;
    const newEntry = {
      id: entries.length + 1,
      type: formType,
      category: formCat,
      amount: Math.round(parseFloat(formAmount.replace(",", ".")) * 100),
      date: formDate,
      note: formNote,
    };
    setEntries(prev => [...prev, newEntry]);
    setShowForm(false);
    setFormAmount("");
    setFormNote("");
    setFormCat("");
  };

  const getCatInfo = (entry) => {
    const cats = entry.type === "income" ? INCOME_CATEGORIES : [...EXPENSE_CATEGORIES, OWNER_CATEGORY];
    return cats.find(c => c.id === entry.category) || { icon: "📦", label: entry.category, color: C.g400 };
  };

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 22 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 800, color: C.dark, margin: 0 }}>Buchungen</h1>
          <p style={{ color: C.g500, margin: "4px 0 0", fontSize: 13 }}>Einnahmen und Ausgaben erfassen</p>
        </div>
        <button onClick={() => setShowForm(!showForm)} style={{
          padding: "10px 20px", borderRadius: 10, border: "none",
          background: C.red, color: C.white, fontSize: 13, fontWeight: 700,
          cursor: "pointer", fontFamily: "inherit",
        }}>+ Neue Buchung</button>
      </div>

      {showForm && (
        <Card style={{ marginBottom: 18, border: `2px solid ${C.red}30` }}>
          <h3 style={{ fontSize: 14, fontWeight: 700, color: C.dark, margin: "0 0 14px" }}>Neue Buchung erfassen</h3>
          <div style={{ display: "flex", gap: 4, marginBottom: 14, padding: 3, background: C.g100, borderRadius: 8, width: "fit-content" }}>
            <button onClick={() => { setFormType("expense"); setFormCat(""); }} style={{
              padding: "7px 16px", borderRadius: 6, border: "none", cursor: "pointer",
              background: formType === "expense" ? C.red : "transparent",
              color: formType === "expense" ? C.white : C.g500,
              fontSize: 12, fontWeight: 600, fontFamily: "inherit",
            }}>Ausgabe</button>
            <button onClick={() => { setFormType("income"); setFormCat(""); }} style={{
              padding: "7px 16px", borderRadius: 6, border: "none", cursor: "pointer",
              background: formType === "income" ? C.green : "transparent",
              color: formType === "income" ? C.white : C.g500,
              fontSize: 12, fontWeight: 600, fontFamily: "inherit",
            }}>Einnahme</button>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr 1fr", gap: 12, marginBottom: 14 }}>
            <div>
              <label style={{ fontSize: 11, fontWeight: 600, color: C.g500, display: "block", marginBottom: 4 }}>KATEGORIE</label>
              <select value={formCat} onChange={e => setFormCat(e.target.value)} style={{ width: "100%", padding: "9px 10px", borderRadius: 8, border: `1px solid ${C.g300}`, fontSize: 12, fontFamily: "inherit", background: C.white }}>
                <option value="">Bitte wählen...</option>
                {categories.map(c => <option key={c.id} value={c.id}>{c.icon} {c.label}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize: 11, fontWeight: 600, color: C.g500, display: "block", marginBottom: 4 }}>BETRAG (€)</label>
              <input value={formAmount} onChange={e => setFormAmount(e.target.value)} placeholder="0,00" style={{ width: "100%", padding: "9px 10px", borderRadius: 8, border: `1px solid ${C.g300}`, fontSize: 12, fontFamily: "inherit", boxSizing: "border-box" }} />
            </div>
            <div>
              <label style={{ fontSize: 11, fontWeight: 600, color: C.g500, display: "block", marginBottom: 4 }}>DATUM</label>
              <input type="date" value={formDate} onChange={e => setFormDate(e.target.value)} style={{ width: "100%", padding: "9px 10px", borderRadius: 8, border: `1px solid ${C.g300}`, fontSize: 12, fontFamily: "inherit", boxSizing: "border-box" }} />
            </div>
            <div>
              <label style={{ fontSize: 11, fontWeight: 600, color: C.g500, display: "block", marginBottom: 4 }}>NOTIZ</label>
              <input value={formNote} onChange={e => setFormNote(e.target.value)} placeholder="Beschreibung..." style={{ width: "100%", padding: "9px 10px", borderRadius: 8, border: `1px solid ${C.g300}`, fontSize: 12, fontFamily: "inherit", boxSizing: "border-box" }} />
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={handleAdd} style={{ padding: "9px 20px", borderRadius: 8, border: "none", background: formType === "income" ? C.green : C.red, color: C.white, fontSize: 12, fontWeight: 700, cursor: "pointer", fontFamily: "inherit" }}>
              ✅ {formType === "income" ? "Einnahme" : "Ausgabe"} speichern
            </button>
            <button onClick={() => setShowForm(false)} style={{ padding: "9px 14px", borderRadius: 8, border: `1px solid ${C.g300}`, background: C.white, fontSize: 12, cursor: "pointer", fontFamily: "inherit", color: C.g500, fontWeight: 600 }}>Abbrechen</button>
          </div>
        </Card>
      )}

      <div style={{ display: "flex", gap: 4, marginBottom: 16 }}>
        {[
          { id: "alle", label: "Alle" },
          { id: "expense", label: "Ausgaben" },
          { id: "income", label: "Einnahmen" },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: "7px 14px", borderRadius: 18, border: "none", cursor: "pointer",
            fontSize: 12, fontWeight: 600, fontFamily: "inherit",
            background: filter === f.id ? C.dark : C.g100,
            color: filter === f.id ? C.white : C.g500,
          }}>{f.label}</button>
        ))}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
        {sorted.slice(0, 25).map(entry => {
          const cat = getCatInfo(entry);
          const isIncome = entry.type === "income";
          return (
            <div key={entry.id} style={{
              display: "flex", alignItems: "center", gap: 12, padding: "12px 16px",
              background: C.white, borderRadius: 10, border: `1px solid ${C.g200}`,
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 8, background: cat.color + "15", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 16 }}>{cat.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: C.dark }}>{cat.label}</div>
                <div style={{ fontSize: 11, color: C.g400, marginTop: 1 }}>{entry.note}</div>
              </div>
              <div style={{ fontSize: 11, color: C.g400 }}>{entry.date.split("-").reverse().join(".")}</div>
              <div style={{ fontSize: 14, fontWeight: 700, color: isIncome ? C.greenDark : C.red, minWidth: 100, textAlign: "right" }}>
                {isIncome ? "+" : "−"}{fmt(entry.amount)} €
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function KategorienPage({ entries }) {
  const allExpenses = entries.filter(e => e.type === "expense");
  const total = allExpenses.reduce((s, e) => s + e.amount, 0);

  const byCategory = [...EXPENSE_CATEGORIES, OWNER_CATEGORY].map(cat => {
    const catEntries = allExpenses.filter(e => e.category === cat.id);
    const catTotal = catEntries.reduce((s, e) => s + e.amount, 0);
    const monthly = {};
    catEntries.forEach(e => {
      const m = e.date.slice(0, 7);
      monthly[m] = (monthly[m] || 0) + e.amount;
    });
    return { ...cat, total: catTotal, count: catEntries.length, monthly, pct: total > 0 ? (catTotal / total * 100) : 0 };
  }).filter(c => c.total > 0).sort((a, b) => b.total - a.total);

  return (
    <div>
      <div style={{ marginBottom: 22 }}>
        <h1 style={{ fontSize: 24, fontWeight: 800, color: C.dark, margin: 0 }}>Kategorien-Analyse</h1>
        <p style={{ color: C.g500, margin: "4px 0 0", fontSize: 13 }}>Detaillierte Aufschlüsselung aller Ausgaben · Q1 2026</p>
      </div>

      {/* Visual category map */}
      <Card style={{ marginBottom: 18 }}>
        <h3 style={{ fontSize: 14, fontWeight: 700, color: C.dark, margin: "0 0 14px" }}>🗺 Ausgaben-Landkarte</h3>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 4 }}>
          {byCategory.map(cat => (
            <div key={cat.id} style={{
              width: `${Math.max(cat.pct * 2.5, 60)}px`,
              height: `${Math.max(cat.pct * 1.8, 50)}px`,
              background: cat.color + "20",
              border: `2px solid ${cat.color}40`,
              borderRadius: 10, display: "flex", flexDirection: "column",
              alignItems: "center", justifyContent: "center", padding: 6,
            }}>
              <span style={{ fontSize: cat.pct > 10 ? 18 : 14 }}>{cat.icon}</span>
              <span style={{ fontSize: 9, fontWeight: 700, color: cat.color, marginTop: 2, textAlign: "center" }}>{cat.pct.toFixed(0)}%</span>
            </div>
          ))}
        </div>
      </Card>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {byCategory.map(cat => (
          <Card key={cat.id} style={{ padding: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <div style={{ width: 44, height: 44, borderRadius: 10, background: cat.color + "18", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 22 }}>{cat.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 14, fontWeight: 700, color: C.dark }}>{cat.label}</span>
                  <Badge color={cat.color} bg={cat.color + "15"}>{cat.pct.toFixed(1)}%</Badge>
                </div>
                <div style={{ marginTop: 6, display: "flex", gap: 6 }}>
                  {["2026-01", "2026-02", "2026-03"].map(m => (
                    <div key={m} style={{ flex: 1 }}>
                      <div style={{ fontSize: 10, color: C.g400, marginBottom: 2 }}>{MONTHS[parseInt(m.split("-")[1]) - 1]}</div>
                      <ProgressBar value={cat.monthly[m] || 0} max={Math.max(...Object.values(cat.monthly))} color={cat.color} h={4} />
                      <div style={{ fontSize: 10, fontWeight: 600, color: C.g700, marginTop: 2 }}>{fmt(cat.monthly[m] || 0)} €</div>
                    </div>
                  ))}
                </div>
              </div>
              <div style={{ textAlign: "right" }}>
                <div style={{ fontSize: 18, fontWeight: 800, color: C.dark }}>{fmt(cat.total)} €</div>
                <div style={{ fontSize: 11, color: C.g400 }}>Ø {fmt(Math.round(cat.total / 3))} €/Mon.</div>
              </div>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}

// ─── MAIN APP ──────────────────────────────────────────────────────

const NAV = [
  { id: "dashboard", label: "Übersicht", icon: "📊" },
  { id: "buchungen", label: "Buchungen", icon: "📝" },
  { id: "kategorien", label: "Kategorien", icon: "📂" },
];

export default function App() {
  const [page, setPage] = useState("dashboard");
  const [entries, setEntries] = useState(DEMO_ENTRIES);
  const [selectedMonth, setSelectedMonth] = useState("alle");
  const [collapsed, setCollapsed] = useState(false);
  const [loaded, setLoaded] = useState(false);
  useEffect(() => setLoaded(true), []);

  return (
    <div style={{
      display: "flex", minHeight: "100vh", fontFamily: "'DM Sans', 'Segoe UI', sans-serif",
      background: C.g50, opacity: loaded ? 1 : 0, transition: "opacity 0.4s",
    }}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700;800;900&display=swap" rel="stylesheet" />

      <aside style={{
        width: collapsed ? 64 : 220, minHeight: "100vh", background: C.dark,
        padding: "16px 10px", display: "flex", flexDirection: "column",
        transition: "width 0.25s", flexShrink: 0, position: "sticky", top: 0,
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: collapsed ? 0 : 10, justifyContent: collapsed ? "center" : "flex-start", marginBottom: 24, padding: "4px 4px" }}>
          <div style={{ width: 34, height: 34, borderRadius: 9, background: C.red, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 14, fontWeight: 900, color: C.white, flexShrink: 0 }}>D</div>
          {!collapsed && (
            <div>
              <div style={{ fontSize: 13, fontWeight: 800, color: C.white, letterSpacing: "0.5px" }}>DIACARA</div>
              <div style={{ fontSize: 9, color: C.g400, fontWeight: 500, marginTop: -1 }}>Finanz-Cockpit</div>
            </div>
          )}
        </div>

        {NAV.map(item => (
          <button key={item.id} onClick={() => setPage(item.id)} style={{
            display: "flex", alignItems: "center", gap: collapsed ? 0 : 10,
            justifyContent: collapsed ? "center" : "flex-start",
            padding: collapsed ? "10px" : "9px 12px", width: "100%",
            borderRadius: 8, border: "none", cursor: "pointer",
            background: page === item.id ? "rgba(229,25,50,0.2)" : "transparent",
            color: page === item.id ? C.red : C.g400,
            fontWeight: 600, fontSize: 13, fontFamily: "inherit", marginBottom: 2,
          }}
          onMouseEnter={e => { if (page !== item.id) e.currentTarget.style.background = "rgba(255,255,255,0.05)"; }}
          onMouseLeave={e => { if (page !== item.id) e.currentTarget.style.background = "transparent"; }}
          >
            <span style={{ fontSize: 16, minWidth: 22, textAlign: "center" }}>{item.icon}</span>
            {!collapsed && <span>{item.label}</span>}
          </button>
        ))}

        {!collapsed && (
          <div style={{ marginTop: 24, padding: "12px", borderRadius: 8, background: "rgba(255,255,255,0.04)" }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: C.g400, letterSpacing: "1px", marginBottom: 6 }}>HINWEIS</div>
            <div style={{ fontSize: 11, color: C.g400, lineHeight: 1.5 }}>
              Dies ist ein Übersichtstool, keine Buchhaltung. Die offizielle Buchführung läuft über DATEV / Steuerberater.
            </div>
          </div>
        )}

        <div style={{ flex: 1 }} />
        <button onClick={() => setCollapsed(!collapsed)} style={{ padding: 8, borderRadius: 8, border: "none", cursor: "pointer", background: "transparent", color: C.g400, fontSize: 14, fontFamily: "inherit" }}>
          {collapsed ? "→" : "←"}
        </button>
      </aside>

      <main style={{ flex: 1, padding: 28, maxWidth: 1100, overflow: "auto" }}>
        {page === "dashboard" && <DashboardPage entries={entries} selectedMonth={selectedMonth} setSelectedMonth={setSelectedMonth} />}
        {page === "buchungen" && <BuchungenPage entries={entries} setEntries={setEntries} />}
        {page === "kategorien" && <KategorienPage entries={entries} />}
      </main>
    </div>
  );
}
