// Componentes compartilhados — popovers, menus, toasts.
// Drop-in para botões de Exportar, Mais opções, etc. em qualquer tela.

const { useState: usePopState, useEffect: usePopEffect, useRef: usePopRef } = React;

/* ────────────────────────────────────────────────────────────────
   useOutsideClose — fecha o popover ao clicar fora ou apertar ESC
   ──────────────────────────────────────────────────────────────── */
function useOutsideClose(open, onClose) {
  usePopEffect(() => {
    if (!open) return;
    const onClick = () => onClose();
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    // delay so the click that opened the popover doesn't immediately close it
    const t = setTimeout(() => window.addEventListener('click', onClick), 0);
    window.addEventListener('keydown', onKey);
    return () => { clearTimeout(t); window.removeEventListener('click', onClick); window.removeEventListener('keydown', onKey); };
  }, [open, onClose]);
}

/* ────────────────────────────────────────────────────────────────
   <ExportButton count label />
   icon-btn com popover de exportação (PDF / CSV / XLS / email)
   ──────────────────────────────────────────────────────────────── */
function ExportButton({ count, label = 'registros', email = 'leticia.andrade@ezza.com.br', size = 'icon' }) {
  const [open, setOpen] = usePopState(false);
  useOutsideClose(open, () => setOpen(false));
  const toast = useToast();

  const handle = (fmt, msg) => {
    setOpen(false);
    toast(msg);
  };

  return (
    <div className="pop-wrap" onClick={(e) => e.stopPropagation()}>
      {size === 'mini' ? (
        <button className="mini-btn" onClick={() => setOpen(o => !o)} title="Exportar">{ICN.upload}</button>
      ) : size === 'primary' ? (
        <button className="btn-primary" onClick={() => setOpen(o => !o)}>{ICN.upload} Exportar</button>
      ) : (
        <button className={`icon-btn ${open ? 'icon-btn-on' : ''}`} onClick={() => setOpen(o => !o)} title="Exportar">{ICN.upload}</button>
      )}
      {open && (
        <div className="pop pop-export" onClick={(e) => e.stopPropagation()}>
          <div className="pop-head">
            <strong>Exportar</strong>
            {count != null && <span className="muted pop-count">{count} {label}</span>}
          </div>
          <div className="pop-list">
            <button className="pop-item" onClick={() => handle('pdf', 'Relatório em PDF gerado · 2 MB')}>
              <span className="pop-ic pop-ic-pdf">PDF</span>
              <span className="col" style={{flex:1, minWidth:0, textAlign:'left'}}>
                <span className="pop-lbl">Relatório em PDF</span>
                <span className="pop-sub muted">Apresentação com gráficos · ~2 MB</span>
              </span>
              <span className="muted">{ICN.arrowRight}</span>
            </button>
            <button className="pop-item" onClick={() => handle('csv', 'CSV pronto para baixar · 12 KB')}>
              <span className="pop-ic pop-ic-csv">CSV</span>
              <span className="col" style={{flex:1, minWidth:0, textAlign:'left'}}>
                <span className="pop-lbl">Dados em CSV</span>
                <span className="pop-sub muted">Para importar em outro CRM · ~12 KB</span>
              </span>
              <span className="muted">{ICN.arrowRight}</span>
            </button>
            <button className="pop-item" onClick={() => handle('xls', 'Planilha Excel gerada · 84 KB')}>
              <span className="pop-ic pop-ic-xls">XLS</span>
              <span className="col" style={{flex:1, minWidth:0, textAlign:'left'}}>
                <span className="pop-lbl">Planilha do Excel</span>
                <span className="pop-sub muted">Com fórmulas e gráficos · ~84 KB</span>
              </span>
              <span className="muted">{ICN.arrowRight}</span>
            </button>
          </div>
          <div className="pop-divider" />
          <button className="pop-item" onClick={() => handle('mail', 'Enviado para ' + email)}>
            <span className="pop-ic pop-ic-mail">{ICN.mail}</span>
            <span className="col" style={{flex:1, minWidth:0, textAlign:'left'}}>
              <span className="pop-lbl">Enviar por e-mail</span>
              <span className="pop-sub muted">{email}</span>
            </span>
            <span className="muted">{ICN.arrowRight}</span>
          </button>
        </div>
      )}
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────
   <MoreMenu items={[{ic, label, onClick, danger}]} />
   Menu contextual de 3 pontinhos
   ──────────────────────────────────────────────────────────────── */
function MoreMenu({ items, size = 'mini', align = 'right', placement = 'bottom', title = 'Mais opções' }) {
  const [open, setOpen] = usePopState(false);
  useOutsideClose(open, () => setOpen(false));
  const toast = useToast();

  const fire = (item) => {
    setOpen(false);
    if (item.onClick) item.onClick();
    else if (item.toast) toast(item.toast);
  };

  return (
    <div className="pop-wrap" onClick={(e) => e.stopPropagation()}>
      {size === 'icon' ? (
        <button className={`icon-btn ${open ? 'icon-btn-on' : ''}`} onClick={() => setOpen(o => !o)} title={title}>{ICN.more}</button>
      ) : (
        <button className={`mini-btn ${open ? 'mini-btn-on' : ''}`} onClick={() => setOpen(o => !o)} title={title}>{ICN.more}</button>
      )}
      {open && (
        <div className={`pop pop-menu pop-${align} pop-place-${placement}`} onClick={(e) => e.stopPropagation()}>
          {items.map((it, i) => {
            if (it.divider) return <div key={i} className="pop-divider" />;
            if (it.section) return <div key={i} className="pop-section">{it.section}</div>;
            return (
              <button key={i} className={`pop-menu-item ${it.danger ? 'pop-menu-item-danger' : ''}`} onClick={() => fire(it)}>
                {it.ic && <span className="pop-menu-ic">{it.ic}</span>}
                <span className="pop-menu-lbl">{it.label}</span>
                {it.hint && <span className="pop-menu-hint muted">{it.hint}</span>}
                {it.arrow && <span className="muted pop-menu-arrow">{ICN.arrowRight}</span>}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────
   <CardActionsBar onCreate onExport onPeriod count />
   Substitui o CardActions decorativo (+, upload, cal) por ações reais
   ──────────────────────────────────────────────────────────────── */
function CardActionsBar({ count, onCreate, onPeriod, createLabel = 'Criar', moreItems }) {
  const toast = useToast();
  return (
    <div className="card-actions">
      <button className="mini-btn" title={createLabel} onClick={() => onCreate ? onCreate() : toast(createLabel + ' iniciado')}>{ICN.plus}</button>
      <ExportButton count={count} size="mini" />
      <button className="mini-btn" title="Período" onClick={() => onPeriod ? onPeriod() : toast('Período: últimos 30 dias')}>{ICN.cal}</button>
      {moreItems && <MoreMenu items={moreItems} />}
    </div>
  );
}

/* ────────────────────────────────────────────────────────────────
   useToast — hook + ToastHost para feedback rápido
   ──────────────────────────────────────────────────────────────── */
const ToastContext = React.createContext(() => {});

function ToastProvider({ children }) {
  const [toasts, setToasts] = usePopState([]);
  const push = React.useCallback((msg, opts = {}) => {
    const id = Date.now() + Math.random();
    setToasts(t => [...t, { id, msg, kind: opts.kind || 'ok', icon: opts.icon }]);
    setTimeout(() => setToasts(t => t.filter(x => x.id !== id)), opts.duration || 2400);
  }, []);
  return (
    <ToastContext.Provider value={push}>
      {children}
      <div className="toast-host">
        {toasts.map(t => (
          <div key={t.id} className={`toast toast-${t.kind}`}>
            <span className="toast-ic">{t.icon || (t.kind === 'err' ? ICN.x : ICN.check)}</span>
            <span className="toast-msg">{t.msg}</span>
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

function useToast() {
  return React.useContext(ToastContext);
}

/* ────────────────────────────────────────────────────────────────
   <ActionBtn> — substituto universal pros mini-btn decorativos
   Aceita uma ação ou um toast string.
   ──────────────────────────────────────────────────────────────── */
function ActionBtn({ icon, title, onClick, toast: toastMsg, size = 'mini', danger }) {
  const toast = useToast();
  const cls = size === 'icon' ? 'icon-btn' : 'mini-btn';
  return (
    <button
      className={`${cls} ${danger ? 'mini-btn-danger' : ''}`}
      title={title}
      onClick={(e) => {
        e.stopPropagation();
        if (onClick) onClick();
        else if (toastMsg) toast(toastMsg);
        else if (title) toast(title);
      }}
    >
      {icon}
    </button>
  );
}

/* ────────────────────────────────────────────────────────────────
   Estilos compartilhados — injetados uma vez via <PopoverStyles />
   ──────────────────────────────────────────────────────────────── */
function PopoverStyles() {
  return (
    <style>{`
      .pop-wrap { position: relative; display: inline-flex; }

      .pop {
        position: absolute; top: calc(100% + 8px);
        background: white;
        border: 0.5px solid oklch(0.92 0.01 250);
        border-radius: 16px;
        box-shadow: 0 16px 40px -12px rgba(20,30,60,.22);
        padding: 14px;
        z-index: 80;
        animation: pop-in .14s cubic-bezier(.2,.8,.2,1);
        transform-origin: top right;
      }
      .pop-right { right: 0; }
      .pop-left  { left: 0; }
      .pop-place-top { bottom: calc(100% + 8px); top: auto; transform-origin: bottom right; }

      @keyframes pop-in {
        from { opacity: 0; transform: translateY(-4px) scale(0.98); }
        to   { opacity: 1; transform: translateY(0)    scale(1); }
      }

      .pop-export { width: 340px; right: 0; }
      .pop-head { display: flex; justify-content: space-between; align-items: center; padding: 2px 4px 12px; border-bottom: 1px solid oklch(0.93 0.01 255); }
      .pop-head strong { font-size: 14px; letter-spacing: -0.01em; }
      .pop-count { font-size: 11px; font-family: var(--font-mono); }

      .pop-list { display: flex; flex-direction: column; gap: 2px; margin-top: 6px; }
      .pop-item {
        display: flex; align-items: center; gap: 12px;
        padding: 10px;
        border-radius: 12px;
        background: transparent;
        border: none;
        text-align: left;
        cursor: default;
        font-family: inherit;
        width: 100%;
        color: var(--ink);
      }
      .pop-item:hover { background: oklch(0.96 0.012 250); }
      .pop-ic {
        width: 38px; height: 38px;
        border-radius: 10px;
        display: grid; place-items: center;
        font-size: 10px; font-weight: 800;
        letter-spacing: 0.04em;
        flex-shrink: 0;
      }
      .pop-ic-pdf  { background: oklch(0.93 0.07 18);  color: oklch(0.42 0.16 18); }
      .pop-ic-csv  { background: oklch(0.93 0.07 160); color: oklch(0.40 0.14 160); }
      .pop-ic-xls  { background: oklch(0.94 0.10 95);  color: oklch(0.40 0.13 80); }
      .pop-ic-mail { background: oklch(0.93 0.06 250); color: oklch(0.40 0.16 250); font-size: 14px; }
      .pop-lbl { display: block; font-size: 13px; font-weight: 600; letter-spacing: -0.005em; }
      .pop-sub { display: block; font-size: 11.5px; margin-top: 2px; line-height: 1.3; }
      .pop-divider { height: 1px; background: oklch(0.93 0.01 255); margin: 8px 0; }
      .pop-section { font-size: 10px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-faint); padding: 8px 8px 4px; }

      .pop-menu { width: 240px; padding: 6px; }
      .pop-menu-item {
        display: flex; align-items: center; gap: 10px;
        width: 100%;
        padding: 8px 10px;
        border-radius: 10px;
        background: transparent;
        border: none;
        text-align: left;
        font-family: inherit;
        font-size: 12.5px;
        font-weight: 500;
        color: var(--ink);
        cursor: default;
      }
      .pop-menu-item:hover { background: oklch(0.96 0.012 250); }
      .pop-menu-item-danger { color: var(--danger); }
      .pop-menu-item-danger:hover { background: oklch(0.96 0.04 18); }
      .pop-menu-ic { display: inline-flex; color: var(--ink-muted); width: 16px; }
      .pop-menu-item-danger .pop-menu-ic { color: var(--danger); }
      .pop-menu-lbl { flex: 1; }
      .pop-menu-hint { font-size: 10.5px; font-family: var(--font-mono); }
      .pop-menu-arrow { display: inline-flex; }

      .icon-btn-on, .mini-btn-on { background: var(--ink) !important; color: white !important; }
      .icon-btn-on svg, .mini-btn-on svg { stroke: white !important; }
      .mini-btn-danger:hover { color: var(--danger); background: oklch(0.96 0.04 18); }

      /* Toast host */
      .toast-host {
        position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%);
        display: flex; flex-direction: column; gap: 8px;
        z-index: 200;
        pointer-events: none;
      }
      .toast {
        display: flex; align-items: center; gap: 10px;
        background: var(--ink);
        color: white;
        padding: 10px 16px 10px 12px;
        border-radius: 999px;
        font-size: 13px;
        font-weight: 500;
        letter-spacing: -0.005em;
        box-shadow: 0 16px 40px -10px rgba(20,30,60,.4);
        animation: toast-in .22s cubic-bezier(.2,.8,.2,1);
        max-width: 460px;
      }
      .toast-ic {
        width: 22px; height: 22px; border-radius: 50%;
        background: oklch(0.65 0.13 155);
        display: grid; place-items: center;
        color: var(--ink);
        flex-shrink: 0;
      }
      .toast-ic svg { width: 13px; height: 13px; stroke-width: 3; }
      .toast-err .toast-ic { background: var(--danger); color: white; }
      .toast-info .toast-ic { background: var(--acc-blue-strong); color: white; }
      @keyframes toast-in {
        from { opacity: 0; transform: translateY(8px); }
        to   { opacity: 1; transform: translateY(0); }
      }
    `}</style>
  );
}

Object.assign(window, { ExportButton, MoreMenu, CardActionsBar, ActionBtn, ToastProvider, useToast, PopoverStyles });
