/* global React */
// Reusable spreadsheet component
const { useState, useMemo } = React;

function colLetter(n) {
  let s = "";
  while (n >= 0) {
    s = String.fromCharCode(65 + (n % 26)) + s;
    n = Math.floor(n / 26) - 1;
  }
  return s;
}

function Spreadsheet({
  columns,        // [{ key, label, width, type: 'text'|'num'|'pct'|'eur' }]
  rows,           // [{ values: { [colKey]: cellValue }, kind?: 'section'|'total', label?, sticky? }]
  tabs,           // [{ key, label }]
  activeTab,
  onTabChange,
  toolbarRight,
  initialSelected,
  scrollHeight,
}) {
  const [selected, setSelected] = useState(initialSelected || { r: 0, c: 0 });
  const cell = rows[selected.r] && rows[selected.r].values && rows[selected.r].values[columns[selected.c] && columns[selected.c].key];
  const ref = (selected.r != null && selected.c != null)
    ? `${colLetter(selected.c)}${selected.r + 1}`
    : "";

  const formatCell = (v, type) => {
    if (v == null || v === "") return "";
    if (type === "num") return typeof v === "number" ? v.toLocaleString("fr-FR") : v;
    if (type === "pct") return typeof v === "number" ? (v * 100).toFixed(1) + "%" : v;
    if (type === "eur") return typeof v === "number" ? v.toLocaleString("fr-FR") + " €" : v;
    return v;
  };

  return (
    <div>
      {tabs && (
        <div className="sheet-toolbar">
          <button className="btn sm"><Icon.formula /> fx</button>
          <div className="formula-bar">
            <span className="ref">{ref}</span>
            <span>{cell != null ? (typeof cell === "object" ? cell.formula || cell.value : cell) : ""}</span>
          </div>
          <div className="sep"></div>
          <button className="btn sm ghost"><Icon.download /></button>
          {toolbarRight}
        </div>
      )}
      <div className="sheet-wrap" style={scrollHeight ? { maxHeight: scrollHeight } : null}>
        <table className="sheet">
          <thead>
            <tr>
              <th className="corner"></th>
              {columns.map((c, i) => (
                <th key={c.key} style={c.width ? { width: c.width, minWidth: c.width } : null}>
                  <div className="row" style={{ gap: 6, alignItems: "center" }}>
                    <span style={{ color: "var(--text-faint)", fontSize: 9.5, fontWeight: 600 }}>{colLetter(i)}</span>
                    <span>{c.label}</span>
                  </div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((r, ri) => (
              <tr key={ri}>
                <td className="row-h">{ri + 1}</td>
                {columns.map((c, ci) => {
                  const raw = r.values && r.values[c.key];
                  const obj = raw && typeof raw === "object" ? raw : null;
                  const value = obj ? obj.value : raw;
                  const klass = [
                    obj && obj.flag,
                    r.kind === "section" && "section",
                    r.kind === "total" && "total",
                    obj && obj.formula && "formula",
                    selected.r === ri && selected.c === ci && "selected",
                    c.type === "num" || c.type === "pct" || c.type === "eur" ? "num" : null,
                  ].filter(Boolean).join(" ");
                  const display = formatCell(value, c.type);
                  return (
                    <td
                      key={c.key}
                      className={klass}
                      onClick={() => setSelected({ r: ri, c: ci })}
                    >
                      <span className={"cell" + (c.type === "num" || c.type === "pct" || c.type === "eur" ? " num" : "") + (r.kind === "section" ? " section" : "") + (c.type === "text" ? " label" : "")}>
                        {display}
                      </span>
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {tabs && (
        <div className="sheet-tabs">
          {tabs.map((t) => (
            <div
              key={t.key}
              className={"stab" + (t.key === activeTab ? " active" : "")}
              onClick={() => onTabChange && onTabChange(t.key)}
            >
              {t.label}
            </div>
          ))}
          <div className="stab"><Icon.plus className="sm" /></div>
        </div>
      )}
    </div>
  );
}

window.Spreadsheet = Spreadsheet;
window.colLetter = colLetter;
