// ============================================================
// LSMD — UI Primitives
// ============================================================
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
const RC = window.Recharts || {};

// ---- Icon helper (Lucide vanilla icon-node data → inline SVG) ----
function Icon({ name, size = 18, className = '', strokeWidth = 2, style }) {
  const LU = window.lucide || {};
  const reg = LU.icons || LU;
  const node = reg[name];
  if (!node) return <svg width={size} height={size} viewBox="0 0 24 24" className={className} style={style} />;
  // node may be ['svg', attrs, children] or just [[tag, attrs], ...]
  const children = typeof node[0] === 'string' ? (node[2] || []) : node;
  return (
    <svg
      xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24"
      fill="none" stroke="currentColor" strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round"
      className={className} style={style}
    >
      {children.map((c, i) => React.createElement(c[0], { key: i, ...c[1] }))}
    </svg>
  );
}

// ---- LSMD Wappen / Logo (Upload-System) ----
function Crest({ size = 36, className = '' }) {
  const src = (window.__LSMD_SITE__ && window.__LSMD_SITE__.logoUrl) || '/img/lsmd-logo.png';
  const abs = src.startsWith('http') ? src : `${window.location.origin}${src.startsWith('/') ? src : `/${src}`}`;
  return (
    <img
      src={abs}
      alt="LSMD"
      className={`shrink-0 object-contain drop-shadow-[0_2px_8px_rgba(0,0,0,.35)] ${className}`}
      style={{ width: size, height: size }}
      onError={(e) => { e.target.onerror = null; e.target.src = `${window.location.origin}/img/lsmd-logo.png`; }}
    />
  );
}

// ---- Buttons ----
function Btn({ children, variant = 'solid', size = 'md', icon, iconRight, className = '', ...rest }) {
  const sizes = { sm: 'h-8 px-3 text-[13px]', md: 'h-10 px-4 text-sm', lg: 'h-12 px-6 text-[15px]' };
  const variants = {
    solid:   'bg-accent text-white hover:brightness-110 shadow-[0_4px_14px_rgba(204,34,51,.35)]',
    outline: 'border border-line text-ink hover:border-accent hover:text-accent bg-transparent',
    ghost:   'text-muted hover:text-ink hover:bg-white/5',
    soft:    'bg-[var(--c-accent-soft)] text-accent hover:brightness-110',
    discord: 'bg-discord text-white hover:brightness-110',
  };
  return (
    <button
      className={`inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md font-semibold transition-all duration-150 active:scale-[.98] disabled:opacity-50 disabled:pointer-events-none ${sizes[size]} ${variants[variant]} ${className}`}
      {...rest}
    >
      {icon && <Icon name={icon} size={size === 'lg' ? 18 : 16} />}
      {children}
      {iconRight && <Icon name={iconRight} size={size === 'lg' ? 18 : 16} />}
    </button>
  );
}

// ---- Card ----
function Card({ children, className = '', glass = false, ...rest }) {
  return (
    <div
      className={`rounded-lg border border-line ${glass ? 'glass' : 'bg-card'} ${className}`}
      {...rest}
    >
      {children}
    </div>
  );
}

function Label({ children, className = '' }) {
  return <div className={`uplabel text-[11px] ${className}`}>{children}</div>;
}

// ---- Badges ----
function StatusBadge({ status, dot = true, className = '' }) {
  const s = STATUS[status] || { label: status, color: '#8899AA' };
  return (
    <span
      className={`inline-flex items-center gap-1.5 whitespace-nowrap rounded px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide ${className}`}
      style={{ color: s.color, background: `${s.color}1f`, border: `1px solid ${s.color}40` }}
    >
      {dot && <span className="h-1.5 w-1.5 rounded-full" style={{ background: s.color }} />}
      {s.label}
    </span>
  );
}

function RangBadge({ rank, className = '' }) {
  const r = RANKS[rank] || { label: rank, color: '#8899AA' };
  return (
    <span
      className={`inline-flex items-center whitespace-nowrap rounded px-2 py-0.5 text-[11px] font-bold tracking-wide ${className}`}
      style={{ color: r.color, background: `${r.color}1a`, border: `1px solid ${r.color}40` }}
    >
      {r.label}
    </span>
  );
}

// ---- Avatar (Discord-style monogram) ----
function Avatar({ name, size = 40, color = 'var(--c-accent)' }) {
  return (
    <div
      className="grid place-items-center rounded-full font-bold text-white shrink-0 select-none"
      style={{ width: size, height: size, background: color, fontSize: size * 0.38, letterSpacing: '.02em' }}
    >
      {avatarFor(name)}
    </div>
  );
}

// ---- KPI StatCard ----
function StatCard({ label, value, sub, icon, tone = 'ink', delay = 0 }) {
  const toneColor = { accent: 'var(--c-accent)', success: '#22C55E', warning: '#F59E0B', ink: 'var(--c-ink)' }[tone];
  return (
    <Card glass className="p-4 fadeup hover:border-accent/50 transition-colors group" style={{ animationDelay: `${delay}ms` }}>
      <div className="flex items-start justify-between">
        <Label>{label}</Label>
        <div
          className="grid place-items-center h-8 w-8 rounded-md transition-transform group-hover:scale-110"
          style={{ background: `color-mix(in srgb, ${toneColor} 14%, transparent)`, color: toneColor }}
        >
          <Icon name={icon} size={16} />
        </div>
      </div>
      <div className="mt-3 text-3xl font-extrabold tracking-tight" style={{ color: tone === 'ink' ? 'var(--c-ink)' : toneColor }}>
        {value}
      </div>
      <div className="mt-1 text-xs text-muted">{sub}</div>
    </Card>
  );
}

// ---- Modal ----
function Modal({ open, onClose, title, children, footer, width = 'max-w-lg' }) {
  useEffect(() => {
    const onKey = (e) => e.key === 'Escape' && onClose && onClose();
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[100] grid place-items-center p-4">
      <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={onClose} />
      <Card className={`relative w-full ${width} p-6 shadow-glass fadeup`}>
        {title && (
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold">{title}</h3>
            <button onClick={onClose} className="text-muted hover:text-ink transition-colors">
              <Icon name="X" size={20} />
            </button>
          </div>
        )}
        {children}
        {footer && <div className="mt-6 flex justify-end gap-2">{footer}</div>}
      </Card>
    </div>
  );
}

// ---- Form inputs ----
function Field({ label, hint, children, required }) {
  return (
    <label className="block">
      {label && (
        <div className="mb-1.5 text-[13px] font-semibold text-ink">
          {label} {required && <span className="text-accent">*</span>}
        </div>
      )}
      {children}
      {hint && <div className="mt-1 text-[11px] text-muted">{hint}</div>}
    </label>
  );
}
const inputCls = 'w-full h-10 rounded-md border border-line px-3 text-sm outline-none transition-colors focus:border-accent';
function TextInput(props) { return <input className={inputCls} {...props} />; }
function Select({ children, ...p }) { return <select className={inputCls + ' appearance-none cursor-pointer'} {...p}>{children}</select>; }
function TextArea(props) { return <textarea className={inputCls + ' h-auto py-2 resize-none'} {...props} />; }

// ---- Toggle ----
function Toggle({ checked, onChange, labels = ['Nein', 'Ja'] }) {
  return (
    <div className="inline-flex rounded-md border border-line overflow-hidden text-[13px] font-semibold">
      {[false, true].map((v, i) => (
        <button
          key={i}
          onClick={() => onChange(v)}
          className={`h-9 px-4 transition-colors ${checked === v ? (v ? 'bg-accent text-white' : 'bg-white/10 text-ink') : 'text-muted hover:text-ink'}`}
        >
          {labels[i]}
        </button>
      ))}
    </div>
  );
}

// ---- Chip (multi-select) ----
function Chip({ active, children, onClick, icon }) {
  return (
    <button
      onClick={onClick}
      className={`inline-flex items-center gap-1.5 rounded-md border px-3 h-9 text-[13px] font-semibold transition-all ${active ? 'border-accent bg-[var(--c-accent-soft)] text-accent' : 'border-line text-muted hover:text-ink hover:border-muted'}`}
    >
      {icon && <Icon name={icon} size={15} />}
      {children}
    </button>
  );
}

// ============================================================
// Charts (Recharts wrappers)
// ============================================================
function DonutChart({ data, centerLabel, centerValue, height = 220 }) {
  const { PieChart, Pie, Cell, ResponsiveContainer, Tooltip } = RC;
  return (
    <div className="relative" style={{ height }}>
      <ResponsiveContainer width="100%" height="100%">
        <PieChart>
          <Pie data={data} dataKey="value" innerRadius="62%" outerRadius="90%" paddingAngle={2} stroke="none">
            {data.map((d, i) => <Cell key={i} fill={d.fill} />)}
          </Pie>
          <Tooltip contentStyle={{ background: 'var(--c-card)', border: '1px solid var(--c-border)', borderRadius: 6, color: 'var(--c-ink)' }} itemStyle={{ color: 'var(--c-ink)' }} />
        </PieChart>
      </ResponsiveContainer>
      {centerValue && (
        <div className="absolute inset-0 grid place-items-center pointer-events-none">
          <div className="text-center">
            <div className="text-2xl font-extrabold">{centerValue}</div>
            <div className="text-[11px] uplabel">{centerLabel}</div>
          </div>
        </div>
      )}
    </div>
  );
}

function VBarChart({ data, color = '#CC2233', height = 220, colored = false }) {
  const { BarChart, Bar, Cell, XAxis, YAxis, ResponsiveContainer, Tooltip, CartesianGrid } = RC;
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} margin={{ top: 8, right: 8, left: -18, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="var(--c-border)" vertical={false} />
        <XAxis dataKey="name" tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <YAxis tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <Tooltip cursor={{ fill: 'rgba(255,255,255,.04)' }} contentStyle={{ background: 'var(--c-card)', border: '1px solid var(--c-border)', borderRadius: 6, color: 'var(--c-ink)' }} />
        <Bar dataKey="value" radius={[4, 4, 0, 0]} maxBarSize={48}>
          {data.map((d, i) => <Cell key={i} fill={colored ? (d.fill || color) : color} />)}
        </Bar>
      </BarChart>
    </ResponsiveContainer>
  );
}

function HBarChart({ data, color = '#CC2233', height = 240 }) {
  const { BarChart, Bar, XAxis, YAxis, ResponsiveContainer, Tooltip, CartesianGrid } = RC;
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} layout="vertical" margin={{ top: 0, right: 16, left: 8, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="var(--c-border)" horizontal={false} />
        <XAxis type="number" tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <YAxis type="category" dataKey="name" width={92} tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <Tooltip cursor={{ fill: 'rgba(255,255,255,.04)' }} contentStyle={{ background: 'var(--c-card)', border: '1px solid var(--c-border)', borderRadius: 6, color: 'var(--c-ink)' }} />
        <Bar dataKey="value" radius={[0, 4, 4, 0]} fill={color} maxBarSize={22} />
      </BarChart>
    </ResponsiveContainer>
  );
}

function GroupBarChart({ data, height = 240 }) {
  const { BarChart, Bar, XAxis, YAxis, ResponsiveContainer, Tooltip, CartesianGrid, Legend } = RC;
  return (
    <ResponsiveContainer width="100%" height={height}>
      <BarChart data={data} margin={{ top: 8, right: 8, left: -18, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="var(--c-border)" vertical={false} />
        <XAxis dataKey="rank" tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <YAxis tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <Tooltip cursor={{ fill: 'rgba(255,255,255,.04)' }} contentStyle={{ background: 'var(--c-card)', border: '1px solid var(--c-border)', borderRadius: 6, color: 'var(--c-ink)' }} />
        <Legend wrapperStyle={{ fontSize: 12 }} />
        <Bar dataKey="anwaerter" name="Anwärter" fill="#3B82F6" radius={[4, 4, 0, 0]} maxBarSize={26} />
        <Bar dataKey="erfuellt" name="Erfüllt" fill="#22C55E" radius={[4, 4, 0, 0]} maxBarSize={26} />
      </BarChart>
    </ResponsiveContainer>
  );
}

function WeekLineChart({ data, height = 240 }) {
  const { ComposedChart, Line, Bar, XAxis, YAxis, ResponsiveContainer, Tooltip, CartesianGrid, Legend } = RC;
  return (
    <ResponsiveContainer width="100%" height={height}>
      <ComposedChart data={data} margin={{ top: 8, right: 8, left: -18, bottom: 0 }}>
        <CartesianGrid strokeDasharray="3 3" stroke="var(--c-border)" vertical={false} />
        <XAxis dataKey="week" tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <YAxis tick={{ fill: 'var(--c-muted)', fontSize: 11 }} axisLine={false} tickLine={false} />
        <Tooltip cursor={{ fill: 'rgba(255,255,255,.04)' }} contentStyle={{ background: 'var(--c-card)', border: '1px solid var(--c-border)', borderRadius: 6, color: 'var(--c-ink)' }} />
        <Bar dataKey="std" name="Std." fill="var(--c-accent-soft)" radius={[4, 4, 0, 0]} maxBarSize={36} />
        <Line type="monotone" dataKey="std" name="Dienststunden" stroke="var(--c-accent)" strokeWidth={2.5} dot={{ r: 3, fill: 'var(--c-accent)' }} />
      </ComposedChart>
    </ResponsiveContainer>
  );
}

Object.assign(window, {
  Icon, Crest, Btn, Card, Label, StatusBadge, RangBadge, Avatar, StatCard, Modal,
  Field, TextInput, Select, TextArea, Toggle, Chip,
  DonutChart, VBarChart, HBarChart, GroupBarChart, WeekLineChart,
});
