// aerOS — overlays: Toast, Modal, ConfirmDialog, Sheet. Exports to window.
const { useState: _uS, useEffect: _uE, useCallback: _uC, useRef: _uR } = React;

/* ----------------------------- Toast ----------------------------- */
const ToastCtx = React.createContext(null);
function useToast() { return React.useContext(ToastCtx); }

function ToastProvider({ children }) {
  const [toasts, setToasts] = _uS([]);
  const push = _uC((t) => {
    const id = Math.random().toString(36).slice(2);
    setToasts(ts => [...ts, { id, tone: 'ok', ...t }]);
    setTimeout(() => setToasts(ts => ts.filter(x => x.id !== id)), t.duration || 3200);
  }, []);
  const api = React.useMemo(() => ({
    push,
    ok: (msg, title) => push({ tone: 'ok', msg, title }),
    error: (msg, title) => push({ tone: 'danger', msg, title }),
    info: (msg, title) => push({ tone: 'info', msg, title }),
    warn: (msg, title) => push({ tone: 'warn', msg, title }),
  }), [push]);
  const icons = { ok: Icon.checkCircle, danger: Icon.alert, info: Icon.info, warn: Icon.alert };
  return (
    <ToastCtx.Provider value={api}>
      {children}
      <div style={{ position: 'fixed', bottom: 20, right: 20, display: 'flex', flexDirection: 'column', gap: 10, zIndex: 9000, maxWidth: 360 }}>
        {toasts.map(t => (
          <div key={t.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 11, padding: '13px 15px', background: 'var(--bg-0)', border: '1px solid var(--border)', borderLeft: `3px solid var(--${t.tone})`, borderRadius: 'var(--r-sm)', boxShadow: 'var(--shadow-lg)', animation: 'ds-toast-in 200ms ease', minWidth: 260 }}>
            <span style={{ color: `var(--${t.tone})`, display: 'flex', flexShrink: 0, marginTop: 1 }}>{icons[t.tone]({ size: 18 })}</span>
            <div style={{ flex: 1, minWidth: 0 }}>
              {t.title && <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--fg-1)' }}>{t.title}</div>}
              {t.msg && <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: t.title ? 2 : 0 }}>{t.msg}</div>}
            </div>
            <button onClick={() => setToasts(ts => ts.filter(x => x.id !== t.id))} style={{ background: 'none', border: 'none', color: 'var(--fg-3)', cursor: 'pointer', display: 'flex', padding: 0 }}>{Icon.x({ size: 15 })}</button>
          </div>
        ))}
      </div>
    </ToastCtx.Provider>
  );
}

/* ----------------------------- Modal ----------------------------- */
function Modal({ open, onClose, title, subtitle, children, footer, width = 560, icon }) {
  _uE(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onMouseDown={e => { if (e.target === e.currentTarget) onClose && onClose(); }}
      style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', backdropFilter: 'blur(2px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 8000, padding: 20, animation: 'ds-fade-in 150ms ease' }}>
      <div role="dialog" aria-modal="true" style={{ width, maxWidth: '100%', maxHeight: '90vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-0)', borderRadius: 'var(--r-md)', boxShadow: 'var(--shadow-lg)', border: '1px solid var(--border)', animation: 'ds-slide-up 200ms ease', overflow: 'hidden' }}>
        {title && (
          <header style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
            {icon && <span style={{ width: 36, height: 36, borderRadius: 'var(--r-sm)', background: 'var(--brand-soft)', color: 'var(--brand)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{typeof icon === 'function' ? icon({ size: 19 }) : icon}</span>}
            <div style={{ flex: 1, minWidth: 0 }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)' }}>{title}</h3>
              {subtitle && <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 2 }}>{subtitle}</div>}
            </div>
            <IconButton icon={Icon.x} onClick={onClose} title="Kapat" />
          </header>
        )}
        <div style={{ padding: 22, overflowY: 'auto', flex: 1 }}>{children}</div>
        {footer && <footer style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 10, background: 'var(--bg-2)' }}>{footer}</footer>}
      </div>
    </div>
  );
}

/* ----------------------------- Sheet (side drawer) ----------------------------- */
function Sheet({ open, onClose, title, subtitle, children, footer, width = 460, side = 'right' }) {
  _uE(() => {
    if (!open) return;
    const onKey = e => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return (
    <div onMouseDown={e => { if (e.target === e.currentTarget) onClose && onClose(); }}
      style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', backdropFilter: 'blur(2px)', display: 'flex', justifyContent: side === 'right' ? 'flex-end' : 'flex-start', zIndex: 8000, animation: 'ds-fade-in 150ms ease' }}>
      <div style={{ width, maxWidth: '100%', height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--bg-0)', boxShadow: 'var(--shadow-lg)', borderLeft: side === 'right' ? '1px solid var(--border)' : 'none', animation: `ds-sheet-in 240ms cubic-bezier(0.16,1,0.3,1)` }}>
        <header style={{ padding: '18px 22px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <h3 style={{ fontSize: 16, fontWeight: 600, color: 'var(--fg-1)' }}>{title}</h3>
            {subtitle && <div style={{ fontSize: 12.5, color: 'var(--fg-3)', marginTop: 2 }}>{subtitle}</div>}
          </div>
          <IconButton icon={Icon.x} onClick={onClose} title="Kapat" />
        </header>
        <div style={{ padding: 22, overflowY: 'auto', flex: 1 }}>{children}</div>
        {footer && <footer style={{ padding: '14px 22px', borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 10, background: 'var(--bg-2)' }}>{footer}</footer>}
      </div>
    </div>
  );
}

/* ----------------------------- ConfirmDialog ----------------------------- */
function ConfirmDialog({ open, onClose, onConfirm, title, message, confirmLabel = 'Onayla', cancelLabel = 'Vazgeç', tone = 'danger' }) {
  return (
    <Modal open={open} onClose={onClose} width={420}>
      <div style={{ display: 'flex', gap: 14 }}>
        <span style={{ width: 42, height: 42, borderRadius: 'var(--r-sm)', background: `var(--${tone}-soft)`, color: `var(--${tone})`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{Icon.alert({ size: 21 })}</span>
        <div style={{ flex: 1 }}>
          <h3 style={{ fontSize: 16, fontWeight: 600, marginBottom: 6 }}>{title}</h3>
          <p style={{ fontSize: 13.5, color: 'var(--fg-2)', margin: 0, lineHeight: 1.5 }}>{message}</p>
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 22 }}>
            <Button variant="ghost" onClick={onClose}>{cancelLabel}</Button>
            <Button variant={tone === 'danger' ? 'danger' : 'primary'} onClick={() => { onConfirm(); onClose(); }}>{confirmLabel}</Button>
          </div>
        </div>
      </div>
    </Modal>
  );
}

const _sheetKeyframes = document.createElement('style');
_sheetKeyframes.textContent = '@keyframes ds-sheet-in { from { transform: translateX(100%); } to { transform: translateX(0); } }';
document.head.appendChild(_sheetKeyframes);

Object.assign(window, { ToastProvider, useToast, Modal, Sheet, ConfirmDialog });
