// components/fontTransforms.jsx

const unicodeBlocks = {
  sansSerif: { upperStart: 0x1D5A0, lowerStart: 0x1D5BA },
  sansSerifBold: { upperStart: 0x1D5D4, lowerStart: 0x1D5EE },
  script: { upperStart: 0x1D49C, lowerStart: 0x1D4B6 },
  scriptBold: { upperStart: 0x1D4D0, lowerStart: 0x1D4EA },
  fraktur: { upperStart: 0x1D504, lowerStart: 0x1D51E },
  frakturBold: { upperStart: 0x1D56C, lowerStart: 0x1D586 },
  monospace: { upperStart: 0x1D670, lowerStart: 0x1D68A },
  fullwidth: { upperStart: 0xFF21, lowerStart: 0xFF41 }
};

const mapUnicode = (char, block) => {
  const code = char.charCodeAt(0);
  if (code >= 65 && code <= 90) return String.fromCodePoint(block.upperStart + (code - 65));
  if (code >= 97 && code <= 122) return String.fromCodePoint(block.lowerStart + (code - 97));
  return char;
};

const createTransform = (blockKey) => (text) =>
  text.split('').map((c) => mapUnicode(c, unicodeBlocks[blockKey])).join('');

const fontList = [
  "Anton", "Bebas Neue", "Dancing Script", "Montserrat", "Orbitron", "Pacifico",
  "Playfair Display", "Poppins"
];

const getCategory = (name) => {
  const normalizedName = name.toLowerCase().replace(/ /g, "-");
  if (["dancing-script", "pacifico"].includes(normalizedName)) return "handwriting";
  if (["anton", "bebas-neue", "playfair-display"].includes(normalizedName)) return "statement";
  if (["orbitron"].includes(normalizedName)) return "futuristic";
  if (["montserrat", "poppins"].includes(normalizedName)) return "modern";
  return "aesthetic";
};

const blockForCategory = {
  modern: "sansSerif",
  handwriting: "scriptBold",
  statement: "fullwidth",
  futuristic: "monospace",
  aesthetic: "frakturBold"
};

export const fontTransforms = Object.fromEntries(
  fontList.map((font) => {
    const normalizedFont = font.toLowerCase().replace(/ /g, "-");
    const category = getCategory(font);
    return [font, {
      transform: (text) => text, // Echte Fonts verwenden, keine Unicode-Transformation
      category,
      description: `${font} – Echte Schriftart verwendet`,
      className: `font-${normalizedFont}`
    }];
  })
);

export const transformText = (text, fontName) => {
  const font = fontTransforms[fontName];
  if (!font || !text) return { transformed: text, fontClassName: "" };
  return {
    transformed: font.transform(text),
    fontClassName: font.className
  };
};

export const getPopularFonts = () => Object.keys(fontTransforms).slice(0, 5);

export const getFontsByCategory = (category) =>
  category === "all"
    ? Object.keys(fontTransforms)
    : Object.keys(fontTransforms).filter(
        (f) => fontTransforms[f].category === category
      );