export function autoPlaceArticles(articles, columnCount) {
  const columnHeights = Array(columnCount).fill(0); // Track max height per column
  const placements = [];

  for (let article of articles) {
    const { colSpan, rowSpan, gridColumnStart } = article;

    let colStart, rowStart;

    if (gridColumnStart) {
      // Manual column override
      colStart = gridColumnStart;
      // Get current max height in that column group
      const currentHeight = Math.max(
        ...columnHeights.slice(colStart - 1, colStart - 1 + colSpan)
      );
      rowStart = currentHeight + 1;
    } else {
      // Auto-placement: find best column group with lowest stack height
      let bestStart = 0;
      let minHeight = Infinity;

      for (let start = 0; start <= columnCount - colSpan; start++) {
        const slice = columnHeights.slice(start, start + colSpan);
        const height = Math.max(...slice);
        if (height < minHeight) {
          minHeight = height;
          bestStart = start;
        }
      }

      colStart = bestStart + 1;
      rowStart = minHeight + 1;
    }

    // Place the article
    placements.push({
      ...article,
      gridColumnStart: colStart,
      gridRowStart: rowStart,
    });

    // Update column heights
    for (let i = colStart - 1; i < colStart - 1 + colSpan; i++) {
      columnHeights[i] = rowStart - 1 + rowSpan;
    }
  }

  return placements;
}

export function parseImageFilename(filename) {
  // Updated regex to capture optional gridColumnStart (_gZ) and handle parentheses/brackets
  const regex =
    /(?<page>\d+)_r(?<rowSpan>\d+)_c(?<colSpan>\d+)(?:_g(?<gridColumnStart>\d+))?.*\.\w+$/;
  const match = filename.match(regex);

  if (!match || !match.groups) {
    throw new Error(`Invalid filename format: ${filename}`);
  }

  const { page, rowSpan, colSpan, gridColumnStart } = match.groups;

  return {
    page: parseInt(page, 10),
    rowSpan: parseInt(rowSpan, 10),
    colSpan: parseInt(colSpan, 10),
    // Only include gridColumnStart if it exists in the filename
    ...(gridColumnStart && { gridColumnStart: parseInt(gridColumnStart, 10) }),
  };
}

export function createArticlesFromFilenames(filenames, pageNumber) {
  return filenames
    .map((filename, index) => {
      try {
        const properties = parseImageFilename(filename);
        return {
          id: index + 1,
          page: pageNumber, // inject page from outer structure
          colSpan: properties.colSpan,
          rowSpan: properties.rowSpan,
          image: filename,
          ...(properties.gridColumnStart && {
            gridColumnStart: properties.gridColumnStart,
          }),
        };
      } catch (error) {
        console.error(`Error processing filename ${filename}:`, error.message);
        return null;
      }
    })
    .filter((article) => article !== null);
}

export function isSameDay(date1, date2) {
  if (!date1 || !date2) return false;

  // Convert string dates to Date objects if needed
  const d1 = typeof date1 === "string" ? new Date(date1) : date1;
  const d2 = typeof date2 === "string" ? new Date(date2) : date2;

  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
}
