/**
 * ElementRenderer Component
 *
 * Main entry point for rendering canvas elements.
 * Wraps elements in BaseElement and dispatches to the correct renderer.
 */

import {BaseElement} from "./BaseElement";
import {PriceElementRenderer} from "./PriceElementRenderer";
import {CurrencyElementRenderer} from "./CurrencyElementRenderer";
import {DiscountBadgeRenderer} from "./DiscountBadgeRenderer";
import {TextElementRenderer} from "./TextElementRenderer";
import {VariablePriceRangeRenderer} from "./VariablePriceRangeRenderer";
import {DefaultElementRenderer} from "./DefaultElementRenderer";
import {getRenderer} from "./rendererRegistry";
import type {
  CanvasElement,
  PriceElement,
  CurrencyElement,
  DiscountBadgeElement,
  TextElement,
  VariablePriceRangeElement,
} from "@/types";

interface ElementRendererProps {
  element: CanvasElement;
  containerSize: {width: number; height: number};
}

// Type guards
const isPriceElement = (element: CanvasElement): element is PriceElement => {
  return element.type === "regularPrice" || element.type === "salePrice";
};

const isCurrencyElement = (
  element: CanvasElement
): element is CurrencyElement => {
  return element.type === "currencySymbol";
};

const isDiscountBadgeElement = (
  element: CanvasElement
): element is DiscountBadgeElement => {
  return element.type === "discountBadge";
};

const isTextElement = (element: CanvasElement): element is TextElement => {
  return element.type === "text";
};

const isVariablePriceRangeElement = (
  element: CanvasElement
): element is VariablePriceRangeElement => {
  return element.type === "variablePriceRange";
};

/**
 * Get the appropriate renderer content for an element
 */
function getRendererContent(element: CanvasElement) {
  // First check if there's a custom registered renderer
  const CustomRenderer = getRenderer(element.type);
  if (CustomRenderer) {
    return <CustomRenderer element={element} />;
  }

  // Use built-in renderers
  if (isPriceElement(element)) {
    return <PriceElementRenderer element={element} />;
  }

  if (isCurrencyElement(element)) {
    return <CurrencyElementRenderer element={element} />;
  }

  if (isDiscountBadgeElement(element)) {
    return <DiscountBadgeRenderer element={element} />;
  }

  if (isTextElement(element)) {
    return <TextElementRenderer element={element} />;
  }

  if (isVariablePriceRangeElement(element)) {
    return <VariablePriceRangeRenderer element={element} />;
  }

  // Fallback to default renderer
  return <DefaultElementRenderer element={element} />;
}

export function ElementRenderer({
  element,
  containerSize,
}: ElementRendererProps) {
  return (
    <BaseElement element={element} containerSize={containerSize}>
      {getRendererContent(element)}
    </BaseElement>
  );
}
