/* ===================================================================
   KabelFlux v5 — UI Primitives
   - Touch targets ≥32px (≥44px on coarse pointers) — C1 fix
   - Focus rings + aria-labels — C2/C3 fix
   - AsyncButton with busy state — H4 fix
   - Reusable EmptyState — H3 fix
   - Confirm modal — C5 fix
   =================================================================== */
const { useState, useEffect, useRef, useCallback, useMemo, createContext, useContext } = React;

/* ---------- Button ---------- */
const Btn = React.forwardRef(({ kind='ghost', size='md', icon, iconRight, children, busy, disabled, ariaLabel, fullWidth, style, className, ...rest }, ref) => {
  const cls = `kf-btn kf-btn-${kind} kf-btn-${size}` + (fullWidth ? ' kf-btn-full' : '') + (className ? ' '+className : '');
  return (
    <button
      ref={ref}
      className={cls}
      disabled={disabled || busy}
      aria-label={ariaLabel || (typeof children === 'string' ? undefined : 'button')}
      aria-busy={busy || undefined}
      style={style}
      {...rest}
    >
      {busy ? <Spinner size={size === 'sm' ? 12 : 14}/> : (icon && <Icon name={icon} size={size === 'sm' ? 14 : 16}/>)}
      {children && <span className="kf-btn-label">{children}</span>}
      {iconRight && !busy && <Icon name={iconRight} size={size === 'sm' ? 14 : 16}/>}
    </button>
  );
});

/* ---------- AsyncButton: H4 fix ---------- */
const AsyncBtn = ({ onClick, busyLabel='Working…', children, ...rest }) => {
  const [busy, setBusy] = useState(false);
  const [origLabel] = useState(children);
  const handle = async (e) => {
    if (busy) return;
    setBusy(true);
    try { await onClick(e); }
    finally { setBusy(false); }
  };
  return <Btn {...rest} onClick={handle} busy={busy}>{busy ? busyLabel : origLabel}</Btn>;
};

/* ---------- Spinner ---------- */
const Spinner = ({ size=14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" style={{ animation: 'spin 0.8s linear infinite' }} aria-hidden="true">
    <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="2.5" opacity=".22" fill="none"/>
    <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
  </svg>
);

/* ---------- Chip ---------- */
const Chip = ({ tone='neutral', size='md', icon, children, onClick, active, dot, ariaLabel, ...rest }) => {
  const cls = `kf-chip kf-chip-${tone} kf-chip-${size}` + (active ? ' on' : '') + (onClick ? ' clickable' : '');
  return (
    <span className={cls} role={onClick ? 'button' : undefined} tabIndex={onClick ? 0 : undefined}
          onClick={onClick}
          onKeyDown={onClick ? e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onClick(e); } } : undefined}
          aria-label={ariaLabel} {...rest}>
      {dot && <span className="kf-chip-dot"/>}
      {icon && <Icon name={icon} size={12}/>}
      {children}
    </span>
  );
};

/* ---------- Kbd ---------- */
const Kbd = ({ children }) => <kbd className="kf-kbd">{children}</kbd>;

/* ---------- Tooltip ---------- */
const Tip = ({ label, side='top', children }) => (
  <span className={`kf-tip kf-tip-${side}`} data-tip={label}>{children}</span>
);

/* ---------- Empty state (H3 fix) ---------- */
const EmptyState = ({ icon='folder', title, hint, action, secondary, compact }) => (
  <div className={`kf-empty ${compact ? 'kf-empty-compact' : ''}`}>
    <div className="kf-empty-icon">
      <Icon name={icon} size={compact ? 28 : 36} stroke="var(--t-3)"/>
    </div>
    <div className="kf-empty-title">{title}</div>
    {hint && <div className="kf-empty-hint">{hint}</div>}
    {(action || secondary) && (
      <div className="kf-empty-actions">
        {action}
        {secondary}
      </div>
    )}
  </div>
);

/* ---------- Toast ---------- */
const ToastCtx = createContext(null);
const ToastProvider = ({ children }) => {
  const [list, setList] = useState([]);
  const push = useCallback((kind, msg, hint) => {
    const id = Math.random().toString(36).slice(2);
    setList(l => [...l, { id, kind, msg, hint }]);
    setTimeout(() => setList(l => l.filter(t => t.id !== id)), 4200);
  }, []);
  const api = useMemo(() => ({
    ok:   (m, h) => push('ok',   m, h),
    err:  (m, h) => push('err',  m, h),
    info: (m, h) => push('info', m, h),
    warn: (m, h) => push('warn', m, h),
  }), [push]);
  return (
    <ToastCtx.Provider value={api}>
      {children}
      <div className="kf-toast-wrap" role="status" aria-live="polite">
        {list.map(t => (
          <div key={t.id} className={`kf-toast kf-toast-${t.kind}`}>
            <Icon name={t.kind === 'ok' ? 'ok' : t.kind === 'err' ? 'err' : t.kind === 'warn' ? 'warn' : 'info'} size={16}/>
            <div className="kf-toast-text">
              <div className="kf-toast-msg">{t.msg}</div>
              {t.hint && <div className="kf-toast-hint">{t.hint}</div>}
            </div>
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
};
const useToast = () => useContext(ToastCtx);

/* ---------- Modal w/ confirm (C5 fix) ---------- */
const Modal = ({ title, onClose, children, footer, size='md', tone='neutral' }) => {
  useEffect(() => {
    const fn = e => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', fn);
    return () => document.removeEventListener('keydown', fn);
  }, [onClose]);
  return (
    <div className="kf-modal-backdrop fade-in" onClick={onClose} role="dialog" aria-modal="true" aria-label={title}>
      <div className={`kf-modal kf-modal-${size}`} onClick={e => e.stopPropagation()}>
        <div className={`kf-modal-head kf-modal-head-${tone}`}>
          <div className="kf-modal-title">{title}</div>
          <button className="kf-iconbtn" onClick={onClose} aria-label="Close dialog"><Icon name="x" size={16}/></button>
        </div>
        <div className="kf-modal-body">{children}</div>
        {footer && <div className="kf-modal-foot">{footer}</div>}
      </div>
    </div>
  );
};

const ConfirmModal = ({ title, body, danger, confirmLabel='Confirm', cancelLabel='Cancel', onConfirm, onClose }) => (
  <Modal title={title} onClose={onClose} size="sm" tone={danger ? 'danger' : 'neutral'} footer={
    <>
      <Btn kind="ghost" onClick={onClose}>{cancelLabel}</Btn>
      <Btn kind={danger ? 'danger' : 'primary'} onClick={() => { onConfirm(); onClose(); }} icon={danger ? 'trash' : 'check'}>{confirmLabel}</Btn>
    </>
  }>
    <div className="kf-confirm-body">{body}</div>
  </Modal>
);

/* ---------- IconButton (with accessible name — C3 fix) ---------- */
const IconBtn = ({ icon, label, size=14, active, danger, onClick, ...rest }) => (
  <button className={`kf-iconbtn ${active ? 'on' : ''} ${danger ? 'danger' : ''}`} onClick={onClick} aria-label={label} title={label} {...rest}>
    <Icon name={icon} size={size}/>
  </button>
);

/* ---------- Inline-edit cell (M4 fix — save flash) ---------- */
const InlineCell = ({ value, onSave, type='text', options, width, align='left', mono }) => {
  const [editing, setEditing] = useState(false);
  const [v, setV] = useState(value);
  const [flash, setFlash] = useState(null); // 'ok' | 'err' | null
  const ref = useRef();
  useEffect(() => { setV(value); }, [value]);
  useEffect(() => { if (editing && ref.current) { ref.current.focus(); if (ref.current.select) ref.current.select(); } }, [editing]);

  const commit = async () => {
    if (v === value) { setEditing(false); return; }
    try {
      await onSave(v);
      setEditing(false);
      setFlash('ok');
      setTimeout(() => setFlash(null), 1100);
    } catch (e) {
      setFlash('err');
      setTimeout(() => setFlash(null), 400);
    }
  };

  const cls = 'kf-cell' + (editing ? ' editing' : '') + (mono ? ' mono' : '') + (flash === 'ok' ? ' flash-save' : '') + (flash === 'err' ? ' shake-err' : '');

  if (editing) {
    if (type === 'select') {
      return (
        <td className={cls} style={{ width, textAlign: align }}>
          <select ref={ref} className="kf-cell-input" value={v} onChange={e => setV(e.target.value)} onBlur={commit}
                  onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') { setV(value); setEditing(false); } }}>
            {options.map(o => <option key={o} value={o}>{o}</option>)}
          </select>
        </td>
      );
    }
    return (
      <td className={cls} style={{ width, textAlign: align }}>
        <input ref={ref} className="kf-cell-input" value={v}
               onChange={e => setV(type === 'number' ? +e.target.value : e.target.value)}
               onBlur={commit}
               onKeyDown={e => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') { setV(value); setEditing(false); } }}/>
      </td>
    );
  }
  return (
    <td className={cls} style={{ width, textAlign: align }} onClick={() => setEditing(true)} tabIndex={0}
        onKeyDown={e => { if (e.key === 'Enter' || e.key === 'F2') setEditing(true); }}>
      {value}
    </td>
  );
};

/* ---------- Dropdown menu ---------- */
const Menu = ({ anchor, onClose, children, align='left', width=220 }) => {
  const ref = useRef();
  useEffect(() => {
    const click = e => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    document.addEventListener('mousedown', click);
    document.addEventListener('keydown', e => { if (e.key === 'Escape') onClose(); });
    return () => document.removeEventListener('mousedown', click);
  }, [onClose]);
  return (
    <div ref={ref} className="kf-menu fade-in" style={{ [align]: 0, width }}>
      {children}
    </div>
  );
};
const MenuItem = ({ icon, label, hint, onClick, danger, disabled, kbd, children }) => (
  <button className={`kf-menu-item ${danger ? 'danger' : ''}`} onClick={onClick} disabled={disabled}>
    {icon && <Icon name={icon} size={14}/>}
    <div className="kf-menu-item-text">
      <div className="kf-menu-item-label">{label}</div>
      {hint && <div className="kf-menu-item-hint">{hint}</div>}
    </div>
    {kbd && <span className="kf-menu-item-kbd">{kbd}</span>}
    {children}
  </button>
);
const MenuLabel = ({ children }) => <div className="kf-menu-label">{children}</div>;
const MenuSep   = () => <div className="kf-menu-sep"/>;

/* ============================================================
   Inject all component CSS (kept in JS so primitives ship together)
   ============================================================ */
const STYLE = `
/* Touch targets ≥32 (≥44 on coarse) — C1 fix */
.kf-btn {
  --h: 32px;
  display: inline-flex; align-items: center; justify-content: center;
  gap: 6px;
  height: var(--h); min-width: var(--h);
  padding: 0 12px;
  font-family: var(--f-sans);
  font-size: 12.5px; font-weight: 600;
  border-radius: var(--r-2);
  border: 1px solid transparent;
  background: transparent; color: var(--t-1);
  cursor: pointer;
  transition: background .12s var(--ease), border-color .12s var(--ease), color .12s var(--ease), transform .08s var(--ease);
  white-space: nowrap;
  user-select: none;
}
.kf-btn-sm { --h: 26px; font-size: 11.5px; padding: 0 9px; gap: 5px; }
.kf-btn-lg { --h: 40px; font-size: 13.5px; padding: 0 16px; }
.kf-btn-full { width: 100%; }
.kf-btn-label { line-height: 1; }
.kf-btn:disabled { opacity: .42; cursor: not-allowed; }
.kf-btn:active:not(:disabled) { transform: translateY(1px); }

.kf-btn-primary { background: var(--accent); color: #fff; }
.kf-btn-primary:hover:not(:disabled) { filter: brightness(1.08); }

.kf-btn-secondary { background: var(--bg-3); color: var(--t-1); border-color: var(--line-strong); }
.kf-btn-secondary:hover:not(:disabled) { background: var(--bg-4); }

.kf-btn-ghost { color: var(--t-2); }
.kf-btn-ghost:hover:not(:disabled) { background: var(--bg-3); color: var(--t-1); }

.kf-btn-soft { background: var(--info-soft); color: var(--info); }
.kf-btn-soft:hover:not(:disabled) { background: rgba(74,158,255,.22); }

.kf-btn-success { background: var(--success); color: #002a23; }
.kf-btn-success:hover:not(:disabled) { filter: brightness(1.08); }

.kf-btn-danger  { background: transparent; color: var(--danger); border-color: rgba(239,78,78,.4); }
.kf-btn-danger:hover:not(:disabled)  { background: var(--danger); color: #fff; border-color: var(--danger); }

.kf-btn-outline { color: var(--t-1); border-color: var(--line-strong); background: transparent; }
.kf-btn-outline:hover:not(:disabled) { background: var(--bg-3); border-color: var(--t-3); }

@media (pointer: coarse) {
  .kf-btn { --h: 44px; font-size: 14px; }
  .kf-btn-sm { --h: 36px; }
}

/* Icon button */
.kf-iconbtn {
  display: inline-flex; align-items: center; justify-content: center;
  width: 28px; height: 28px;
  border-radius: var(--r-2);
  background: transparent;
  border: 1px solid transparent;
  color: var(--t-2);
  cursor: pointer;
  transition: all .12s var(--ease);
}
.kf-iconbtn:hover { background: var(--bg-3); color: var(--t-1); }
.kf-iconbtn.on    { background: var(--info-soft); color: var(--info); }
.kf-iconbtn.danger:hover { background: rgba(239,78,78,.12); color: var(--danger); }
@media (pointer: coarse) { .kf-iconbtn { width: 40px; height: 40px; } }

/* Chip */
.kf-chip {
  display: inline-flex; align-items: center; gap: 5px;
  padding: 2px 9px;
  height: 22px;
  font-size: 11px; font-weight: 600;
  border-radius: var(--r-pill);
  background: var(--bg-3);
  color: var(--t-2);
  border: 1px solid var(--line);
  letter-spacing: .2px;
  white-space: nowrap;
}
.kf-chip-sm { height: 18px; font-size: 10px; padding: 0 7px; }
.kf-chip-lg { height: 28px; font-size: 12px; padding: 4px 12px; }
.kf-chip.clickable { cursor: pointer; transition: all .12s var(--ease); }
.kf-chip.clickable:hover { background: var(--bg-4); }
.kf-chip.on { background: var(--info-soft); color: var(--info); border-color: rgba(74,158,255,.4); }
.kf-chip-info    { background: var(--info-soft);    color: var(--info);    border-color: rgba(74,158,255,.3); }
.kf-chip-success { background: var(--success-soft); color: var(--success); border-color: rgba(0,212,170,.3); }
.kf-chip-warning { background: var(--warning-soft); color: var(--warning); border-color: rgba(245,166,35,.35); }
.kf-chip-danger  { background: rgba(239,78,78,.16); color: var(--danger);  border-color: rgba(239,78,78,.3); }
.kf-chip-violet  { background: rgba(167,139,250,.16); color: var(--violet); border-color: rgba(167,139,250,.3); }
.kf-chip-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }

/* Kbd */
.kf-kbd {
  font-family: var(--f-mono); font-size: 10.5px;
  background: var(--bg-3); color: var(--t-2);
  padding: 1px 6px;
  border-radius: 4px;
  border: 1px solid var(--line-strong);
  border-bottom-width: 2px;
  box-shadow: 0 1px 0 rgba(0,0,0,.3);
  display: inline-block;
  line-height: 1.4;
}

/* Tooltip */
.kf-tip { position: relative; display: inline-flex; }
.kf-tip::after {
  content: attr(data-tip);
  position: absolute;
  bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%) translateY(2px);
  background: var(--bg-5); color: var(--t-1);
  padding: 4px 8px; border-radius: 4px;
  font-size: 11px; font-weight: 500;
  white-space: nowrap;
  pointer-events: none; opacity: 0;
  transition: opacity .15s var(--ease), transform .15s var(--ease);
  z-index: var(--z-tooltip);
  border: 1px solid var(--line-strong);
  box-shadow: 0 4px 14px rgba(0,0,0,.4);
}
/* Bottom variant — for tooltips near the top of the viewport (topbar icons)
   so they don't clip off-screen above the header. */
.kf-tip-bottom::after {
  bottom: auto; top: calc(100% + 6px);
  transform: translateX(-50%) translateY(-2px);
}
.kf-tip-left::after {
  bottom: auto; top: 50%; left: auto; right: calc(100% + 6px);
  transform: translateY(-50%) translateX(2px);
}
.kf-tip-right::after {
  bottom: auto; top: 50%; left: calc(100% + 6px);
  transform: translateY(-50%) translateX(-2px);
}
@media (hover: hover) {
  .kf-tip:hover::after { opacity: 1; transform: translateX(-50%) translateY(0); }
  .kf-tip-bottom:hover::after { transform: translateX(-50%) translateY(0); }
  .kf-tip-left:hover::after,
  .kf-tip-right:hover::after { transform: translateY(-50%) translateX(0); }
}

/* Empty state */
.kf-empty {
  display: flex; flex-direction: column; align-items: center;
  text-align: center;
  padding: 56px 24px;
  gap: 14px;
  max-width: 460px; margin: 0 auto;
}
.kf-empty-compact { padding: 30px 20px; }
.kf-empty-icon {
  width: 64px; height: 64px;
  display: flex; align-items: center; justify-content: center;
  background: var(--bg-3);
  border: 1px solid var(--line);
  border-radius: 50%;
}
.kf-empty-compact .kf-empty-icon { width: 48px; height: 48px; }
.kf-empty-title { font-size: 16px; font-weight: 700; color: var(--t-1); }
.kf-empty-compact .kf-empty-title { font-size: 14px; }
.kf-empty-hint { font-size: 13px; color: var(--t-3); max-width: 380px; line-height: 1.5; }
.kf-empty-compact .kf-empty-hint { font-size: 12px; }
.kf-empty-actions { display: flex; gap: 8px; margin-top: 6px; }

/* Toast */
.kf-toast-wrap {
  position: fixed; bottom: 32px; right: 18px;
  display: flex; flex-direction: column; gap: 8px;
  z-index: var(--z-toast); pointer-events: none;
}
.kf-toast {
  pointer-events: auto;
  display: flex; align-items: flex-start; gap: 10px;
  padding: 10px 14px; min-width: 280px;
  background: var(--bg-3); border: 1px solid var(--line-strong);
  border-radius: var(--r-3);
  box-shadow: 0 8px 32px rgba(0,0,0,.5);
  animation: fade-in .2s var(--ease);
}
.kf-toast-ok    { border-left: 3px solid var(--success); color: var(--success); }
.kf-toast-err   { border-left: 3px solid var(--danger);  color: var(--danger); }
.kf-toast-warn  { border-left: 3px solid var(--warning); color: var(--warning); }
.kf-toast-info  { border-left: 3px solid var(--info);    color: var(--info); }
.kf-toast-text  { color: var(--t-1); font-size: 12.5px; line-height: 1.35; }
.kf-toast-msg   { font-weight: 600; }
.kf-toast-hint  { font-size: 11px; color: var(--t-3); margin-top: 2px; }

/* Modal */
.kf-modal-backdrop {
  position: fixed; inset: 0;
  background: rgba(7,9,15,.72);
  backdrop-filter: blur(4px) saturate(.6);
  display: flex; align-items: center; justify-content: center;
  z-index: var(--z-modal-backdrop);
  padding: 24px;
}
.kf-modal {
  background: var(--bg-2);
  border: 1px solid var(--line-strong);
  border-radius: var(--r-5);
  width: 560px; max-width: 100%; max-height: 90vh;
  display: flex; flex-direction: column;
  box-shadow: 0 24px 80px rgba(0,0,0,.7);
  z-index: var(--z-modal);
  overflow: hidden;
}
.kf-modal-sm { width: 420px; }
.kf-modal-lg { width: 780px; }
.kf-modal-xl { width: 1100px; }
.kf-modal-head {
  display: flex; align-items: center; justify-content: space-between;
  padding: 14px 18px; border-bottom: 1px solid var(--line);
}
.kf-modal-head-danger  { background: linear-gradient(180deg, rgba(239,78,78,.12), transparent); }
.kf-modal-head-warning { background: linear-gradient(180deg, rgba(245,166,35,.12), transparent); }
.kf-modal-title { font-size: 14px; font-weight: 700; color: var(--t-1); letter-spacing: .1px; }
.kf-modal-body { padding: 18px; overflow-y: auto; font-size: 13px; color: var(--t-2); line-height: 1.55; }
.kf-modal-foot { padding: 12px 16px; border-top: 1px solid var(--line); display: flex; gap: 8px; justify-content: flex-end; background: var(--bg-1); }
.kf-confirm-body { font-size: 13px; color: var(--t-2); }
.kf-confirm-body b { color: var(--t-1); }

/* Menu */
.kf-menu {
  position: absolute; top: calc(100% + 6px);
  background: var(--bg-2);
  border: 1px solid var(--line-strong);
  border-radius: var(--r-3);
  padding: 5px;
  box-shadow: 0 12px 40px rgba(0,0,0,.55);
  z-index: var(--z-dropdown);
  min-width: 200px;
}
.kf-menu-item {
  display: flex; align-items: center; gap: 10px;
  width: 100%;
  padding: 7px 9px;
  background: transparent; border: none;
  color: var(--t-1); text-align: left;
  border-radius: var(--r-2);
  cursor: pointer;
  font-family: var(--f-sans);
  font-size: 12px;
  transition: background .1s var(--ease);
}
.kf-menu-item:hover:not(:disabled) { background: var(--bg-3); }
.kf-menu-item:disabled { opacity: .4; cursor: not-allowed; }
.kf-menu-item.danger { color: var(--danger); }
.kf-menu-item.danger:hover { background: rgba(239,78,78,.12); }
.kf-menu-item-text { flex: 1; min-width: 0; }
.kf-menu-item-label { font-weight: 500; }
.kf-menu-item-hint { font-size: 10.5px; color: var(--t-3); margin-top: 1px; }
.kf-menu-item-kbd { font-family: var(--f-mono); font-size: 10.5px; color: var(--t-3); }
.kf-menu-label { font-size: 9.5px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; color: var(--t-3); padding: 7px 9px 4px; }
.kf-menu-sep { height: 1px; background: var(--line); margin: 4px 0; }

/* Inline cell */
.kf-cell {
  cursor: text;
  position: relative;
  transition: background .12s var(--ease);
}
.kf-cell:hover { background: rgba(74,158,255,.04); }
.kf-cell.mono { font-family: var(--f-mono); font-variant-numeric: tabular-nums; }
.kf-cell.editing { padding: 0 !important; background: var(--bg-1); }
.kf-cell-input {
  width: 100%; height: 100%;
  background: transparent; border: none; outline: none;
  color: var(--t-1);
  font: inherit;
  padding: 4px 8px;
}

@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
`;

const styleEl = document.createElement('style');
styleEl.textContent = STYLE;
document.head.appendChild(styleEl);

Object.assign(window, { Btn, AsyncBtn, Chip, Kbd, Tip, EmptyState, ToastProvider, useToast, Modal, ConfirmModal, IconBtn, InlineCell, Menu, MenuItem, MenuLabel, MenuSep, Spinner });
