/**
 * TextElementRenderer Component
 *
 * Renders text elements with:
 * - Multiline text support
 * - Text alignment (left, center, right, justify)
 * - Various width modes (auto, full, custom)
 */

import { Text } from "react-konva";
import type { TextElement } from "@/types";
import { getCanvasFontFamily } from "@/types";
import { useGoogleFont } from "@/hooks/useGoogleFonts";

interface TextElementRendererProps {
  element: TextElement;
}

// Build Konva fontStyle string
const buildFontStyle = (element: TextElement): string => {
  const parts: string[] = [];

  if (element.typography.fontWeight.desktop >= 700) {
    parts.push("bold");
  } else if (element.typography.fontWeight.desktop <= 300) {
    parts.push("300");
  }

  if (element.typography.fontStyle === "italic") {
    parts.push("italic");
  }

  return parts.join(" ") || "normal";
};

// Get display text with text transform applied
const getDisplayText = (element: TextElement): string => {
  const text = element.text || "Your text here";

  // Apply text transform
  switch (element.typography.textTransform) {
    case "uppercase":
      return text.toUpperCase();
    case "lowercase":
      return text.toLowerCase();
    case "capitalize":
      return text
        .split(" ")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
    default:
      return text;
  }
};

export function TextElementRenderer({ element }: TextElementRendererProps) {
  // Load Google font if needed - triggers re-render when font is ready
  useGoogleFont(element.typography.fontFamily);

  // Get canvas-safe font family (undefined for default)
  const fontFamily = getCanvasFontFamily(element.typography.fontFamily);

  const displayText = getDisplayText(element);

  // Calculate effective width for text wrapping
  // For auto mode, we don't set width (text flows naturally)
  // For full and custom modes, we set width minus padding
  const effectiveWidth =
    element.widthMode === "auto" || !element.size
      ? undefined
      : element.size.width - element.padding.left.desktop - element.padding.right.desktop;

  // Position text with padding offset
  return (
    <Text
      x={element.padding.left.desktop}
      y={element.padding.top.desktop}
      text={displayText}
      fill={element.color}
      fontFamily={fontFamily}
      fontSize={element.typography.fontSize.desktop}
      fontStyle={buildFontStyle(element)}
      lineHeight={element.typography.lineHeight}
      letterSpacing={element.typography.letterSpacing.desktop}
      textDecoration={element.typography.textDecoration === "none" ? "" : element.typography.textDecoration}
      align={element.textAlign}
      verticalAlign={element.verticalAlign}
      width={effectiveWidth}
      wrap={element.widthMode === "auto" ? "none" : "word"}
      listening={false}
    />
  );
}
