// Desktop UI primitives — modals (Sheet→centered dialog), toasts, form fields,
// segmented controls, search, popover menus. Shared by all desktop screens.

// ─── Modal dialog (desktop replacement for the mobile bottom Sheet) ───
function Sheet({ open, onClose, children, width = 520 }) {
  const t = useTheme();
  const [mounted, setMounted] = useState(open);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    if (open) { setMounted(true); requestAnimationFrame(() => setShown(true)); }
    else { setShown(false); const id = setTimeout(() => setMounted(false), 200); return () => clearTimeout(id); }
  }, [open]);
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape' && open) onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!mounted) return null;
  return (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 200,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: t.scrim, opacity: shown ? 1 : 0,
      transition: 'opacity 0.2s ease', padding: 24,
      backdropFilter: 'blur(3px)', WebkitBackdropFilter: 'blur(3px)',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width, maxWidth: '100%', maxHeight: '88%', overflow: 'auto',
        background: t.sheetBg, borderRadius: 16,
        boxShadow: '0 20px 70px rgba(0,0,0,0.4), 0 0 0 0.5px ' + t.sep,
        transform: shown ? 'scale(1) translateY(0)' : 'scale(0.96) translateY(8px)',
        opacity: shown ? 1 : 0, transition: 'transform 0.22s cubic-bezier(0.2,0.8,0.2,1), opacity 0.18s',
        paddingTop: 18,
      }}>{children}</div>
    </div>
  );
}

// ─── Toast host ───
const ToastContext = createContext(() => {});
const useToast = () => useContext(ToastContext);
function ToastHost({ children }) {
  const t = useTheme();
  const [toasts, setToasts] = useState([]);
  const push = (msg) => {
    const id = Date.now() + Math.random();
    setToasts((p) => [...p, { id, msg }]);
    setTimeout(() => setToasts((p) => p.filter((x) => x.id !== id)), 2400);
  };
  return (
    <ToastContext.Provider value={push}>
      {children}
      <div style={{ position: 'absolute', bottom: 24, left: '50%', transform: 'translateX(-50%)', zIndex: 400, display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center', pointerEvents: 'none' }}>
        {toasts.map((x) => (
          <div key={x.id} style={{
            background: t.solidBg, color: t.solidFg, padding: '11px 18px', borderRadius: 12,
            fontSize: 13.5, fontWeight: 600, boxShadow: '0 8px 28px rgba(0,0,0,0.32)',
            display: 'flex', alignItems: 'center', gap: 9, animation: 'rfToastIn 0.26s cubic-bezier(0.2,0.8,0.2,1)',
          }}>
            <Icon d={icons.check} color={t.green} size={15} sw={2.6}/>{x.msg}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

// ─── Form helpers ───
const inp = (t) => ({
  width: '100%', padding: '11px 13px', borderRadius: 10,
  border: `1px solid ${t.inputBorder}`, background: t.inputBg,
  fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box',
  transition: 'border 0.15s, box-shadow 0.15s',
});

function Field({ label, required, children, hint, style }) {
  const t = useTheme();
  return (
    <div style={{ marginTop: 16, ...style }}>
      {label && (
        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>
          {label}{required && <span style={{ color: t.red, marginLeft: 3 }}>*</span>}
        </div>
      )}
      {children}
      {hint && <div style={{ fontSize: 11, color: t.textSec, marginTop: 5, lineHeight: 1.4 }}>{hint}</div>}
    </div>
  );
}
const FormGroup = Field;

function TextInput(props) {
  const t = useTheme();
  const [focus, setFocus] = useState(false);
  const { style, ...rest } = props;
  return <input {...rest} onFocus={(e) => { setFocus(true); props.onFocus && props.onFocus(e); }} onBlur={(e) => { setFocus(false); props.onBlur && props.onBlur(e); }}
    style={{ ...inp(t), ...(focus ? { borderColor: t.accent, boxShadow: `0 0 0 3px ${t.accentSoft}` } : {}), ...style }}/>;
}

// ─── Segmented control ───
function Segmented({ options, value, onChange, size = 'md', style }) {
  const t = useTheme();
  const pad = size === 'sm' ? '5px 12px' : '7px 16px';
  const fs = size === 'sm' ? 12 : 13;
  return (
    <div style={{ display: 'inline-flex', padding: 3, borderRadius: 9, background: t.chipStrong, ...style }}>
      {options.map(([id, label, count]) => (
        <Pressable key={id} onClick={() => onChange(id)} scale={0.97}>
          <div style={{
            padding: pad, borderRadius: 7, fontSize: fs, fontWeight: 600, whiteSpace: 'nowrap',
            background: value === id ? (t.dark ? '#48484A' : '#fff') : 'transparent',
            color: value === id ? t.text : t.textSec,
            boxShadow: value === id ? '0 1px 3px rgba(0,0,0,0.12)' : 'none',
            transition: 'all 0.15s', display: 'flex', alignItems: 'center', gap: 6,
          }}>
            {label}
            {count != null && count > 0 && (
              <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 100, background: value === id ? t.chip : t.chipStrong, color: value === id ? t.text : t.textSec }}>{count}</span>
            )}
          </div>
        </Pressable>
      ))}
    </div>
  );
}

// ─── Toolbar (sits under titlebar in each screen) ───
function Toolbar({ title, subtitle, children }) {
  const t = useTheme();
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 16, padding: '0 28px',
      height: 64, flexShrink: 0, borderBottom: `0.5px solid ${t.sep}`,
    }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 21, fontWeight: 700, color: t.text, letterSpacing: -0.5, lineHeight: 1.1 }}>{title}</div>
        {subtitle && <div style={{ fontSize: 12, color: t.textSec, marginTop: 2 }}>{subtitle}</div>}
      </div>
      <div style={{ flex: 1 }}/>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>{children}</div>
    </div>
  );
}

// ─── Search field (toolbar) ───
function SearchField({ value, onChange, placeholder = 'Suchen', width = 220 }) {
  const t = useTheme();
  const [focus, setFocus] = useState(false);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 7, width, height: 34,
      padding: '0 11px', borderRadius: 9, background: t.inputBg,
      border: `1px solid ${focus ? t.accent : t.inputBorder}`,
      boxShadow: focus ? `0 0 0 3px ${t.accentSoft}` : 'none', transition: 'all 0.15s',
    }}>
      <Icon d={icons.search} color={t.textSec} size={15} sw={2}/>
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 13.5, color: t.text, fontFamily: 'inherit', minWidth: 0 }}/>
      {value && <Pressable onClick={() => onChange('')} scale={0.8}><Icon d="M6 6l12 12M18 6L6 18" color={t.textSec} size={13} sw={2.2}/></Pressable>}
    </div>
  );
}

// ─── Icon button (round, toolbar) ───
function IconBtn({ icon, onClick, active, color, title, badge, size = 34 }) {
  const t = useTheme();
  const [hover, setHover] = useState(false);
  return (
    <Pressable onClick={onClick} scale={0.9}>
      <div title={title}
        onPointerEnter={() => setHover(true)} onPointerLeave={() => setHover(false)}
        style={{
          width: size, height: size, borderRadius: 9, position: 'relative',
          background: active ? t.accentSoft : (hover ? t.chip : 'transparent'),
          display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background 0.15s',
        }}>
        <Icon d={icon} color={active ? t.accent : (color || t.text)} size={18} sw={1.9}/>
        {badge > 0 && (
          <div style={{ position: 'absolute', top: 2, right: 2, minWidth: 15, height: 15, borderRadius: 8, background: t.red, color: '#fff', fontSize: 9.5, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '0 4px', boxShadow: `0 0 0 2px ${t.bg}` }}>{badge}</div>
        )}
      </div>
    </Pressable>
  );
}

// ─── Scroll area (page body) ───
function Scroll({ children, style, padding = 28 }) {
  return <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding, ...style }}>{children}</div>;
}

// ─── Section header within a page ───
function SectionTitle({ children, action, onAction, style }) {
  const t = useTheme();
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12, ...style }}>
      <div style={{ fontSize: 15, fontWeight: 700, color: t.text, letterSpacing: -0.2 }}>{children}</div>
      {action && <Pressable onClick={onAction}><div style={{ fontSize: 13, color: t.accent, fontWeight: 600 }}>{action}</div></Pressable>}
    </div>
  );
}

// ─── Detail row (label/value) ───
function DRow({ label, value, mono, color, multiline }) {
  const t = useTheme();
  return (
    <div style={{ display: 'flex', alignItems: multiline ? 'flex-start' : 'center', gap: 16, padding: '10px 0', borderBottom: `0.5px solid ${t.sep}` }}>
      <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500, width: 130, flexShrink: 0 }}>{label}</div>
      <div style={{ flex: 1, fontSize: 13.5, color: color || t.text, fontWeight: 600, textAlign: 'right', whiteSpace: multiline ? 'pre-line' : 'normal', fontVariantNumeric: mono ? 'tabular-nums' : 'normal' }}>{value}</div>
    </div>
  );
}

// ─── Empty state ───
function Empty({ icon, title, sub, action, onAction }) {
  const t = useTheme();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '60px 24px', textAlign: 'center', height: '100%' }}>
      <div style={{ width: 56, height: 56, borderRadius: 16, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
        <Icon d={icon || icons.folder} color={t.textSec} size={26} sw={1.6}/>
      </div>
      <div style={{ fontSize: 16, fontWeight: 700, color: t.text }}>{title}</div>
      {sub && <div style={{ fontSize: 13, color: t.textSec, marginTop: 5, maxWidth: 320, lineHeight: 1.5 }}>{sub}</div>}
      {action && <div style={{ marginTop: 18 }}><Button variant="accent" icon={icons.plus} onClick={onAction}>{action}</Button></div>}
    </div>
  );
}

// ─── Status dot+label ───
function StatusPill({ status }) {
  const m = statusMeta(status);
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 9.5, fontWeight: 700, color: m.color, padding: '2px 7px 2px 6px', borderRadius: 100, background: m.color + '1e', letterSpacing: 0.3, whiteSpace: 'nowrap' }}>
      <span style={{ width: 5, height: 5, borderRadius: 3, background: m.color }}/>{m.label}
    </span>
  );
}

// ─── Confirm dialog ───
function Confirm({ open, title, message, confirmLabel = 'Löschen', danger = true, onConfirm, onClose }) {
  const t = useTheme();
  return (
    <Sheet open={open} onClose={onClose} width={400}>
      <div style={{ padding: '6px 26px 24px' }}>
        <div style={{ fontSize: 18, fontWeight: 700, color: t.text }}>{title}</div>
        {message && <div style={{ fontSize: 13.5, color: t.textSec, marginTop: 8, lineHeight: 1.5 }}>{message}</div>}
        <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
          <Pressable onClick={onClose} scale={0.97} style={{ flex: 1 }}>
            <div style={{ padding: '11px 0', textAlign: 'center', borderRadius: 10, background: t.chip, color: t.text, fontSize: 14, fontWeight: 600 }}>Abbrechen</div>
          </Pressable>
          <Pressable onClick={() => { onConfirm(); onClose(); }} scale={0.97} style={{ flex: 1 }}>
            <div style={{ padding: '11px 0', textAlign: 'center', borderRadius: 10, background: danger ? t.red : t.accent, color: '#fff', fontSize: 14, fontWeight: 700 }}>{confirmLabel}</div>
          </Pressable>
        </div>
      </div>
    </Sheet>
  );
}

Object.assign(window, {
  Sheet, ToastContext, useToast, ToastHost,
  inp, Field, FormGroup, TextInput, Segmented, Toolbar, SearchField, IconBtn,
  Scroll, SectionTitle, DRow, Empty, StatusPill, Confirm,
});
