// Grade de blocos reposicionáveis para telas estratégicas (Dashboard, Painel administrativo, Visão comercial).
// Arraste pela alça no topo de cada bloco (ou use as setas com a alça focada): o bloco solto assume a posição
// do alvo e os demais se reacomodam na grade de 12 colunas, sem sobreposição. A ordem fica salva neste navegador.
// "Restaurar grade" (canto superior direito da área de dados) volta à ordem padrão da tela.
const VX_GRID_KEY = id => 'vx-blocks:' + id;

function vxGridMerge(saved, ids) {
  const known = (saved || []).filter(x => ids.includes(x));
  return [...known, ...ids.filter(x => !known.includes(x))];
}

function vxGridRead(id, ids) {
  try {
    const raw = JSON.parse(window.localStorage.getItem(VX_GRID_KEY(id)) || 'null');
    if (Array.isArray(raw)) return vxGridMerge(raw, ids);
  } catch (e) { /* armazenamento indisponível: usa a ordem padrão */ }
  return ids;
}

function vxGridWrite(id, order, isDefault) {
  try {
    if (isDefault) window.localStorage.removeItem(VX_GRID_KEY(id));
    else window.localStorage.setItem(VX_GRID_KEY(id), JSON.stringify(order));
  } catch (e) { /* preferência opcional */ }
}

// blocks: [{ id, title, span (1–12, padrão 12), node }]. `header` (ex.: PageHeader) fica abaixo do botão de restaurar.
function BlockGrid({ id, blocks, header }) {
  const ids = blocks.map(b => b.id);
  const key = ids.join('|');
  const [order, setOrder] = React.useState(() => vxGridRead(id, ids));
  const [armed, setArmed] = React.useState(null);
  const [drag, setDrag] = React.useState(null);
  const [over, setOver] = React.useState(null);
  const [note, setNote] = React.useState('');

  // Blocos que surgem ou somem (permissão, dados) entram no fim / saem sem desarrumar o restante.
  React.useEffect(() => {
    setOrder(o => { const n = vxGridMerge(o, ids); return n.join('|') === o.join('|') ? o : n; });
  }, [key]);

  const current = vxGridMerge(order, ids);
  const isDefault = current.join('|') === key;
  const byId = Object.fromEntries(blocks.map(b => [b.id, b]));

  const commit = next => { setOrder(next); vxGridWrite(id, next, next.join('|') === key); };
  const move = (from, to) => {
    if (from === to || !current.includes(from) || !current.includes(to)) return;
    const next = current.filter(x => x !== from);
    next.splice(current.indexOf(to), 0, from);
    commit(next);
    setNote((byId[from].title || 'Bloco') + ' movido para a posição ' + (next.indexOf(from) + 1) + ' de ' + next.length);
  };
  const step = (blockId, delta) => {
    const i = current.indexOf(blockId), j = i + delta;
    if (j < 0 || j >= current.length) return;
    move(blockId, current[j]);
  };
  const reset = () => { commit(ids); setNote('Grade restaurada para a ordem padrão'); };
  const clear = () => { setArmed(null); setDrag(null); setOver(null); };

  return (
    <>
      <div className="vx-bgrid-bar">
        <button type="button" className="vx-bgrid-reset" disabled={isDefault} onClick={reset} title="Voltar os blocos para a ordem padrão desta tela">
          <i className="ph ph-arrow-counter-clockwise" />Restaurar grade
        </button>
      </div>
      {header}
      <div className="vx-bgrid" role="list">
        {current.map(blockId => {
          const b = byId[blockId];
          if (!b) return null;
          return (
            <div key={blockId} role="listitem" className="vx-bblock"
              style={{ '--span': b.span || 12 }}
              data-dragging={drag === blockId ? 'true' : undefined}
              data-over={over === blockId && drag && drag !== blockId ? 'true' : undefined}
              draggable={armed === blockId}
              onDragStart={e => { setDrag(blockId); e.dataTransfer.effectAllowed = 'move'; try { e.dataTransfer.setData('text/plain', blockId); } catch (err) { /* navegadores antigos */ } }}
              onDragOver={e => { if (drag) { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; if (over !== blockId) setOver(blockId); } }}
              onDrop={e => { e.preventDefault(); if (drag) move(drag, blockId); clear(); }}
              onDragEnd={clear}>
              <button type="button" className="vx-bhandle"
                aria-label={'Mover bloco ' + (b.title || '') + '. Arraste ou use as setas para reposicionar.'}
                title="Arraste para reposicionar"
                onMouseDown={() => setArmed(blockId)} onMouseUp={() => setArmed(null)}
                onKeyDown={e => {
                  if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') { e.preventDefault(); step(blockId, -1); }
                  else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { e.preventDefault(); step(blockId, 1); }
                }}>
                <i className="ph ph-dots-six" />
              </button>
              <div className="vx-bcontent">{b.node}</div>
            </div>
          );
        })}
      </div>
      <span className="vx-sr-only" role="status" aria-live="polite">{note}</span>
    </>
  );
}

// Atalho para telas existentes: os filhos viram blocos de largura total, na ordem em que aparecem.
// PageHeader e ReadOnlyNote ficam fixos acima da grade; Drawer, Modal e Toast ficam fixos depois dela.
function BlockGridAuto({ id, children }) {
  const DS = window.VRticeDesignSystem_d763eb;
  const kids = React.Children.toArray(children);
  const isTop = c => React.isValidElement(c) && (c.type === DS.PageHeader || c.type === window.ReadOnlyNote);
  const isOverlay = c => React.isValidElement(c) && (c.type === DS.Drawer || c.type === DS.Modal || c.type === DS.Toast || (c.type && c.type.vxOverlay));
  const top = kids.filter(isTop), overlays = kids.filter(isOverlay);
  const blocks = kids.filter(c => !isTop(c) && !isOverlay(c)).map((c, i) => {
    const p = (React.isValidElement(c) && c.props) || {};
    const title = typeof p.title === 'string' ? p.title : typeof p.label === 'string' ? p.label : 'Seção ' + (i + 1);
    return { id: 'b' + i, title, span: 12, node: c };
  });
  return <><BlockGrid id={id} blocks={blocks} header={<>{top}</>} />{overlays}</>;
}
BlockGrid.Auto = BlockGridAuto;
window.BlockGrid = BlockGrid;
