// Present the SAME authorised cells as cards on phones and a table on larger screens.
// No data lookup or permission logic lives here. Hidden/withheld columns never reappear.
function useCompactLayout(query = "(max-width: 600px)") {
  const [compact, setCompact] = React.useState(() => !!(window.matchMedia && window.matchMedia(query).matches));
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const media = window.matchMedia(query);
    const update = () => setCompact(media.matches);
    update();
    if (media.addEventListener) { media.addEventListener("change", update); return () => media.removeEventListener("change", update); }
    media.addListener(update); return () => media.removeListener(update);
  }, [query]);
  return compact;
}

function ResponsiveTable({ children, primary = [], label = "Records" }) {
  const compact = useCompactLayout();
  const lang = useLang();
  const ar = lang === "ar";
  const table = React.Children.only(children);
  if (!compact) return <div className="responsive-table-scroll" role="region" aria-label={label} tabIndex={0}>{table}</div>;
  const sections = React.Children.toArray(table.props.children);
  const head = sections.find(n => n.type === "thead");
  const body = sections.find(n => n.type === "tbody");
  const headRow = head && React.Children.toArray(head.props.children)[0];
  const headers = headRow ? React.Children.toArray(headRow.props.children) : [];
  const rows = body ? React.Children.toArray(body.props.children) : [];
  const labels = headers.map(h => h.props.label || h.props.children || "");
  const sorts = headers.filter(h => h.props.col && h.props.setSort);
  const currentSort = sorts[0] && sorts[0].props.sort;
  return <div className="record-list" aria-label={label}>
    {sorts.length > 0 && <div className="record-sort">
      <label>{ar ? "ترتيب حسب" : "Sort by"}<select className="sel" value={currentSort.key}
        onChange={e => sorts[0].props.setSort({ key: e.target.value, dir: currentSort.dir })}>
        {sorts.map(h => <option key={h.props.col} value={h.props.col}>{h.props.label}</option>)}
      </select></label>
      <Btn variant="ghost" onClick={() => sorts[0].props.setSort({ key: currentSort.key, dir: currentSort.dir === "asc" ? "desc" : "asc" })}>
        {currentSort.dir === "asc" ? (ar ? "تصاعدي ↑" : "Ascending ↑") : (ar ? "تنازلي ↓" : "Descending ↓")}
      </Btn>
    </div>}
    {rows.map((row, index) => row.type === "tr"
      ? <ResponsiveRecord key={row.key || index} row={row} labels={labels} primary={primary} ar={ar} />
      : React.cloneElement(row, { mobileColumns: labels, mobilePrimary: primary, mobileArabic: ar }))}
  </div>;
}

function ResponsiveRecord({ row, labels, primary, ar }) {
      const cells = React.Children.toArray(row.props.children);
      // Empty/group rows retain their full text instead of assigning incorrect column labels.
      if (cells.some(c => c.props.colSpan > 1)) return <div className="record-group">{cells.map(c => c.props.children)}</div>;
      const renderCell = (cell, i) => <div className={"record-field" + (!labels[i] ? " record-actions" : "")} key={i}>
        {labels[i] && <div className="record-label">{labels[i]}</div>}
        <div className="record-value" style={{ color: cell.props.style && cell.props.style.color }}>{cell.props.children}</div>
      </div>;
      const main = [], extra = [];
      cells.forEach((cell, i) => (primary.includes(labels[i]) ? main : extra).push(renderCell(cell, i)));
      return <article className={"record-card" + ((row.props.className || "").includes("row-void") ? " row-void" : "")} style={row.props.style}>
        <div className="record-fields">{main}</div>
        {extra.length > 0 && <details className="record-details"><summary>{ar ? "التفاصيل والخيارات" : "Details & actions"}</summary><div className="record-fields">{extra}</div></details>}
        {row.props.onClick && <Btn variant="ghost" className="record-open" icon="eye" onClick={row.props.onClick}>{ar ? "فتح السجل" : "Open record"}</Btn>}
      </article>;
}

// Secondary toolbar tools stay mounted exactly once; on compact screens they live in a drawer.
function TopbarTools({ children }) {
  const compact = useCompactLayout("(max-width: 1200px)");
  const [open, setOpen] = React.useState(false);
  const lang = useLang();
  const ref = React.useRef(null), trigger = React.useRef(null);
  React.useEffect(() => {
    if (!open || !compact) return;
    const key = e => { if (e.key === "Escape") { setOpen(false); trigger.current && trigger.current.focus(); } };
    const outside = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("keydown", key); document.addEventListener("pointerdown", outside);
    return () => { document.removeEventListener("keydown", key); document.removeEventListener("pointerdown", outside); };
  }, [open, compact]);
  return <div className="topbar-tools" ref={ref}>
    <button ref={trigger} type="button" className="btn topbar-more" aria-expanded={open} aria-controls="topbar-tools-panel" onClick={() => setOpen(!open)}>
      <Icon name="layers" size={16} />{lang === "ar" ? "المزيد" : "More"}
    </button>
    <div id="topbar-tools-panel" className={"topbar-tools-panel" + (open ? " is-open" : "")} hidden={compact && !open}>
      <div className="topbar-tools-heading"><strong>{lang === "ar" ? "خيارات إضافية" : "More options"}</strong><Btn variant="ghost" icon="x" aria-label={lang === "ar" ? "إغلاق" : "Close"} onClick={() => setOpen(false)} /></div>
      {children}
    </div>
  </div>;
}
