/* overlays.jsx — Shared Modal / Drawer / Popover primitives */
/* global React */

/* ── Modal ──────────────────────────────────────────────────────── */
function Modal({ open, onClose, title, subtitle, width = 560, children, footer }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(0,16,32,0.45)',
        backdropFilter: 'blur(6px)',
        WebkitBackdropFilter: 'blur(6px)',
        display: 'grid', placeItems: 'center',
        padding: 20,
        animation: 'modalFade .2s ease-out'
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: width,
          background: 'white',
          borderRadius: 18,
          boxShadow: '0 30px 80px rgba(0,16,32,0.32)',
          overflow: 'hidden',
          animation: 'modalRise .25s cubic-bezier(.2,.9,.3,1)',
          maxHeight: '88vh', display: 'flex', flexDirection: 'column'
        }}>
        {(title || subtitle) && (
          <div style={{ padding: '22px 24px 14px', borderBottom: '1px solid var(--line)' }}>
            <div className="row items-start justify-between gap-12">
              <div style={{ flex: 1 }}>
                {title && <div className="font-display bold" style={{ fontSize: 20, letterSpacing: '-0.02em' }}>{title}</div>}
                {subtitle && <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{subtitle}</div>}
              </div>
              <button onClick={onClose} aria-label="Close" style={{
                background: 'var(--bg-soft, #F5F7FA)', border: 0,
                width: 32, height: 32, borderRadius: 10,
                display: 'grid', placeItems: 'center',
                cursor: 'pointer', color: 'var(--ink-soft)',
                flexShrink: 0
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
              </button>
            </div>
          </div>
        )}
        <div style={{ padding: '20px 24px', overflow: 'auto', flex: 1 }}>{children}</div>
        {footer && (
          <div style={{ padding: '14px 20px', borderTop: '1px solid var(--line)', background: 'var(--bg-soft, #F5F7FA)' }}>
            {footer}
          </div>
        )}
      </div>
      <style>{`
        @keyframes modalFade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes modalRise { from { opacity: 0; transform: translateY(20px) scale(.97); } to { opacity: 1; transform: translateY(0) scale(1); } }
      `}</style>
    </div>
  );
}

/* ── Drawer (right-aligned slide-in) ────────────────────────────── */
function Drawer({ open, onClose, width = 480, children }) {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(0,16,32,0.4)',
        backdropFilter: 'blur(4px)',
        WebkitBackdropFilter: 'blur(4px)',
        animation: 'modalFade .2s ease-out',
        display: 'flex', justifyContent: 'flex-end'
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: '100%', maxWidth: width,
          height: '100vh',
          background: 'white',
          boxShadow: '-20px 0 60px rgba(0,16,32,0.18)',
          overflow: 'auto',
          animation: 'drawerSlide .3s cubic-bezier(.2,.9,.3,1)'
        }}>
        {children}
      </div>
      <style>{`@keyframes drawerSlide { from { transform: translateX(100%); } to { transform: translateX(0); } }`}</style>
    </div>
  );
}

/* ── Popover (anchored to a trigger, controlled) ────────────────── */
function Popover({ open, onClose, anchorRef, align = 'right', width = 280, children }) {
  const [pos, setPos] = React.useState({ top: 0, left: 0 });

  React.useEffect(() => {
    if (!open || !anchorRef?.current) return;
    const r = anchorRef.current.getBoundingClientRect();
    const top = r.bottom + 8 + window.scrollY;
    const left = align === 'right' ? r.right - width + window.scrollX : r.left + window.scrollX;
    setPos({ top, left });
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, anchorRef, align, width, onClose]);

  if (!open) return null;

  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 900 }} />
      <div
        style={{
          position: 'absolute',
          top: pos.top, left: pos.left,
          width,
          background: 'white',
          borderRadius: 14,
          boxShadow: '0 18px 40px rgba(0,16,32,0.18)',
          border: '1px solid var(--line)',
          zIndex: 901,
          animation: 'popoverIn .18s cubic-bezier(.2,.9,.3,1)',
          overflow: 'hidden'
        }}>
        {children}
      </div>
      <style>{`@keyframes popoverIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }`}</style>
    </>
  );
}

/* Toast — appears bottom-center, auto-dismisses */
function Toast({ open, onClose, kind = 'success', message, action }) {
  React.useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => onClose?.(), 4200);
    return () => clearTimeout(t);
  }, [open, onClose]);
  if (!open) return null;
  const colors = {
    success: { bg: 'var(--ink)', accent: '#79FEE7' },
    info:    { bg: 'var(--ink)', accent: '#009CFF' },
    warning: { bg: 'var(--ink)', accent: '#FEE960' },
  };
  const c = colors[kind] || colors.success;
  return (
    <div style={{
      position: 'fixed', bottom: 24, left: '50%',
      transform: 'translateX(-50%)',
      background: c.bg, color: 'white',
      padding: '12px 16px',
      borderRadius: 14,
      boxShadow: '0 18px 40px rgba(0,16,32,0.32)',
      zIndex: 1100,
      display: 'flex', alignItems: 'center', gap: 12,
      fontSize: 13, fontWeight: 600,
      animation: 'toastIn .3s cubic-bezier(.2,.9,.3,1)',
      maxWidth: 520
    }}>
      <span style={{ width: 8, height: 8, borderRadius: 999, background: c.accent, boxShadow: `0 0 12px ${c.accent}` }} />
      <span style={{ flex: 1 }}>{message}</span>
      {action && (
        <button onClick={action.onClick} style={{
          background: 'rgba(255,255,255,0.14)', border: 0,
          color: 'white', padding: '6px 12px', borderRadius: 8,
          fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit'
        }}>{action.label}</button>
      )}
      <button onClick={onClose} aria-label="Dismiss" style={{
        background: 'transparent', border: 0, color: 'rgba(255,255,255,0.6)',
        padding: 4, cursor: 'pointer', display: 'grid', placeItems: 'center'
      }}>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12" /></svg>
      </button>
      <style>{`@keyframes toastIn { from { opacity: 0; transform: translate(-50%, 10px); } to { opacity: 1; transform: translate(-50%, 0); } }`}</style>
    </div>
  );
}

Object.assign(window, { Modal, Drawer, Popover, Toast });
