import type { SpreadsheetHeaderConfig } from '../types';
import { DEFAULT_COL_WIDTH, ROW_NUMBER_WIDTH } from '../types';

export function getFixedColOffset(
  col: number,
  colWidths: number[],
  fixedCols: number[],
): number {
  let w = 0;
  for (const c of fixedCols) {
    if (c >= col) break;
    w += colWidths[c] ?? DEFAULT_COL_WIDTH;
  }
  return w;
}

export function getFixedDataWidth(
  col: number,
  colWidths: number[],
  fixedCols: number[],
): number {
  return getFixedColOffset(col, colWidths, fixedCols);
}

export function isFixedCol(col: number, fixedCols: number[]) {
  return fixedCols.includes(col);
}

export function getDataColX(
  col: number,
  colWidths: number[],
  scrollLeft: number,
  fixedCols: number[],
  fixedWidth: number,
): number {
  if (isFixedCol(col, fixedCols)) {
    return ROW_NUMBER_WIDTH + getFixedColOffset(col, colWidths, fixedCols);
  }
  const scrollColOffset =
    getColLeft(col, colWidths) - getFixedDataWidth(col, colWidths, fixedCols);
  return fixedWidth + scrollColOffset - scrollLeft;
}

export function getColLeft(colIndex: number, colWidths: number[]): number {
  let left = 0;
  for (let i = 0; i < colIndex; i += 1) {
    left += colWidths[i] ?? DEFAULT_COL_WIDTH;
  }
  return left;
}

export function computeFixedWidth(
  colWidths: number[],
  fixedCols: number[],
): number {
  let w = ROW_NUMBER_WIDTH;
  for (const col of fixedCols) {
    w += colWidths[col] ?? DEFAULT_COL_WIDTH;
  }
  return w;
}

/** Keep only contiguous frozen columns starting from col 0 (Excel freeze semantics). */
export function normalizeFixedCols(fixedCols: number[]): number[] {
  if (fixedCols.length === 0) return [];
  const sorted = [...fixedCols].sort((a, b) => a - b);
  const result: number[] = [];
  for (let i = 0; i < sorted.length; i += 1) {
    if (sorted[i] === i) result.push(i);
    else break;
  }
  return result;
}

export function getFixedColIndices(
  headers: SpreadsheetHeaderConfig[],
): number[] {
  const raw = headers
    .filter((h) => h.fixed)
    .map((h) => h.col)
    .sort((a, b) => a - b);
  return normalizeFixedCols(raw);
}
