// ============================================================
// LSMD — Dashboard Shell (Sidebar, Topbar) + Übersicht
// ============================================================

function lsmdUserLabel(user) {
  if (!user) return 'Mitarbeiter';
  return user.display_name || user.username || 'Mitarbeiter';
}

function lsmdDienstnummer(user) {
  if (!user) return '[Unbekannt]';
  const en = user.employee_number != null ? String(user.employee_number).trim() : '';
  if (en) {
    if (/^\[\d+\]$/.test(en)) return en;
    const m = en.match(/\d+/g);
    if (m?.length) return `[${parseInt(m[m.length - 1], 10)}]`;
    return en;
  }
  const raw = user.display_name || user.ic_name || user.name || '';
  const b = String(raw).match(/^\s*\[(\d+)\]/);
  if (b) return `[${b[1]}]`;
  return '[Unbekannt]';
}

const NAV_GROUPS = [
  { title: 'Suche & Wissen', items: [
    { id: 'rechner', label: 'Kosten-Rechner', icon: 'Calculator' },
    { id: 'versicherungssuche', label: 'Versicherungssuche', icon: 'Search' },
    { id: 'wiki', label: 'Wiki', icon: 'BookOpen' },
  ]},
  { title: 'Aktensystem', items: [
    { id: 'akten', label: 'Patientenakten', icon: 'FolderHeart' },
  ]},
  { title: 'Team & Dienste', items: [
    { id: 'boards', label: 'Boards & Teams', icon: 'LayoutGrid' },
    { id: 'personal', label: 'Personal', icon: 'Users', sub: [
      { id: 'personal-statistik', label: 'Statistik' },
      { id: 'abteilungen', label: 'Abteilungen' },
      { id: 'verwaltung', label: 'Verwaltung' },
      { id: 'verknuepfungen', label: 'Verknüpfungen' },
      { id: 'urlaub', label: 'Urlaub' },
      { id: 'verfuegbarkeit', label: 'Verfügbarkeit' },
      { id: 'bonus', label: 'Bonus' },
      { id: 'dienstzeiten', label: 'Dienstzeiten' },
      { id: 'versicherungen', label: 'Versicherungen' },
    ]},
  ]},
  { title: 'Administration', items: [
    { id: 'logbuch', label: 'Logbuch', icon: 'ScrollText' },
    { id: 'dna', label: 'DNA-Test', icon: 'TestTube' },
    { id: 'admin', label: 'Admin', icon: 'ShieldAlert' },
  ]},
  { title: 'Konto', items: [
    { id: 'profil', label: 'Profil', icon: 'User', sub: [
      { id: 'profil', label: 'Profil' },
      { id: 'profil-bonus', label: 'Bonus' },
      { id: 'profil-abwesenheit', label: 'Abwesenheit' },
      { id: 'profil-dienstzeiten', label: 'Dienstzeiten' },
      { id: 'profil-akte', label: 'Personalakte' },
    ]},
    { id: 'logout', label: 'Logout', icon: 'LogOut' },
  ]},
];

function Sidebar({ view, setView, go, dark, setDark, open, setOpen, user }) {
  const [expanded, setExpanded] = useState({ personal: true, profil: false });
  const toggle = (id) => setExpanded(s => ({ ...s, [id]: !s[id] }));

  const NavItem = ({ item }) => {
    const hasSub = item.sub;
    const active = view === item.id || (hasSub && item.sub.some(s => s.id === view));
    return (
      <div>
        <button
          onClick={() => { if (item.id === 'logout') { window.location.href = '/auth/logout'; return; } hasSub ? toggle(item.id) : setView(item.id); }}
          className={`group w-full flex items-center gap-2.5 h-9 px-2.5 rounded-md text-[13px] font-semibold transition-colors ${active && !hasSub ? 'bg-[var(--c-accent-soft)] text-accent' : 'text-muted hover:text-ink hover:bg-white/5'}`}
          style={active && !hasSub ? { boxShadow: 'inset 2px 0 0 var(--c-accent)' } : {}}
        >
          <Icon name={item.icon} size={17} className={active ? 'text-accent' : ''} />
          <span className="flex-1 text-left truncate">{item.label}</span>
          {hasSub && <Icon name="ChevronDown" size={14} className={`transition-transform ${expanded[item.id] ? 'rotate-180' : ''}`} />}
        </button>
        {hasSub && expanded[item.id] && (
          <div className="ml-4 mt-0.5 mb-1 border-l border-line pl-2 flex flex-col gap-0.5">
            {item.sub.map(s => {
              const sActive = view === s.id;
              return (
                <button key={s.id} onClick={() => setView(s.id)} className={`flex items-center gap-2 h-8 px-2.5 rounded-md text-[12.5px] font-medium transition-colors ${sActive ? 'text-accent bg-[var(--c-accent-soft)]' : 'text-muted hover:text-ink hover:bg-white/5'}`}>
                  <span className="flex-1 text-left truncate">{s.label}</span>
                  {s.badge != null && <span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-line text-ink">{s.badge}</span>}
                </button>
              );
            })}
          </div>
        )}
      </div>
    );
  };

  return (
    <>
      {open && <div className="fixed inset-0 z-40 bg-black/50 lg:hidden" onClick={() => setOpen(false)} />}
      <aside className={`fixed lg:sticky top-0 z-50 lg:z-0 h-screen w-[272px] shrink-0 border-r border-line bg-bg2 flex flex-col transition-transform lg:translate-x-0 ${open ? 'translate-x-0' : '-translate-x-full'}`}>
        <button
          type="button"
          onClick={() => { window.location.href = '/'; }}
          className="p-4 flex items-center gap-3 border-b border-line w-full text-left hover:bg-white/5 transition-colors"
          title="Zur Startseite"
        >
          <Crest size={38} />
          <div className="leading-tight min-w-0">
            <div className="font-extrabold truncate">LSMD-Dashboard</div>
            <div className="text-[10px] uplabel truncate">Verwaltungspanel der Behörde</div>
          </div>
        </button>
        <div className="p-3">
          <div className="relative">
            <Icon name="Search" size={15} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted" />
            <input placeholder="Suchen …" className="w-full h-9 rounded-md bg-card border border-line pl-8 pr-3 text-[13px] outline-none focus:border-accent" />
          </div>
        </div>
        <nav className="flex-1 overflow-y-auto px-3 pb-3 flex flex-col gap-4">
          {NAV_GROUPS.map(g => (
            <div key={g.title}>
              <div className="uplabel text-[10px] px-2.5 mb-1.5">{g.title}</div>
              <div className="flex flex-col gap-0.5">
                {g.items.map(it => <NavItem key={it.id} item={it} />)}
              </div>
            </div>
          ))}
        </nav>
        <div className="p-3 border-t border-line">
          <button onClick={() => setDark(d => !d)} className="w-full flex items-center gap-2 h-9 px-2.5 rounded-md text-[13px] font-semibold text-muted hover:text-ink hover:bg-white/5">
            <Icon name={dark ? 'Moon' : 'Sun'} size={17} />
            <span className="flex-1 text-left">{dark ? 'Dark Mode' : 'Light Mode'}</span>
            <span className="relative h-5 w-9 rounded-full bg-line">
              <span className={`absolute top-0.5 h-4 w-4 rounded-full bg-accent transition-all ${dark ? 'left-0.5' : 'left-[18px]'}`} />
            </span>
          </button>
        </div>
      </aside>
    </>
  );
}

function Topbar({ onStudio, setOpen, dark, setDark, user, onProfile }) {
  const display = lsmdUserLabel(user);
  const sub = `Dienstnummer ${lsmdDienstnummer(user)}`;
  return (
    <header className="sticky top-0 z-30 glass border-b border-line">
      <div className="h-16 px-4 lg:px-6 flex items-center gap-3">
        <button className="lg:hidden text-ink" onClick={() => setOpen(true)}><Icon name="Menu" size={22} /></button>
        <div className="flex-1 max-w-md hidden sm:block">
          <div className="relative">
            <Icon name="Search" size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted" />
            <input placeholder="Mitarbeiter, Versicherung, Dienstnummer …" className="w-full h-10 rounded-md bg-card border border-line pl-9 pr-3 text-sm outline-none focus:border-accent" />
          </div>
        </div>
        <div className="flex-1 sm:hidden" />
        <button onClick={() => setDark(d => !d)} className="grid place-items-center h-10 w-10 rounded-md border border-line text-muted hover:text-ink transition-colors"><Icon name={dark ? 'Moon' : 'Sun'} size={18} /></button>
        <Btn variant="outline" size="md" icon="Palette" onClick={onStudio}>Studio</Btn>
        <button type="button" onClick={onProfile} className="flex items-center gap-2.5 h-10 pl-1.5 pr-3 rounded-md border border-line hover:border-muted transition-colors">
          {user?.avatar
            ? <img src={user.avatar} alt="" className="h-7 w-7 rounded-md object-cover" />
            : <Avatar name={display} size={28} color="#CC2233" />}
          <div className="text-left leading-tight hidden md:block whitespace-nowrap">
            <div className="text-[13px] font-bold">{display}</div>
            <div className="text-[10px] text-muted">{sub}</div>
          </div>
        </button>
      </div>
    </header>
  );
}

// ---- Section header used across dashboard pages ----
function PageHead({ title, sub, children }) {
  return (
    <div className="flex flex-wrap items-end justify-between gap-3 mb-6">
      <div>
        <h1 className="text-2xl font-extrabold tracking-tight">{title}</h1>
        {sub && <p className="mt-1 text-sm text-muted">{sub}</p>}
      </div>
      {children}
    </div>
  );
}

function Tabs({ tabs, active, onChange }) {
  return (
    <div className="flex items-center gap-1 overflow-x-auto border-b border-line -mx-1 px-1">
      {tabs.map(t => {
        const id = typeof t === 'string' ? t : t.id;
        const label = typeof t === 'string' ? t : t.label;
        const badge = typeof t === 'object' ? t.badge : null;
        const on = active === id;
        return (
          <button key={id} onClick={() => onChange(id)} className={`relative flex items-center gap-1.5 h-10 px-3 text-[13px] font-semibold whitespace-nowrap transition-colors ${on ? 'text-ink' : 'text-muted hover:text-ink'}`}>
            {label}
            {badge != null && <span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-line text-ink">{badge}</span>}
            {on && <span className="absolute bottom-0 left-0 right-0 h-0.5 bg-accent rounded-full" />}
          </button>
        );
      })}
    </div>
  );
}

// ============================================================
// Dashboard — Übersicht
// ============================================================
function DashboardOverview({ user, setView }) {
  const [range, setRange] = useState('6 Wochen');
  const [kpis, setKpis] = useState([]);
  const [quickLinks, setQuickLinks] = useState([]);
  const display = lsmdUserLabel(user);
  const dnLabel = lsmdDienstnummer(user);
  const rank = user?.rank_label || 'Mitarbeiter';
  const dateLine = new Date().toLocaleDateString('de-DE', {
    weekday: 'long', day: '2-digit', month: 'long', year: 'numeric',
  });

  useEffect(() => {
    fetch('/api/dashboard/overview', { credentials: 'same-origin' })
      .then(r => r.json())
      .then(d => { setKpis(d.kpis || []); setQuickLinks(d.quickLinks || []); })
      .catch(() => { setKpis([]); setQuickLinks([]); });
  }, []);

  return (
    <div className="flex flex-col gap-6">
      {/* Begrüßung */}
      <Card className="relative overflow-hidden p-6" style={{ background: 'linear-gradient(120deg, var(--c-card), var(--c-bg2))' }}>
        <div className="absolute -right-10 -top-10 h-44 w-44 rotate-45 rounded-3xl opacity-15" style={{ background: 'var(--c-accent)' }} />
        <div className="relative flex flex-wrap items-center justify-between gap-4">
          <div>
            <Label className="capitalize">{dateLine}</Label>
            <h1 className="mt-1.5 text-3xl font-black tracking-tight">Willkommen, {display}</h1>
            <p className="mt-1 text-sm text-muted">Dienstnummer {dnLabel} · {rank}</p>
          </div>
          <div className="flex items-center gap-2">
            <StatusBadge status="AKTIV" />
            <Btn variant="soft" icon="Stethoscope" size="sm">Im Dienst</Btn>
          </div>
        </div>
      </Card>

      {/* Schnellzugriff */}
      {quickLinks.length > 0 && (
        <div>
          <h2 className="text-lg font-bold mb-3">Schnellzugriff</h2>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2">
            {quickLinks.map(l => (
              <button key={l.id} type="button" onClick={() => setView?.(l.id)}
                className="flex flex-col items-center gap-2 rounded-lg border border-line bg-card p-4 hover:border-accent transition-colors">
                <Icon name={l.icon} size={22} className="text-accent" />
                <span className="text-xs font-semibold text-center">{l.label}</span>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-3">
        {(kpis.length ? kpis : KPIS).map((k, i) => <StatCard key={k.label} {...k} delay={i * 40} />)}
      </div>

      {/* Wochenperformance */}
      <Card className="p-6">
        <div className="flex flex-wrap items-start justify-between gap-3 mb-5">
          <div>
            <h2 className="text-lg font-bold">Wochenperformance</h2>
            <p className="text-sm text-muted mt-0.5">Dienststunden & Beförderungen im Verlauf</p>
          </div>
          <div className="flex items-center gap-2">
            <Select value={range} onChange={e => setRange(e.target.value)} style={{ width: 140 }}>
              <option>6 Wochen</option><option>3 Monate</option><option>Jahr</option>
            </Select>
            <Btn variant="outline" size="sm" icon="Download">CSV</Btn>
            <Btn variant="outline" size="sm" icon="FileDown">PDF</Btn>
          </div>
        </div>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
          {[['Wochen','6'],['Gesamt-Zeit','1.027 h'],['Schnitt / Woche','171 h'],['Beförderungen','12']].map(([l,v]) => (
            <div key={l} className="rounded-md border border-line bg-bg/40 p-3">
              <div className="uplabel text-[10px]">{l}</div>
              <div className="mt-1 text-xl font-extrabold">{v}</div>
            </div>
          ))}
        </div>
        <WeekLineChart data={WEEK_PERF} height={240} />
      </Card>

      {/* Charts Reihe 1 */}
      <div className="grid lg:grid-cols-2 gap-6">
        <Card className="p-6">
          <h2 className="text-lg font-bold mb-1">Status im Rettungsdienst</h2>
          <p className="text-sm text-muted mb-4">Aktuelle Verteilung aller Mitarbeiter</p>
          <div className="grid grid-cols-2 gap-4 items-center">
            <DonutChart data={STATUS_DONUT} centerValue="55" centerLabel="Gesamt" height={200} />
            <div className="flex flex-col gap-2">
              {STATUS_DONUT.map(s => (
                <div key={s.name} className="flex items-center gap-2 text-sm">
                  <span className="h-2.5 w-2.5 rounded-sm" style={{ background: s.fill }} />
                  <span className="flex-1 text-muted">{s.name}</span>
                  <span className="font-bold">{s.value}</span>
                </div>
              ))}
            </div>
          </div>
        </Card>
        <Card className="p-6">
          <h2 className="text-lg font-bold mb-1">Warnstufen</h2>
          <p className="text-sm text-muted mb-4">Disziplinarische Vermerke nach Stufe</p>
          <VBarChart data={WARN_BARS} colored height={232} />
        </Card>
      </div>

      {/* Charts Reihe 2 */}
      <div className="grid lg:grid-cols-2 gap-6">
        <Card className="p-6">
          <h2 className="text-lg font-bold mb-4">Top Positionen</h2>
          <HBarChart data={TOP_POSITIONS} height={244} />
        </Card>
        <Card className="p-6">
          <h2 className="text-lg font-bold mb-1">Timeline-Typen</h2>
          <p className="text-sm text-muted mb-4">Verteilung aller Akten-Einträge</p>
          <div className="grid grid-cols-2 gap-4 items-center">
            <DonutChart data={TIMELINE_TYPES} centerValue="134" centerLabel="Einträge" height={200} />
            <div className="flex flex-col gap-2">
              {TIMELINE_TYPES.map(s => (
                <div key={s.name} className="flex items-center gap-2 text-sm">
                  <span className="h-2.5 w-2.5 rounded-sm" style={{ background: s.fill }} />
                  <span className="flex-1 text-muted">{s.name}</span>
                  <span className="font-bold">{s.value}</span>
                </div>
              ))}
            </div>
          </div>
        </Card>
      </div>

      {/* Charts Reihe 3 */}
      <div className="grid lg:grid-cols-2 gap-6">
        <Card className="p-6">
          <h2 className="text-lg font-bold mb-4">Angestrebte Positionen</h2>
          <div className="flex flex-col gap-2">
            {TARGET_POSITIONS.map(t => {
              const pct = Math.round(t.erfuellt / t.anwaerter * 100);
              return (
                <div key={t.rank} className="flex items-center gap-3">
                  <div className="w-28 text-sm font-semibold truncate">{t.rank}</div>
                  <div className="flex-1 h-2.5 rounded-full bg-line overflow-hidden">
                    <div className="h-full rounded-full bg-accent transition-all" style={{ width: `${pct}%` }} />
                  </div>
                  <div className="w-20 text-right text-xs text-muted">{t.erfuellt}/{t.anwaerter} · {pct}%</div>
                </div>
              );
            })}
          </div>
        </Card>
        <Card className="p-6">
          <h2 className="text-lg font-bold mb-1">Beförderungen nach Ziel-Rang</h2>
          <p className="text-sm text-muted mb-4">Anwärter vs. erfüllte Ziele</p>
          <GroupBarChart data={TARGET_POSITIONS} height={244} />
        </Card>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, PageHead, Tabs, DashboardOverview, NAV_GROUPS });
