// src/lib/useColumnasAjustables.jsx
// Hook para columnas redimensionables (arrastrar el borde, estilo Excel).
import { useState, useEffect } from "react";

export function useColumnasAjustables(anchosIniciales) {
  const [anchos, setAnchos] = useState(anchosIniciales);

  useEffect(() => {
    if (anchos.length !== anchosIniciales.length) {
      setAnchos(anchosIniciales);
    }
  }, [anchosIniciales.length]);

  function iniciarResize(e, i) {
    e.preventDefault();
    e.stopPropagation();
    const xInicial = e.clientX;
    const anchoInicial = anchos[i];
    function onMove(ev) {
      const nuevo = Math.max(50, anchoInicial + (ev.clientX - xInicial));
      setAnchos((prev) => { const c = [...prev]; c[i] = nuevo; return c; });
    }
    function onUp() {
      document.removeEventListener("mousemove", onMove);
      document.removeEventListener("mouseup", onUp);
    }
    document.addEventListener("mousemove", onMove);
    document.addEventListener("mouseup", onUp);
  }

  function ColGroup() {
    return (
      <colgroup>
        {anchos.map((w, i) => <col key={i} style={{ width: w, minWidth: w }} />)}
      </colgroup>
    );
  }

  function Resizer({ index }) {
    return (
      <span
        onMouseDown={(e) => iniciarResize(e, index)}
        className="col-resizer"
        style={{ position: "absolute", top: 0, right: 0, width: 8, height: "100%",
          cursor: "col-resize", userSelect: "none", zIndex: 5 }}
      />
    );
  }

  const anchoTotal = anchos.reduce((a, b) => a + b, 0);
  const tableProps = {
    style: { tableLayout: "fixed", width: "100%", minWidth: anchoTotal },
  };

  return { anchos, ColGroup, Resizer, anchoTotal, tableProps };
}
