/**
 * Layout Exporter Utility Functions
 */

import type { CanvasElement, ElementType, ResponsiveValue } from "@/types";
import { isResponsiveValue, getFontCssValue } from "@/types";
import type { AlignmentInfo, ContainerBounds } from "../layoutAnalyzer";

/**
 * Generate CSS class name from element type
 */
export function getClassName(type: ElementType): string {
  const classMap: Record<ElementType, string> = {
    regularPrice: "oppb-regular-price",
    salePrice: "oppb-sale-price",
    variablePriceRange: "oppb-variable-range",
    currencySymbol: "oppb-currency",
    discountBadge: "oppb-discount-badge",
    text: "oppb-text",
  };
  return classMap[type] || "oppb-element";
}

/**
 * Helper to get desktop value from a responsive or plain value
 */
export function getDesktopValue<T>(value: T | ResponsiveValue<T> | undefined, fallback: T): T {
  if (value === undefined) return fallback;
  if (isResponsiveValue(value)) {
    return value.desktop;
  }
  return value as T;
}

/**
 * Convert alignment type to CSS align-items value
 */
export function alignmentToCSS(alignment: AlignmentInfo["vertical"]): string {
  switch (alignment) {
    case "baseline":
      return "baseline";
    case "center":
      return "center";
    case "flex-start":
      return "flex-start";
    case "flex-end":
      return "flex-end";
    case "custom":
      // Custom alignment falls back to center with individual margin adjustments
      return "center";
    default:
      return "baseline";
  }
}

/**
 * Generate CSS for typography (desktop values only - for base CSS)
 */
export function generateTypographyCSS(el: CanvasElement): string {
  const { typography } = el;
  const rules: string[] = [];

  // Only add font-family if not using default (which inherits from theme)
  const fontCssValue = getFontCssValue(typography.fontFamily);
  if (fontCssValue) {
    rules.push(`font-family: ${fontCssValue}`);
  }
  rules.push(`font-size: ${typography.fontSize.desktop}px`);
  rules.push(`font-weight: ${typography.fontWeight.desktop}`);
  if (typography.fontStyle !== "normal") {
    rules.push(`font-style: ${typography.fontStyle}`);
  }
  rules.push(`line-height: ${typography.lineHeight}`);
  if (typography.letterSpacing.desktop !== 0) {
    rules.push(`letter-spacing: ${typography.letterSpacing.desktop}px`);
  }
  if (typography.textTransform !== "none") {
    rules.push(`text-transform: ${typography.textTransform}`);
  }
  if (typography.textDecoration !== "none") {
    rules.push(`text-decoration: ${typography.textDecoration}`);
  }

  return rules.join(";\n  ");
}

/**
 * Generate base CSS for an element (without positioning)
 */
export function generateBaseElementCSS(el: CanvasElement): string {
  const rules: string[] = [];

  // Colors
  rules.push(`color: ${el.color}`);
  if (el.backgroundColor !== "transparent") {
    rules.push(`background-color: ${el.backgroundColor}`);
  }

  // Opacity
  if (el.opacity < 1) {
    rules.push(`opacity: ${el.opacity}`);
  }

  // Typography
  rules.push(generateTypographyCSS(el));

  // Border
  if (el.border.width.desktop > 0) {
    rules.push(`border: ${el.border.width.desktop}px ${el.border.style} ${el.border.color}`);
  }
  if (el.border.radius > 0) {
    rules.push(`border-radius: ${el.border.radius}px`);
  }

  // Padding
  if (el.padding.top.desktop > 0 || el.padding.right.desktop > 0 || el.padding.bottom.desktop > 0 || el.padding.left.desktop > 0) {
    rules.push(
      `padding: ${el.padding.top.desktop}px ${el.padding.right.desktop}px ${el.padding.bottom.desktop}px ${el.padding.left.desktop}px`
    );
  }

  // Margin
  if (el.margin.top.desktop > 0 || el.margin.right.desktop > 0 || el.margin.bottom.desktop > 0 || el.margin.left.desktop > 0) {
    rules.push(`margin: ${el.margin.top.desktop}px ${el.margin.right.desktop}px ${el.margin.bottom.desktop}px ${el.margin.left.desktop}px`);
  }

  // Rotation
  if (el.rotation !== 0) {
    rules.push(`transform: rotate(${el.rotation}deg)`);
  }

  return rules.join(";\n  ");
}

/**
 * Generate CSS for absolute positioned element
 * Positions are rounded to whole pixels for cleaner CSS output
 */
export function generateAbsoluteCSS(el: CanvasElement, containerBounds: ContainerBounds): string {
  const rules: string[] = [];

  rules.push("position: absolute");

  // Calculate position relative to container (rounded to whole pixels)
  const relativeX = Math.round(el.position.x - containerBounds.x);
  const relativeY = Math.round(el.position.y - containerBounds.y);

  rules.push(`left: ${relativeX}px`);
  rules.push(`top: ${relativeY}px`);

  return rules.join(";\n  ");
}

/**
 * Escape HTML special characters
 */
export function escapeHtml(text: string): string {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
}
