// Shared UI building blocks — avatars, pill variants, section wrappers

function GMAvatar({ initials, size = 28, bg, style = {} }) {
  const palette = ['#2C2C2C', '#6B6B6B', '#0369A1', '#059669', '#D97706', '#6B21A8', '#D93E0A'];
  const hash = (initials || 'X').charCodeAt(0) % palette.length;
  const color = bg || palette[hash];
  return (
    <span className="avatar" style={{
      width: size, height: size,
      fontSize: Math.max(9, Math.round(size * 0.38)),
      background: color,
      ...style,
    }}>{initials}</span>
  );
}

function GMPill({ tone = 'ghost', children, dotColor }) {
  return (
    <span className={`pill pill--${tone}`}>
      {dotColor && <span className="dot" style={{ background: dotColor }} />}
      {children}
    </span>
  );
}

// Menu — popover positioned to a trigger rect. `onClose` fires on outside click.
function GMMenu({ anchor, onClose, children, align = 'right', width = 260 }) {
  if (!anchor) return null;
  const top = anchor.bottom + 6;
  const left = align === 'right' ? anchor.right - width : anchor.left;
  return (
    <>
      <div className="menu-backdrop" onClick={onClose} />
      <div className="menu" style={{ top, left, minWidth: width }} onClick={e => e.stopPropagation()}>
        {children}
      </div>
    </>
  );
}

// Toast host — keeps a queue of messages and auto-dismisses each after 4s.
function GMToastHost({ toasts }) {
  return (
    <div className="toasts" aria-live="polite">
      {toasts.map(t => (
        <div className="toast" key={t.id}>
          <div className="toast-icon">
            {t.kind === 'ai' ? <GMI.sparkle /> : <GMI.check />}
          </div>
          <div className="toast-body">
            <div className="toast-title">{t.title}</div>
            {t.sub && <div className="toast-sub">{t.sub}</div>}
          </div>
        </div>
      ))}
    </div>
  );
}

// Simple toast hook — call push({title,sub,kind}) to add a message.
function useToasts() {
  const [toasts, setToasts] = React.useState([]);
  const nextId = React.useRef(1);
  const push = React.useCallback((t) => {
    const id = nextId.current++;
    setToasts(ts => [...ts, { id, ...t }]);
    setTimeout(() => setToasts(ts => ts.filter(x => x.id !== id)), 4200);
  }, []);
  return { toasts, push };
}

window.GMAvatar = GMAvatar;
window.GMPill = GMPill;
window.GMMenu = GMMenu;
window.GMToastHost = GMToastHost;
window.useToasts = useToasts;
