/**
 * Main Layout Export Function
 *
 * Generates clean, semantic HTML and CSS from canvas elements.
 * Uses layoutAnalyzer for smart positioning detection.
 */

import type { CanvasElement, ContainerSettings, CurrencyElement, DiscountBadgeElement, TextElement } from "@/types";
import { analyzeLayout, type AlignmentInfo } from "../layoutAnalyzer";
import type { ExportResult } from "./types";
import {
  isPriceElement,
  isVariablePriceRangeElement,
  isCurrencyElement,
  isDiscountBadgeElement,
  isTextElement,
  BREAKPOINTS,
} from "./types";
import { getClassName, generateBaseElementCSS, generateAbsoluteCSS, alignmentToCSS } from "./utils";
import { generateElementHTML } from "./htmlGenerators";
import { generateDecimalCSS, generateLineThroughCSS, generateVariablePriceRangeCSS } from "./cssGenerators";
import {
  generateResponsiveContainerRules,
  collectElementResponsiveRules,
  generateMediaQueryCSS,
  generateResponsiveDecimalRules,
  generateResponsiveVariableRangeRules,
} from "./responsiveGenerators";

/**
 * Generate animation CSS if needed
 * Note: countUp animation is handled via JavaScript, not CSS
 */
function generateAnimationCSS(el: CanvasElement): string {
  // countUp uses JavaScript, not CSS animations
  if (el.animation.type === "none" || el.animation.type === "countUp") return "";

  const className = getClassName(el.type);
  const { duration, delay, easing } = el.animation;

  const keyframes: Record<string, string> = {
    fadeIn: `@keyframes oppb-fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}`,
    slideIn: `@keyframes oppb-slideIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}`,
    scaleIn: `@keyframes oppb-scaleIn {
  from { opacity: 0; transform: scale(0.9); }
  to { opacity: 1; transform: scale(1); }
}`,
    pulse: `@keyframes oppb-pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}`,
    glow: `@keyframes oppb-glow {
  0%, 100% { box-shadow: 0 0 5px currentColor; }
  50% { box-shadow: 0 0 20px currentColor; }
}`,
  };

  const animationName = `oppb-${el.animation.type}`;
  const keyframe = keyframes[el.animation.type];

  if (!keyframe) return "";

  return `${keyframe}

.${className} {
  animation: ${animationName} ${duration}ms ${easing} ${delay}ms;
  ${
    el.animation.type === "pulse" || el.animation.type === "glow"
      ? "animation-iteration-count: infinite;"
      : "animation-fill-mode: forwards;"
  }
}`;
}

/**
 * Generate CSS for container only (used in custom HTML mode)
 */
function generateContainerOnlyCSS(containerSettings: ContainerSettings): string {
  const cssRules: string[] = [`/* Opus Price Builder - Custom HTML Mode */`, ""];

  const containerCSSProps: string[] = ["position: relative", "display: inline-block"];

  const { padding, margin, border, backgroundColor, backgroundImage, backgroundSize, backgroundPosition, backgroundRepeat } =
    containerSettings;

  if (padding.top.desktop || padding.right.desktop || padding.bottom.desktop || padding.left.desktop) {
    containerCSSProps.push(
      `padding: ${padding.top.desktop}px ${padding.right.desktop}px ${padding.bottom.desktop}px ${padding.left.desktop}px`,
    );
  }

  if (margin.top.desktop || margin.right.desktop || margin.bottom.desktop || margin.left.desktop) {
    containerCSSProps.push(`margin: ${margin.top.desktop}px ${margin.right.desktop}px ${margin.bottom.desktop}px ${margin.left.desktop}px`);
  }

  if (border.width.desktop > 0) {
    containerCSSProps.push(`border: ${border.width.desktop}px ${border.style} ${border.color}`);
  }

  if (border.radius > 0) {
    containerCSSProps.push(`border-radius: ${border.radius}px`);
  }

  if (backgroundColor && backgroundColor !== "transparent") {
    containerCSSProps.push(`background-color: ${backgroundColor}`);
  }

  if (backgroundImage) {
    containerCSSProps.push(`background-image: url(${backgroundImage})`);
    containerCSSProps.push(`background-size: ${backgroundSize}`);
    containerCSSProps.push(`background-position: ${backgroundPosition}`);
    containerCSSProps.push(`background-repeat: ${backgroundRepeat}`);
  }

  cssRules.push(`.oppb-price-container {
  ${containerCSSProps.join(";\n  ")};
}`);

  const tabletRules = new Map<string, string[]>();
  const mobileRules = new Map<string, string[]>();

  const tabletContainerRules = generateResponsiveContainerRules(containerSettings, "tablet");
  const mobileContainerRules = generateResponsiveContainerRules(containerSettings, "mobile");

  if (tabletContainerRules.length > 0) {
    tabletRules.set(".oppb-price-container", tabletContainerRules);
  }
  if (mobileContainerRules.length > 0) {
    mobileRules.set(".oppb-price-container", mobileContainerRules);
  }

  const mediaQueryCSS = generateMediaQueryCSS(tabletRules, mobileRules);
  if (mediaQueryCSS) {
    cssRules.push(mediaQueryCSS);
  }

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

/**
 * Generate layout with column-based structure
 */
function generateColumnLayout(
  analysis: ReturnType<typeof analyzeLayout>,
  visibleElements: CanvasElement[],
  containerSettings?: ContainerSettings,
): ExportResult {
  const cssRules: string[] = [`/* Opus Price Builder - Generated CSS (Column Layout) */`, ""];
  cssRules.push(
    ".oppb-regular-price__decimal,",
    ".oppb-sale-price__decimal {",
    "  white-space: nowrap;",
    "}",
    "",
  );

  const hasAbsolute = analysis.absoluteElements.length > 0;

  const containerCSSProps: string[] = [
    "position: relative",
    "display: inline-flex",
    "flex-direction: row",
    `align-items: ${analysis.containerAlignItems || "center"}`,
    `gap: ${analysis.columnGap}px`,
  ];

  if (hasAbsolute) {
    const minWidth = Math.round(analysis.containerBounds.width);
    const minHeight = Math.round(analysis.containerBounds.height);
    containerCSSProps.push(`--oppb-min-width: ${minWidth}px`);
    containerCSSProps.push(`--oppb-min-height: ${minHeight}px`);
    containerCSSProps.push(`min-width: var(--oppb-min-width)`);
    containerCSSProps.push(`min-height: var(--oppb-min-height)`);
  }

  if (containerSettings) {
    const { padding, margin, border, backgroundColor, backgroundImage, backgroundSize, backgroundPosition, backgroundRepeat } =
      containerSettings;

    if (padding.top.desktop || padding.right.desktop || padding.bottom.desktop || padding.left.desktop) {
      containerCSSProps.push(
        `padding: ${padding.top.desktop}px ${padding.right.desktop}px ${padding.bottom.desktop}px ${padding.left.desktop}px`,
      );
    }

    if (margin.top.desktop || margin.right.desktop || margin.bottom.desktop || margin.left.desktop) {
      containerCSSProps.push(
        `margin: ${margin.top.desktop}px ${margin.right.desktop}px ${margin.bottom.desktop}px ${margin.left.desktop}px`,
      );
    }

    if (border.width.desktop > 0) {
      containerCSSProps.push(`border: ${border.width.desktop}px ${border.style} ${border.color}`);
    }

    if (border.radius > 0) {
      containerCSSProps.push(`border-radius: ${border.radius}px`);
    }

    if (backgroundColor && backgroundColor !== "transparent") {
      containerCSSProps.push(`background-color: ${backgroundColor}`);
    }

    if (backgroundImage) {
      containerCSSProps.push(`background-image: url(${backgroundImage})`);
      containerCSSProps.push(`background-size: ${backgroundSize}`);
      containerCSSProps.push(`background-position: ${backgroundPosition}`);
      containerCSSProps.push(`background-repeat: ${backgroundRepeat}`);
    }
  }

  cssRules.push(`.oppb-price-container {
  ${containerCSSProps.join(";\n  ")};
}`);

  analysis.columns.forEach((col, colIndex) => {
    const colClass = `.oppb-price-column--${colIndex + 1}`;

    const colCSSProps: string[] = [
      "display: inline-flex",
      "flex-direction: column",
      `align-items: flex-start`,
      `justify-content: ${col.verticalAlign}`,
    ];

    if (col.rows.length > 1) {
      colCSSProps.push(`gap: ${analysis.rowGap}px`);
    }

    cssRules.push("");
    cssRules.push(`${colClass} {
  ${colCSSProps.join(";\n  ")};
}`);

    col.rows.forEach((row, rowIndex) => {
      if (row.elements.length > 1 || col.rows.length > 1) {
        const rowClass = `${colClass} .oppb-price-row--${rowIndex + 1}`;
        const alignItems = alignmentToCSS(row.alignment.vertical);
        const justifyContent = row.alignment.horizontal || "flex-start";

        cssRules.push("");
        cssRules.push(`${rowClass} {
  display: inline-flex;
  align-items: ${alignItems};
  justify-content: ${justifyContent};
  gap: ${row.recommendedGap}px;
}`);

        if (row.alignment.vertical === "custom") {
          row.alignment.offsets.forEach((offset, elementId) => {
            const el = row.elements.find((e) => e.id === elementId);
            if (el) {
              const className = getClassName(el.type);
              if (offset.top > 0) {
                cssRules.push(`${rowClass} .${className} { margin-top: ${offset.top}px; }`);
              } else if (offset.bottom > 0) {
                cssRules.push(`${rowClass} .${className} { margin-bottom: ${offset.bottom}px; }`);
              }
            }
          });
        }
      }
    });
  });

  // Generate element CSS
  visibleElements.forEach((el) => {
    const className = getClassName(el.type);
    const isAbsolute = el.positionType === "absolute";

    cssRules.push("");

    if (isAbsolute) {
      cssRules.push(`.${className} {
  ${generateAbsoluteCSS(el, analysis.containerBounds)};
  ${generateBaseElementCSS(el)};
}`);
    } else {
      cssRules.push(`.${className} {
  ${generateBaseElementCSS(el)};
}`);
    }

    if (isPriceElement(el)) {
      const decimalCSS = generateDecimalCSS(el);
      if (decimalCSS) cssRules.push("", decimalCSS);

      const lineThroughCSS = generateLineThroughCSS(el);
      if (lineThroughCSS) cssRules.push("", lineThroughCSS);
    }

    if (isVariablePriceRangeElement(el)) {
      const variableRangeCSS = generateVariablePriceRangeCSS(el);
      if (variableRangeCSS) cssRules.push("", variableRangeCSS);
    }

    if (isDiscountBadgeElement(el) && el.format === "custom" && el.customFormat?.includes("\n")) {
      cssRules.push("");
      cssRules.push(`.${className} {
  display: flex;
  flex-direction: column;
  align-items: center;
}`);
      cssRules.push("");
      cssRules.push(`.oppb-discount-line {
  display: block;
}`);
    }

    if (isCurrencyElement(el) && el.useCustomImage && el.customImageUrl) {
      cssRules.push("");
      cssRules.push(`.${className}__img {
  height: ${el.typography.fontSize.desktop}px;
  width: auto;
  display: block;
}`);
    }
  });

  // Responsive rules
  const tabletRules = new Map<string, string[]>();
  const mobileRules = new Map<string, string[]>();

  if (containerSettings) {
    const tabletContainerRules = generateResponsiveContainerRules(
      containerSettings,
      "tablet",
      hasAbsolute ? analysis.containerBounds : undefined,
    );
    const mobileContainerRules = generateResponsiveContainerRules(
      containerSettings,
      "mobile",
      hasAbsolute ? analysis.containerBounds : undefined,
    );

    if (tabletContainerRules.length > 0) {
      tabletRules.set(".oppb-price-container", tabletContainerRules);
    }
    if (mobileContainerRules.length > 0) {
      mobileRules.set(".oppb-price-container", mobileContainerRules);
    }
  }

  visibleElements.forEach((el) => {
    const className = `.${getClassName(el.type)}`;

    const tabletElementRules = collectElementResponsiveRules(el, "tablet");
    const mobileElementRules = collectElementResponsiveRules(el, "mobile");

    if (tabletElementRules.length > 0) {
      tabletRules.set(className, tabletElementRules);
    }
    if (mobileElementRules.length > 0) {
      mobileRules.set(className, mobileElementRules);
    }

    if (isPriceElement(el) && el.decimal?.show && el.decimal.position !== "inline") {
      const decimalSelector = `${className}__decimal`;

      const tabletDecimalRules = generateResponsiveDecimalRules(el, "tablet");
      const mobileDecimalRules = generateResponsiveDecimalRules(el, "mobile");

      if (tabletDecimalRules.length > 0) {
        tabletRules.set(decimalSelector, tabletDecimalRules);
      }
      if (mobileDecimalRules.length > 0) {
        mobileRules.set(decimalSelector, mobileDecimalRules);
      }
    }

    if (isVariablePriceRangeElement(el)) {
      const tabletVarRules = generateResponsiveVariableRangeRules(el, "tablet");
      const mobileVarRules = generateResponsiveVariableRangeRules(el, "mobile");

      tabletVarRules.forEach((rules, selector) => {
        const existing = tabletRules.get(selector) || [];
        tabletRules.set(selector, [...existing, ...rules]);
      });
      mobileVarRules.forEach((rules, selector) => {
        const existing = mobileRules.get(selector) || [];
        mobileRules.set(selector, [...existing, ...rules]);
      });
    }

    if (isCurrencyElement(el) && el.useCustomImage && el.customImageUrl) {
      const imgSelector = `${className}__img`;

      if (el.typography.fontSize.tablet !== el.typography.fontSize.desktop) {
        const existingTablet = tabletRules.get(imgSelector) || [];
        existingTablet.push(`height: ${el.typography.fontSize.tablet}px`);
        tabletRules.set(imgSelector, existingTablet);
      }
      if (el.typography.fontSize.mobile !== el.typography.fontSize.desktop) {
        const existingMobile = mobileRules.get(imgSelector) || [];
        existingMobile.push(`height: ${el.typography.fontSize.mobile}px`);
        mobileRules.set(imgSelector, existingMobile);
      }
    }
  });

  const mediaQueryCSS = generateMediaQueryCSS(tabletRules, mobileRules);
  if (mediaQueryCSS) {
    cssRules.push(mediaQueryCSS);
  }

  // Generate HTML
  const htmlLines: string[] = [`<span class="oppb-price-container">`];
  const webComponentLines: string[] = [`<span class="oppb-price-container">`];

  analysis.columns.forEach((col, colIndex) => {
    const colClass = `oppb-price-column oppb-price-column--${colIndex + 1}`;
    htmlLines.push(`  <span class="${colClass}">`);
    webComponentLines.push(`  <span class="${colClass}">`);

    col.rows.forEach((row, rowIndex) => {
      if (row.elements.length > 1 || col.rows.length > 1) {
        const rowClass = `oppb-price-row oppb-price-row--${rowIndex + 1}`;
        htmlLines.push(`    <span class="${rowClass}">`);
        webComponentLines.push(`    <span class="${rowClass}">`);

        row.elements.forEach((el) => {
          htmlLines.push(`      ${generateElementHTML(el, false)}`);
          webComponentLines.push(`      ${generateElementHTML(el, true)}`);
        });

        htmlLines.push(`    </span>`);
        webComponentLines.push(`    </span>`);
      } else if (row.elements.length === 1) {
        htmlLines.push(`    ${generateElementHTML(row.elements[0], false)}`);
        webComponentLines.push(`    ${generateElementHTML(row.elements[0], true)}`);
      }
    });

    htmlLines.push(`  </span>`);
    webComponentLines.push(`  </span>`);
  });

  analysis.absoluteElements.forEach(({ element }) => {
    htmlLines.push(`  ${generateElementHTML(element, false)}`);
    webComponentLines.push(`  ${generateElementHTML(element, true)}`);
  });

  htmlLines.push(`</span>`);
  webComponentLines.push(`</span>`);

  return {
    html: htmlLines.join("\n"),
    css: cssRules.join("\n"),
    webComponentHtml: webComponentLines.join("\n"),
  };
}

/**
 * Generate traditional row-based layout
 */
function generateRowLayout(
  analysis: ReturnType<typeof analyzeLayout>,
  visibleElements: CanvasElement[],
  containerSettings?: ContainerSettings,
): ExportResult {
  const cssRules: string[] = [`/* Opus Price Builder - Generated CSS */`, ""];
  cssRules.push(
    ".oppb-regular-price__decimal,",
    ".oppb-sale-price__decimal {",
    "  white-space: nowrap;",
    "}",
    "",
  );

  const hasAbsolute = analysis.absoluteElements.length > 0;

  let containerHorizontalAlign = "flex-start";
  if (analysis.rows.length > 0) {
    const rowAlignments = analysis.rows.map((r) => r.alignment.horizontal || "flex-start");
    const allSame = rowAlignments.every((a) => a === rowAlignments[0]);
    if (allSame) {
      containerHorizontalAlign = rowAlignments[0];
    }
  }

  const containerCSSProps: string[] = [
    "position: relative",
    "display: inline-flex",
    "flex-direction: column",
    `align-items: ${containerHorizontalAlign}`,
    `gap: ${analysis.rowGap}px`,
  ];

  if (hasAbsolute) {
    const minWidth = Math.round(analysis.containerBounds.width);
    const minHeight = Math.round(analysis.containerBounds.height);
    containerCSSProps.push(`--oppb-min-width: ${minWidth}px`);
    containerCSSProps.push(`--oppb-min-height: ${minHeight}px`);
    containerCSSProps.push(`min-width: var(--oppb-min-width)`);
    containerCSSProps.push(`min-height: var(--oppb-min-height)`);
  }

  if (containerSettings) {
    const { padding, margin, border, backgroundColor, backgroundImage, backgroundSize, backgroundPosition, backgroundRepeat } =
      containerSettings;

    if (padding.top.desktop || padding.right.desktop || padding.bottom.desktop || padding.left.desktop) {
      containerCSSProps.push(
        `padding: ${padding.top.desktop}px ${padding.right.desktop}px ${padding.bottom.desktop}px ${padding.left.desktop}px`,
      );
    }

    if (margin.top.desktop || margin.right.desktop || margin.bottom.desktop || margin.left.desktop) {
      containerCSSProps.push(
        `margin: ${margin.top.desktop}px ${margin.right.desktop}px ${margin.bottom.desktop}px ${margin.left.desktop}px`,
      );
    }

    if (border.width.desktop > 0) {
      containerCSSProps.push(`border: ${border.width.desktop}px ${border.style} ${border.color}`);
    }

    if (border.radius > 0) {
      containerCSSProps.push(`border-radius: ${border.radius}px`);
    }

    if (backgroundColor && backgroundColor !== "transparent") {
      containerCSSProps.push(`background-color: ${backgroundColor}`);
    }

    if (backgroundImage) {
      containerCSSProps.push(`background-image: url(${backgroundImage})`);
      containerCSSProps.push(`background-size: ${backgroundSize}`);
      containerCSSProps.push(`background-position: ${backgroundPosition}`);
      containerCSSProps.push(`background-repeat: ${backgroundRepeat}`);
    }
  }

  cssRules.push(`.oppb-price-container {
  ${containerCSSProps.join(";\n  ")};
}`);

  // Row CSS
  analysis.rows.forEach((row, rowIndex) => {
    const rowClass = analysis.rows.length > 1 ? `.oppb-price-row--${rowIndex + 1}` : ".oppb-price-row";
    const alignItems = alignmentToCSS(row.alignment.vertical);
    const justifyContent = row.alignment.horizontal || "flex-start";

    const needsFullWidth = justifyContent !== "flex-start";

    cssRules.push("");
    cssRules.push(`${rowClass} {
  display: inline-flex;
  align-items: ${alignItems};
  justify-content: ${justifyContent};${needsFullWidth ? "\n  width: 100%;" : ""}
  gap: ${row.recommendedGap}px;
}`);

    if (row.alignment.vertical === "custom") {
      row.alignment.offsets.forEach((offset, elementId) => {
        const el = row.elements.find((e) => e.id === elementId);
        if (el) {
          const className = getClassName(el.type);
          if (offset.top > 0) {
            cssRules.push("");
            cssRules.push(`/* Vertical offset for ${el.name} */`);
            cssRules.push(`${rowClass} .${className} { margin-top: ${offset.top}px; }`);
          } else if (offset.bottom > 0) {
            cssRules.push("");
            cssRules.push(`/* Vertical offset for ${el.name} */`);
            cssRules.push(`${rowClass} .${className} { margin-bottom: ${offset.bottom}px; }`);
          }
        }
      });
    }
  });

  // Element CSS
  visibleElements.forEach((el) => {
    const className = getClassName(el.type);
    const isAbsolute = el.positionType === "absolute";

    cssRules.push("");

    if (isAbsolute) {
      cssRules.push(`.${className} {
  ${generateAbsoluteCSS(el, analysis.containerBounds)};
  ${generateBaseElementCSS(el)};
}`);
    } else {
      cssRules.push(`.${className} {
  ${generateBaseElementCSS(el)};
}`);
    }

    if (isPriceElement(el)) {
      const decimalCSS = generateDecimalCSS(el);
      if (decimalCSS) cssRules.push("", decimalCSS);

      const lineThroughCSS = generateLineThroughCSS(el);
      if (lineThroughCSS) cssRules.push("", lineThroughCSS);
    }

    if (isVariablePriceRangeElement(el)) {
      const variableRangeCSS = generateVariablePriceRangeCSS(el);
      if (variableRangeCSS) cssRules.push("", variableRangeCSS);
    }

    if (isDiscountBadgeElement(el) && el.format === "custom" && el.customFormat?.includes("\n")) {
      cssRules.push("");
      cssRules.push(`.${className} {
  display: flex;
  flex-direction: column;
  align-items: center;
}`);
      cssRules.push("");
      cssRules.push(`.oppb-discount-line {
  display: block;
}`);
    }

    if (isTextElement(el)) {
      const textRules: string[] = [];
      textRules.push(`text-align: ${el.textAlign}`);

      if (el.widthMode === "full") {
        textRules.push("width: 100%");
      } else if (el.widthMode === "custom") {
        textRules.push(`width: ${el.customWidth}px`);
      }

      textRules.push("white-space: pre-wrap");

      if (el.backgroundImage) {
        textRules.push(`background-image: url('${el.backgroundImage}')`);
        textRules.push(`background-size: ${el.backgroundSize}`);
        textRules.push(`background-position: ${el.backgroundPosition}`);
        textRules.push(`background-repeat: ${el.backgroundRepeat}`);
      }

      cssRules.push("");
      cssRules.push(`.${className} {
  ${textRules.join(";\n  ")};
}`);

      if (el.text?.includes("\n")) {
        cssRules.push("");
        cssRules.push(`.oppb-text-line {
  display: block;
}`);
      }
    }

    if (isCurrencyElement(el) && el.useCustomImage && el.customImageUrl) {
      cssRules.push("");
      cssRules.push(`.${className}__img {
  height: ${el.typography.fontSize.desktop}px;
  width: auto;
  vertical-align: middle;
}`);
    }

    const animationCSS = generateAnimationCSS(el);
    if (animationCSS) cssRules.push("", animationCSS);
  });

  // Responsive CSS
  const tabletRules = new Map<string, string[]>();
  const mobileRules = new Map<string, string[]>();

  if (containerSettings) {
    const tabletContainerRules = generateResponsiveContainerRules(
      containerSettings,
      "tablet",
      hasAbsolute ? analysis.containerBounds : undefined,
    );
    const mobileContainerRules = generateResponsiveContainerRules(
      containerSettings,
      "mobile",
      hasAbsolute ? analysis.containerBounds : undefined,
    );

    if (tabletContainerRules.length > 0) {
      tabletRules.set(".oppb-price-container", tabletContainerRules);
    }
    if (mobileContainerRules.length > 0) {
      mobileRules.set(".oppb-price-container", mobileContainerRules);
    }
  }

  visibleElements.forEach((el) => {
    const className = `.${getClassName(el.type)}`;

    const tabletElementRules = collectElementResponsiveRules(el, "tablet");
    const mobileElementRules = collectElementResponsiveRules(el, "mobile");

    if (tabletElementRules.length > 0) {
      tabletRules.set(className, tabletElementRules);
    }
    if (mobileElementRules.length > 0) {
      mobileRules.set(className, mobileElementRules);
    }

    if (isPriceElement(el) && el.decimal?.show && el.decimal.position !== "inline") {
      const decimalSelector = `${className}__decimal`;

      const tabletDecimalRules = generateResponsiveDecimalRules(el, "tablet");
      const mobileDecimalRules = generateResponsiveDecimalRules(el, "mobile");

      if (tabletDecimalRules.length > 0) {
        tabletRules.set(decimalSelector, tabletDecimalRules);
      }
      if (mobileDecimalRules.length > 0) {
        mobileRules.set(decimalSelector, mobileDecimalRules);
      }
    }

    if (isVariablePriceRangeElement(el)) {
      const tabletVarRules = generateResponsiveVariableRangeRules(el, "tablet");
      const mobileVarRules = generateResponsiveVariableRangeRules(el, "mobile");

      tabletVarRules.forEach((rules, selector) => {
        const existing = tabletRules.get(selector) || [];
        tabletRules.set(selector, [...existing, ...rules]);
      });
      mobileVarRules.forEach((rules, selector) => {
        const existing = mobileRules.get(selector) || [];
        mobileRules.set(selector, [...existing, ...rules]);
      });
    }

    if (isCurrencyElement(el) && el.useCustomImage && el.customImageUrl) {
      const imgSelector = `${className}__img`;

      if (el.typography.fontSize.tablet !== el.typography.fontSize.desktop) {
        const existingTablet = tabletRules.get(imgSelector) || [];
        existingTablet.push(`height: ${el.typography.fontSize.tablet}px`);
        tabletRules.set(imgSelector, existingTablet);
      }
      if (el.typography.fontSize.mobile !== el.typography.fontSize.desktop) {
        const existingMobile = mobileRules.get(imgSelector) || [];
        existingMobile.push(`height: ${el.typography.fontSize.mobile}px`);
        mobileRules.set(imgSelector, existingMobile);
      }
    }
  });

  const mediaQueryCSS = generateMediaQueryCSS(tabletRules, mobileRules);
  if (mediaQueryCSS) {
    cssRules.push(mediaQueryCSS);
  }

  // Generate HTML
  const htmlLines: string[] = [`<span class="oppb-price-container">`];
  const webComponentLines: string[] = [`<span class="oppb-price-container">`];

  analysis.rows.forEach((row, rowIndex) => {
    const rowClass = analysis.rows.length > 1 ? `oppb-price-row oppb-price-row--${rowIndex + 1}` : "oppb-price-row";

    if (row.elements.length > 1) {
      htmlLines.push(`  <span class="${rowClass}">`);
      webComponentLines.push(`  <span class="${rowClass}">`);

      row.elements.forEach((el) => {
        htmlLines.push(`    ${generateElementHTML(el, false)}`);
        webComponentLines.push(`    ${generateElementHTML(el, true)}`);
      });

      htmlLines.push(`  </span>`);
      webComponentLines.push(`  </span>`);
    } else if (row.elements.length === 1) {
      if (analysis.rows.length > 1) {
        htmlLines.push(`  <span class="${rowClass}">`);
        webComponentLines.push(`  <span class="${rowClass}">`);
        htmlLines.push(`    ${generateElementHTML(row.elements[0], false)}`);
        webComponentLines.push(`    ${generateElementHTML(row.elements[0], true)}`);
        htmlLines.push(`  </span>`);
        webComponentLines.push(`  </span>`);
      } else {
        htmlLines.push(`  ${generateElementHTML(row.elements[0], false)}`);
        webComponentLines.push(`  ${generateElementHTML(row.elements[0], true)}`);
      }
    }
  });

  analysis.absoluteElements.forEach(({ element }) => {
    htmlLines.push(`  ${generateElementHTML(element, false)}`);
    webComponentLines.push(`  ${generateElementHTML(element, true)}`);
  });

  htmlLines.push(`</span>`);
  webComponentLines.push(`</span>`);

  return {
    html: htmlLines.join("\n"),
    css: cssRules.join("\n"),
    webComponentHtml: webComponentLines.join("\n"),
  };
}

/**
 * Main export function - uses layout analyzer for smart CSS generation
 */
export function exportLayout(elements: CanvasElement[], containerSettings?: ContainerSettings): ExportResult {
  // Filter visible elements only
  const visibleElements = elements.filter((el) => el.visible);

  if (visibleElements.length === 0) {
    return {
      html: "<!-- No visible elements -->",
      css: "",
      webComponentHtml: "<!-- No visible elements -->",
    };
  }

  // Analyze layout
  const analysis = analyzeLayout(visibleElements);

  // Route to column or row layout generator
  if (analysis.layoutType === "columns" && analysis.columns.length >= 2) {
    return generateColumnLayout(analysis, visibleElements, containerSettings);
  }

  return generateRowLayout(analysis, visibleElements, containerSettings);
}
