/**
 * Layout Patterns and Templates
 *
 * Pre-defined comic page layout patterns optimized for different genres and narrative styles
 */

import type { LayoutPattern, PageSize, LayoutCell } from "@/types";

/**
 * Standard comic page sizes with dimensions at 300 DPI
 */
export const PAGE_SIZES: Record<string, PageSize> = {
  a4: { name: "A4", width: 2480, height: 3508, dpi: 300, unit: "px" },
  letter: { name: "US Letter", width: 2550, height: 3300, dpi: 300, unit: "px" },
  manga: { name: "B5 Manga", width: 2158, height: 3035, dpi: 300, unit: "px" },
  webtoon: { name: "Webtoon", width: 800, height: 1280, dpi: 72, unit: "px" },
  square: { name: "Instagram", width: 1080, height: 1080, dpi: 72, unit: "px" },
};

/**
 * Pre-defined layout patterns for comic pages
 */
export const LAYOUT_PATTERNS: LayoutPattern[] = [
  {
    id: "grid-2x2",
    name: "Classic Grid",
    description: "2x2 equal panels — standard dialogue/page",
    genre: ["all"],
    maxPanels: 4,
    cells: [
      { x: 0.02, y: 0.02, w: 0.47, h: 0.47, type: "panel" },
      { x: 0.51, y: 0.02, w: 0.47, h: 0.47, type: "panel" },
      { x: 0.02, y: 0.51, w: 0.47, h: 0.47, type: "panel" },
      { x: 0.51, y: 0.51, w: 0.47, h: 0.47, type: "panel" },
    ],
  },
  {
    id: "manga-3-tier",
    name: "Manga 3-Tier",
    description: "Three horizontal tiers, Japanese manga style",
    genre: ["manga", "action"],
    maxPanels: 6,
    cells: [
      { x: 0.02, y: 0.02, w: 0.3, h: 0.3, type: "panel" },
      { x: 0.35, y: 0.02, w: 0.3, h: 0.3, type: "panel" },
      { x: 0.68, y: 0.02, w: 0.3, h: 0.3, type: "panel" },
      { x: 0.02, y: 0.35, w: 0.47, h: 0.3, type: "panel" },
      { x: 0.51, y: 0.35, w: 0.47, h: 0.3, type: "panel" },
      { x: 0.02, y: 0.68, w: 0.96, h: 0.3, type: "panel" },
    ],
  },
  {
    id: "action-dynamic",
    name: "Action Dynamic",
    description: "Varied sizes for action sequences with impact panels",
    genre: ["action", "superhero"],
    maxPanels: 5,
    cells: [
      { x: 0.02, y: 0.02, w: 0.6, h: 0.35, type: "panel" },
      { x: 0.64, y: 0.02, w: 0.34, h: 0.35, type: "panel" },
      { x: 0.02, y: 0.4, w: 0.34, h: 0.28, type: "panel" },
      { x: 0.38, y: 0.4, w: 0.6, h: 0.28, type: "panel" },
      { x: 0.02, y: 0.71, w: 0.96, h: 0.27, type: "panel" },
    ],
  },
  {
    id: "splash-page",
    name: "Splash Page",
    description: "Full-page single panel for dramatic reveals",
    genre: ["all"],
    maxPanels: 1,
    cells: [{ x: 0.02, y: 0.02, w: 0.96, h: 0.96, type: "panel" }],
  },
  {
    id: "webtoon-scroll",
    name: "Webtoon Scroll",
    description: "Tall vertical panels for mobile/webtoon format",
    genre: ["webtoon", "slice-of-life"],
    maxPanels: 3,
    cells: [
      { x: 0.02, y: 0.01, w: 0.96, h: 0.32, type: "panel" },
      { x: 0.02, y: 0.34, w: 0.96, h: 0.32, type: "panel" },
      { x: 0.02, y: 0.67, w: 0.96, h: 0.32, type: "panel" },
    ],
  },
  {
    id: "western-3x3",
    name: "Western 3x3",
    description: "Three rows of three panels — classic western comic",
    genre: ["western-comic", "all"],
    maxPanels: 9,
    cells: [
      { x: 0.02, y: 0.02, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.35, y: 0.02, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.68, y: 0.02, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.02, y: 0.35, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.35, y: 0.35, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.68, y: 0.35, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.02, y: 0.68, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.35, y: 0.68, w: 0.3, h: 0.29, type: "panel" },
      { x: 0.68, y: 0.68, w: 0.3, h: 0.29, type: "panel" },
    ],
  },
  {
    id: "dialogue-heavy",
    name: "Dialogue Heavy",
    description: "Smaller panels optimized for conversation scenes",
    genre: ["drama", "slice-of-life", "romance"],
    maxPanels: 8,
    cells: [
      { x: 0.02, y: 0.02, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.51, y: 0.02, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.02, y: 0.26, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.51, y: 0.26, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.02, y: 0.5, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.51, y: 0.5, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.02, y: 0.74, w: 0.47, h: 0.22, type: "panel" },
      { x: 0.51, y: 0.74, w: 0.47, h: 0.22, type: "panel" },
    ],
  },
  {
    id: "cinematic-widescreen",
    name: "Cinematic Widescreen",
    description: "Wide cinematic panels for dramatic moments",
    genre: ["action", "scifi", "noir"],
    maxPanels: 4,
    cells: [
      { x: 0.02, y: 0.02, w: 0.96, h: 0.22, type: "panel" },
      { x: 0.02, y: 0.26, w: 0.96, h: 0.22, type: "panel" },
      { x: 0.02, y: 0.5, w: 0.96, h: 0.22, type: "panel" },
      { x: 0.02, y: 0.74, w: 0.96, h: 0.22, type: "panel" },
    ],
  },
];

/**
 * Select best layout pattern based on panel count and genre preference
 */
export function selectBestPattern(
  panelCount: number,
  genre?: string,
  preference?: string
): LayoutPattern {
  // If preference provided, use it
  if (preference) {
    const preferred = LAYOUT_PATTERNS.find((p) => p.id === preference);
    if (preferred && preferred.maxPanels >= panelCount) {
      return preferred;
    }
  }

  // Filter patterns that can accommodate the panel count
  const suitable = LAYOUT_PATTERNS.filter((p) => p.maxPanels >= panelCount);

  // If genre specified, prioritize patterns matching that genre
  if (genre) {
    const genreMatches = suitable.filter(
      (p) => p.genre.includes(genre) || p.genre.includes("all")
    );
    if (genreMatches.length > 0) {
      // Return the pattern with the smallest maxPanels that fits
      return genreMatches.reduce((best, current) =>
        current.maxPanels < best.maxPanels ? current : best
      );
    }
  }

  // Return the pattern with the smallest maxPanels that fits
  if (suitable.length > 0) {
    return suitable.reduce((best, current) =>
      current.maxPanels < best.maxPanels ? current : best
    );
  }

  // Fallback to grid-2x2
  return LAYOUT_PATTERNS[0];
}

import type { PageLayout } from "@/types";

/**
 * Auto-layout algorithm: distribute panels across pages using layout patterns
 */
export function autoLayoutPages(
  panels: { panelId: string; panelNumber: number }[],
  pageSize: PageSize,
  genre?: string,
  patternPreference?: string
): PageLayout[] {
  const pages: PageLayout[] = [];

  let remainingPanels = [...panels];
  let pageNum = 1;

  while (remainingPanels.length > 0) {
    // Select best pattern for remaining panel count
    const pattern = selectBestPattern(
      remainingPanels.length,
      genre,
      patternPreference
    );

    // Get panels for this page (up to pattern.maxPanels)
    const panelsForPage = remainingPanels.splice(0, pattern.maxPanels);

    // Assign layout cells to panels
    const panelsWithLayout = panelsForPage.map((panel, index) => ({
      panelId: panel.panelId,
      panelNumber: panel.panelNumber,
      layoutCell: pattern.cells[index] || pattern.cells[pattern.cells.length - 1],
    }));

    pages.push({
      pageNumber: pageNum,
      patternId: pattern.id,
      pattern,
      panels: panelsWithLayout,
      width: pageSize.width,
      height: pageSize.height,
    });

    pageNum++;
  }

  return pages;
}

/**
 * Get layout patterns suitable for a specific genre
 */
export function getPatternsByGenre(genre: string): LayoutPattern[] {
  return LAYOUT_PATTERNS.filter(
    (p) => p.genre.includes(genre) || p.genre.includes("all")
  );
}

/**
 * Calculate pixel position from relative layout cell
 */
export function calculatePixelPosition(
  cell: LayoutCell,
  pageWidth: number,
  pageHeight: number
): { x: number; y: number; width: number; height: number } {
  return {
    x: Math.round(cell.x * pageWidth),
    y: Math.round(cell.y * pageHeight),
    width: Math.round(cell.w * pageWidth),
    height: Math.round(cell.h * pageHeight),
  };
}
