/* ============================================================
   F2 UI — Feedback & overlays library
   Alert · Banner · Toast (+useToaster, ToastViewport) · Tooltip ·
   Popover · Modal · Drawer
   ============================================================ */
(function () {
  const { Icon, IconButton } = window.F2;
  const { useDismiss } = window.SB;

  const TONES = {
    info: { fg: 'var(--f2-accent-text)', bd: 'var(--f2-accent-border)', bg: 'var(--f2-surface-accent)', icon: 'Info' },
    neutral: { fg: 'var(--f2-text-secondary)', bd: 'var(--f2-border-strong)', bg: 'var(--f2-surface-card)', icon: 'Info' },
    success: { fg: 'var(--f2-success)', bd: 'rgba(79,168,115,0.4)', bg: 'rgba(79,168,115,0.12)', icon: 'CheckCircle2' },
    warning: { fg: 'var(--f2-warning)', bd: 'rgba(224,179,65,0.4)', bg: 'rgba(224,179,65,0.12)', icon: 'TriangleAlert' },
    error: { fg: 'var(--f2-error)', bd: 'rgba(216,92,87,0.4)', bg: 'rgba(216,92,87,0.12)', icon: 'OctagonAlert' },
  };

  /* ====================== Alert ====================== */
  function Alert({ tone = 'info', title, children, onClose, action, icon = true, style = {} }) {
    const t = TONES[tone] || TONES.info;
    return (
      <div role={tone === 'error' || tone === 'warning' ? 'alert' : 'status'} style={{
        display: 'flex', gap: 12, padding: '14px 16px', background: t.bg, border: `1px solid ${t.bd}`,
        borderRadius: 'var(--f2-radius-md)', ...style,
      }}>
        {icon && <span style={{ color: t.fg, flex: '0 0 auto', marginTop: 1 }}><Icon name={t.icon} size={18} /></span>}
        <div style={{ flex: 1, minWidth: 0 }}>
          {title && <div style={{ fontFamily: 'var(--f2-font-display)', fontWeight: 600, fontSize: 15, color: 'var(--f2-text)', marginBottom: children ? 4 : 0 }}>{title}</div>}
          {children && <div style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--f2-text-secondary)' }}>{children}</div>}
          {action && <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>{action}</div>}
        </div>
        {onClose && <button aria-label="Dismiss" onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--f2-text-muted)', cursor: 'pointer', display: 'inline-flex', flex: '0 0 auto' }}><Icon name="X" size={16} /></button>}
      </div>
    );
  }

  /* ====================== Banner ====================== */
  function Banner({ tone = 'info', children, action, onClose, icon = true, style = {} }) {
    const t = TONES[tone] || TONES.info;
    return (
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px', width: '100%',
        background: t.bg, borderBottom: `1px solid ${t.bd}`, ...style,
      }}>
        {icon && <span style={{ color: t.fg, display: 'inline-flex', flex: '0 0 auto' }}><Icon name={t.icon} size={17} /></span>}
        <div style={{ flex: 1, fontSize: 14, color: 'var(--f2-text)', lineHeight: 1.45 }}>{children}</div>
        {action}
        {onClose && <button aria-label="Dismiss" onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--f2-text-muted)', cursor: 'pointer', display: 'inline-flex' }}><Icon name="X" size={16} /></button>}
      </div>
    );
  }

  /* ====================== Toast ====================== */
  function Toast({ tone = 'neutral', title, message, onClose, style = {} }) {
    const t = TONES[tone] || TONES.neutral;
    return (
      <div role="status" style={{
        display: 'flex', gap: 11, alignItems: 'flex-start', width: 340, maxWidth: '100%', padding: '13px 14px',
        background: 'var(--f2-surface-card)', border: '1px solid var(--f2-border-strong)', borderLeft: `2px solid ${t.fg}`,
        borderRadius: 'var(--f2-radius-control)', boxShadow: 'var(--f2-elevation-overlay)', ...style,
      }}>
        <span style={{ color: t.fg, flex: '0 0 auto', marginTop: 1 }}><Icon name={t.icon} size={17} /></span>
        <div style={{ flex: 1, minWidth: 0 }}>
          {title && <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--f2-text)' }}>{title}</div>}
          {message && <div style={{ fontSize: 13.5, color: 'var(--f2-text-muted)', marginTop: title ? 2 : 0, lineHeight: 1.45 }}>{message}</div>}
        </div>
        {onClose && <button aria-label="Dismiss" onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--f2-text-faint)', cursor: 'pointer', display: 'inline-flex' }}><Icon name="X" size={15} /></button>}
      </div>
    );
  }

  function useToaster(defaultTimeout = 4000) {
    const [toasts, setToasts] = React.useState([]);
    const dismiss = React.useCallback((id) => setToasts((ts) => ts.filter((t) => t.id !== id)), []);
    const push = React.useCallback((t) => {
      const id = Math.random().toString(36).slice(2);
      setToasts((ts) => [...ts, { ...t, id }]);
      if (t.timeout !== 0) setTimeout(() => dismiss(id), t.timeout || defaultTimeout);
      return id;
    }, [defaultTimeout, dismiss]);
    return { toasts, push, dismiss };
  }

  function ToastViewport({ toasts, onDismiss, placement = 'bottom-right', contained = false }) {
    const pos = {
      'bottom-right': { bottom: 16, right: 16, alignItems: 'flex-end' },
      'bottom-left': { bottom: 16, left: 16, alignItems: 'flex-start' },
      'top-right': { top: 16, right: 16, alignItems: 'flex-end' },
      'top-left': { top: 16, left: 16, alignItems: 'flex-start' },
    }[placement];
    return (
      <div aria-live="polite" style={{ position: contained ? 'absolute' : 'fixed', zIndex: 200, display: 'flex', flexDirection: 'column', gap: 10, pointerEvents: 'none', ...pos }}>
        {toasts.map((t) => (
          <div key={t.id} style={{ pointerEvents: 'auto', animation: 'f2-toast-in var(--f2-dur-base) var(--f2-ease)' }}>
            <Toast {...t} onClose={() => onDismiss(t.id)} />
          </div>
        ))}
        <style>{`@keyframes f2-toast-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:none}}`}</style>
      </div>
    );
  }

  /* ====================== Tooltip ====================== */
  function Tooltip({ content, placement = 'top', children, style = {} }) {
    const [show, setShow] = React.useState(false);
    const place = {
      top: { bottom: '100%', left: '50%', transform: 'translateX(-50%)', marginBottom: 8 },
      bottom: { top: '100%', left: '50%', transform: 'translateX(-50%)', marginTop: 8 },
      left: { right: '100%', top: '50%', transform: 'translateY(-50%)', marginRight: 8 },
      right: { left: '100%', top: '50%', transform: 'translateY(-50%)', marginLeft: 8 },
    }[placement];
    return (
      <span style={{ position: 'relative', display: 'inline-flex', ...style }}
        onMouseEnter={() => setShow(true)} onMouseLeave={() => setShow(false)}
        onFocus={() => setShow(true)} onBlur={() => setShow(false)}>
        {children}
        {show && content && (
          <span role="tooltip" style={{
            position: 'absolute', zIndex: 80, whiteSpace: 'nowrap', padding: '6px 10px', ...place,
            background: 'var(--f2-surface-sunken)', color: 'var(--f2-text)', border: '1px solid var(--f2-border-strong)',
            borderRadius: 8, fontSize: 12.5, fontFamily: 'var(--f2-font-body)', boxShadow: 'var(--f2-elevation-overlay)', pointerEvents: 'none',
          }}>{content}</span>
        )}
      </span>
    );
  }

  /* ====================== Popover ====================== */
  function Popover({ trigger, children, placement = 'bottom', align = 'start', width = 260, style = {} }) {
    const [open, setOpen] = React.useState(false);
    const ref = React.useRef(null);
    useDismiss(ref, () => setOpen(false), open);
    const vert = placement === 'top' ? { bottom: 'calc(100% + 8px)' } : { top: 'calc(100% + 8px)' };
    const horiz = align === 'end' ? { right: 0 } : align === 'center' ? { left: '50%', transform: 'translateX(-50%)' } : { left: 0 };
    return (
      <span ref={ref} style={{ position: 'relative', display: 'inline-flex', ...style }}>
        <span onClick={() => setOpen((o) => !o)}>{trigger}</span>
        {open && (
          <div role="dialog" style={{
            position: 'absolute', zIndex: 90, width, ...vert, ...horiz, padding: 14,
            background: 'var(--f2-surface-card)', border: '1px solid var(--f2-border-strong)',
            borderRadius: 'var(--f2-radius-md)', boxShadow: 'var(--f2-elevation-overlay)',
          }}>{typeof children === 'function' ? children(() => setOpen(false)) : children}</div>
        )}
      </span>
    );
  }

  /* ====================== Modal ====================== */
  function Modal({ open, onClose, title, description, children, footer, size = 'md', contained = false, style = {} }) {
    React.useEffect(() => {
      if (!open) return undefined;
      const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [open, onClose]);
    if (!open) return null;
    const w = { sm: 380, md: 480, lg: 640 }[size] || 480;
    return (
      <div style={{ position: contained ? 'absolute' : 'fixed', inset: 0, zIndex: 300, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(11,13,17,0.62)' }} />
        <div role="dialog" aria-modal="true" aria-label={title} style={{
          position: 'relative', width: w, maxWidth: '100%', maxHeight: '100%', display: 'flex', flexDirection: 'column',
          background: 'var(--f2-surface-card)', border: '1px solid var(--f2-border-strong)', borderRadius: 'var(--f2-radius-lg)',
          boxShadow: 'var(--f2-elevation-overlay)', animation: 'f2-modal-in var(--f2-dur-base) var(--f2-ease)', ...style,
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '20px 20px 0' }}>
            <div style={{ flex: 1 }}>
              {title && <h2 style={{ margin: 0, fontFamily: 'var(--f2-font-display)', fontWeight: 600, fontSize: 19, letterSpacing: '-0.01em', color: 'var(--f2-text)' }}>{title}</h2>}
              {description && <p style={{ margin: '6px 0 0', fontSize: 14, lineHeight: 1.5, color: 'var(--f2-text-muted)' }}>{description}</p>}
            </div>
            {onClose && <IconButton variant="ghost" size="sm" aria-label="Close" onClick={onClose}><Icon name="X" size={18} /></IconButton>}
          </div>
          <div style={{ padding: '16px 20px', overflowY: 'auto', flex: 1 }}>{children}</div>
          {footer && <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '14px 20px', borderTop: '1px solid var(--f2-border)' }}>{footer}</div>}
        </div>
        <style>{`@keyframes f2-modal-in{from{opacity:0;transform:scale(.97)}to{opacity:1;transform:none}}`}</style>
      </div>
    );
  }

  /* ====================== Drawer ====================== */
  function Drawer({ open, onClose, title, children, footer, side = 'right', width = 380, contained = false, style = {} }) {
    React.useEffect(() => {
      if (!open) return undefined;
      const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
      document.addEventListener('keydown', onKey);
      return () => document.removeEventListener('keydown', onKey);
    }, [open, onClose]);
    if (!open) return null;
    const sideStyle = side === 'left' ? { left: 0 } : { right: 0 };
    return (
      <div style={{ position: contained ? 'absolute' : 'fixed', inset: 0, zIndex: 300 }}>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(11,13,17,0.62)' }} />
        <div role="dialog" aria-modal="true" aria-label={title} style={{
          position: 'absolute', top: 0, bottom: 0, ...sideStyle, width, maxWidth: '100%', display: 'flex', flexDirection: 'column',
          background: 'var(--f2-surface)', borderLeft: side === 'right' ? '1px solid var(--f2-border-strong)' : 'none',
          borderRight: side === 'left' ? '1px solid var(--f2-border-strong)' : 'none', boxShadow: 'var(--f2-elevation-overlay)',
          animation: `f2-drawer-${side} var(--f2-dur-base) var(--f2-ease)`, ...style,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '16px 18px', borderBottom: '1px solid var(--f2-border)' }}>
            <h2 style={{ flex: 1, margin: 0, fontFamily: 'var(--f2-font-display)', fontWeight: 600, fontSize: 17, color: 'var(--f2-text)' }}>{title}</h2>
            {onClose && <IconButton variant="ghost" size="sm" aria-label="Close" onClick={onClose}><Icon name="X" size={18} /></IconButton>}
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '18px' }}>{children}</div>
          {footer && <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, padding: '14px 18px', borderTop: '1px solid var(--f2-border)' }}>{footer}</div>}
          <style>{`@keyframes f2-drawer-right{from{transform:translateX(100%)}to{transform:none}}@keyframes f2-drawer-left{from{transform:translateX(-100%)}to{transform:none}}`}</style>
        </div>
      </div>
    );
  }

  Object.assign(window.F2, { Alert, Banner, Toast, useToaster, ToastViewport, Tooltip, Popover, Modal, Drawer });
})();
