export function buildImageUrl(baseName, ext, fallbackUrl, base) {
  if (baseName) {
    const safeBase = base ? base.replace(/\/?$/, "/") : "";
    const safeExt = ext && ext.trim() ? ext.trim() : ".png";
    const finalExt = safeExt.startsWith(".") ? safeExt : "." + safeExt;
    return safeBase + baseName + finalExt;
  }
  if (fallbackUrl) return fallbackUrl;
  return "";
}

export function renderBlockToPug(block, settings) {
  const d = block.data || {};

  switch (block.type) {
    case "spacer": {
      const h = d.height ?? 40;
      return `+spacerLine(${h})`;
    }

    case "titleActual": {
      const text = d.text || "";
      const top = d.topSpacing ?? 40;
      const bottom = d.bottomSpacing ?? 20;
      const addTop = !d.removeTopSpacing;
      const addBottom = !d.removeBottomSpacing;

      let res = "";
      if (addTop) {
        res += `+spacerLine(${top})\n`;
      }

      res +=
        "tr\n" +
        "    td.paddingWrapper \n" +
        '        +defaultTable("100%")\n' +
        "            tr \n" +
        '                td(align="center")\n' +
        `                    span.font.h2.blackText.uppercase ${text}`;

      if (addBottom) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "paragraph": {
      const text = d.text || "";
      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;

      let res =
        "tr \n" +
        "    td.paddingWrapper \n" +
        '        +defaultTable("100%")\n' +
        "            tr \n" +
        '                td(align="center")\n' +
        `                    span.font.h3.blackText ${text}`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "buttonSingle": {
      const t = d.text || "";
      const href = d.href || "#";
      const w = d.width ?? 340;
      const h = d.height ?? 45;
      const bg = d.bgColor || "#242424";
      const fs = d.fontSize ?? 16;
      const color = d.textColor || "#ffffff";
      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;

      let res =
        "////Блок с кнопкой посередине\n" +
        "tr\n" +
        "    td.headerWrapper\n" +
        '        +defaultTable("100%")\n' +
        "            tr\n" +
        '                td(align="center")\n' +
        `                    +buttonRounded("${t}", "${href}", ${w}, ${h}, "${bg}", ${fs}, "${color}", 3, "#000000").bold.font.uppercase.letter`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "buttonDouble": {
      const {
        leftText,
        leftHref,
        rightText,
        rightHref,
        width,
        height,
        gap,
        bgColor,
        fontSize,
        textColor,
        bottomSpacing,
        removeBottomSpacing
      } = d;

      const w = width ?? 275;
      const h = height ?? 45;
      const g = gap ?? 20;
      const bg = bgColor || "#242424";
      const fs = fontSize ?? 16;
      const color = textColor || "#ffffff";
      const bottom = bottomSpacing ?? 40;
      const addSpacing = !removeBottomSpacing;

      let res =
        "//Блок с 2мя кнопками\n\n" +
        "tr \n" +
        "    td.paddingWrapper\n" +
        '        +defaultTable("100%")\n' +
        "            tr \n" +
        '                td(align="right") \n' +
        `                    +buttonRounded("${leftText || ""}", "${leftHref ||
          "#"}", ${w}, ${h}, "${bg}", ${fs}, "${color}", 3, "#000000").bold.font.uppercase.letter\n` +
        `                +tdFixed(${g})\n` +
        '                td(align="left") \n' +
        `                    +buttonRounded("${rightText || ""}", "${rightHref ||
          "#"}", ${w}, ${h}, "${bg}", ${fs}, "${color}", 3, "#000000").bold.font.uppercase.letter`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "buttonTriple": {
      const {
        leftText,
        leftHref,
        centerText,
        centerHref,
        rightText,
        rightHref,
        width,
        height,
        gap,
        bgColor,
        fontSize,
        textColor,
        bottomSpacing,
        removeBottomSpacing
      } = d;

      const w = width ?? 174;
      const h = height ?? 45;
      const g = gap ?? 24;
      const bg = bgColor || "#242424";
      const fs = fontSize ?? 16;
      const color = textColor || "#ffffff";
      const bottom = bottomSpacing ?? 40;
      const addSpacing = !removeBottomSpacing;

      let res =
        "//Блок с 3мя кнопками\n\n" +
        "tr \n" +
        "    td.paddingWrapper \n" +
        '        +defaultTable("100%")\n' +
        "            tr \n" +
        "                td \n" +
        `                    +buttonRounded("${leftText || ""}", "${leftHref ||
          "#"}", ${w}, ${h}, "${bg}", ${fs}, "${color}", 3, "#000000").bold.font.uppercase.letter\n` +
        `                +tdFixed(${g})\n` +
        "                td \n" +
        `                    +buttonRounded("${centerText || ""}", "${centerHref ||
          "#"}", ${w}, ${h}, "${bg}", ${fs}, "${color}", 3, "#000000").bold.font.uppercase.letter\n` +
        `                +tdFixed(${g})\n` +
        "                td \n" +
        `                    +buttonRounded("${rightText || ""}", "${rightHref ||
          "#"}", ${w}, ${h}, "${bg}", ${fs}, "${color}", 3, "#000000").bold.font.uppercase.letter`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "banner": {
      const href = d.href || "#";
      const baseName = d.imageBaseName || "";
      const ext = d.imageExtension || ".png";

      let img = "";
      if (baseName) {
        img = buildImageUrl(baseName, ext, d.imageUrl, settings.imageBaseUrl);
      } else if (d.imageUrl) {
        img = d.imageUrl;
      }

      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;

      let res =
        "////Блок с баннером и ссылкой\n" +
        `+bannerWLink("${href}", "${img}")`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "bannerNoLink": {
      const img = buildImageUrl(
        d.imageBaseName || "",
        d.imageExtension || ".png",
        d.imageUrl,
        settings.imageBaseUrl
      );
      const h = d.height ?? 293;
      const top = d.topSpacing ?? 40;
      const bottom = d.bottomSpacing ?? 0;
      const addSpacing = !d.removeBottomSpacing;

      let res = `+spacerLine(${top})\n+bannerWithoutLink("${img}", ${h})`;

      if (addSpacing && bottom > 0) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "twoBannersWithText": {
      const {
        leftHref,
        leftImage,
        leftImageBaseName,
        leftImageExtension,
        leftText,
        rightHref,
        rightImage,
        rightImageBaseName,
        rightImageExtension,
        rightText,
        width,
        gap,
        bottomSpacing,
        removeBottomSpacing
      } = d;

      const leftImg = buildImageUrl(
        leftImageBaseName || "",
        leftImageExtension || ".png",
        leftImage,
        settings.imageBaseUrl
      );

      const rightImg = buildImageUrl(
        rightImageBaseName || "",
        rightImageExtension || ".png",
        rightImage,
        settings.imageBaseUrl
      );

      const w = width ?? 270;
      const g = gap ?? 30;
      const bottom = bottomSpacing ?? 40;
      const addSpacing = !removeBottomSpacing;

      let res =
        "tr \n" +
        '    td(align="center").paddingWrapper\n' +
        '        +defaultTable("", "center")\n' +
        "            tr \n" +
        "                td \n" +
        "                    //- (Ссылка, изображение, ширина картинки = 270, текст под баннером)\n" +
        `                    +bannerWithLink("${leftHref ||
          "#"}", "${leftImg || ""}", ${w}, "${leftText || ""}")\n` +
        `                +tdFixed(${g})\n` +
        "                td \n" +
        `                    +bannerWithLink("${rightHref ||
          "#"}", "${rightImg || ""}", ${w}, "${rightText || ""}")`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "twoBannersNoText": {
      const {
        leftHref,
        leftImage,
        leftImageBaseName,
        leftImageExtension,
        rightHref,
        rightImage,
        rightImageBaseName,
        rightImageExtension,
        width,
        gap,
        bottomSpacing,
        removeBottomSpacing
      } = d;

      const leftImg = buildImageUrl(
        leftImageBaseName || "",
        leftImageExtension || ".jpg",
        leftImage,
        settings.imageBaseUrl
      );
      const rightImg = buildImageUrl(
        rightImageBaseName || "",
        rightImageExtension || ".jpg",
        rightImage,
        settings.imageBaseUrl
      );

      const w = width ?? 270;
      const g = gap ?? 30;
      const bottom = bottomSpacing ?? 40;
      const addSpacing = !removeBottomSpacing;

      let res =
        "tr \n" +
        '    td(align="center").paddingWrapper\n' +
        '        +defaultTable("", "center")\n' +
        "            tr \n" +
        "                td \n" +
        "                    //- (Ссылка, изображение, ширина изображения = 270)\n" +
        `                    +bannerWithLink("${leftHref ||
          "#"}", "${leftImg || ""}", ${w})\n` +
        `                +tdFixed(${g})\n` +
        "                td \n" +
        `                    +bannerWithLink("${rightHref ||
          "#"}", "${rightImg || ""}", ${w})`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "threeBannersNoText": {
      const {
        href1,
        img1,
        imgBaseName1,
        imgExtension1,
        href2,
        img2,
        imgBaseName2,
        imgExtension2,
        href3,
        img3,
        imgBaseName3,
        imgExtension3,
        width,
        gap,
        bottomSpacing,
        removeBottomSpacing
      } = d;

      const imgOne = buildImageUrl(
        imgBaseName1 || "",
        imgExtension1 || ".png",
        img1,
        settings.imageBaseUrl
      );
      const imgTwo = buildImageUrl(
        imgBaseName2 || "",
        imgExtension2 || ".png",
        img2,
        settings.imageBaseUrl
      );
      const imgThree = buildImageUrl(
        imgBaseName3 || "",
        imgExtension3 || ".png",
        img3,
        settings.imageBaseUrl
      );

      const w = width ?? 170;
      const g = gap ?? 30;
      const bottom = bottomSpacing ?? 40;
      const addSpacing = !removeBottomSpacing;

      let res =
        "tr \n" +
        '    td(align="center").paddingWrapper\n' +
        '        +defaultTable("", "center")\n' +
        "            tr \n" +
        "                td \n" +
        "                    //- (Ссылка, изображение)\n" +
        `                    +bannerWithLink("${href1 ||
          "#"}", "${imgOne || ""}", ${w})\n` +
        `                +tdFixed(${g})\n` +
        "                td \n" +
        `                    +bannerWithLink("${href2 ||
          "#"}", "${imgTwo || ""}", ${w})\n` +
        `                +tdFixed(${g})\n` +
        "                td \n" +
        `                    +bannerWithLink("${href3 ||
          "#"}", "${imgThree || ""}", ${w})`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "products4Row":
    case "products3Row": {
      const idsRaw = d.productIds || "";
      const ids = idsRaw
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean)
        .join(",");
      const showPrices = settings.showPrices !== undefined ? !!settings.showPrices : d.showPrices ?? true;
      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;

      const mixinName = block.type === "products4Row" ? "products4Row" : "products3Row";

      let params = `"${ids}"`;
      if (!showPrices) {
        params += ", {showPrices : false}";
      }

      let res = `+${mixinName}(${params})`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "productsImageLeft":
    case "productsImageRight":
    case "productsImageLeft3":
    case "productsImageRight3": {
      const idsRaw = d.productIds || "";
      const ids = idsRaw
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean)
        .join(",");
      const link = d.link || "#";
      const img = buildImageUrl(
        d.imageBaseName || "",
        d.imageExtension || ".png",
        d.imageUrl,
        settings.imageBaseUrl
      );
      const w = d.imgWidth ?? 275;
      const isThree = block.type === "productsImageLeft3" || block.type === "productsImageRight3";
      const showPrices =
        settings.showPrices !== undefined ? !!settings.showPrices : d.showPrices ?? true;
      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;

      let mixinName;
      if (block.type === "productsImageLeft" || block.type === "productsImageLeft3") {
        mixinName = isThree ? "productsColumnImageLeft" : "productsImageLeft";
      } else {
        mixinName = isThree ? "productsColumnImageRight" : "productsImageRight";
      }

      let options = showPrices === false ? ", {showPrices : false}" : "";

      let res;
      if (isThree) {
        res = `+${mixinName}("${ids}", "${link}", "${img}"${options})`;
      } else {
        res = `+${mixinName}("${ids}", "${link}", "${img}", ${w}${options})`;
      }

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "textImageLeft":
    case "textImageRight": {
      const link = d.link || "#";
      const img = buildImageUrl(
        d.imageBaseName || "",
        d.imageExtension || ".png",
        d.imageUrl,
        settings.imageBaseUrl
      );
      const w = d.imgWidth ?? 264;
      const h = d.imgHeight ?? 330;
      const header = d.header || "";
      const text = d.text || "";
      const btnText = d.buttonText || "";
      const btnHref = d.buttonHref || "#";
      const bottom = d.bottomSpacing ?? 20;
      const addSpacing = !d.removeBottomSpacing;

      const mixinName = block.type === "textImageLeft" ? "textImageLeft" : "textImageRight";

      let res =
        `//Текст ${block.type === "textImageLeft" ? "справа изображение слева" : "слева изображение справа"}\n` +
        `+${mixinName}("${link}", "${img}", ${w}, ${h})\n` +
        '    +defaultTable("100%")\n' +
        "        tr \n" +
        "            td\n" +
        `                span.imageSideHeader.font.bold ${header}\n` +
        "        +spacerLine(18)\n" +
        "        tr \n" +
        "            td \n" +
        `                span.font.imageSideText.font ${text}\n` +
        "        +spacerLine(18)\n" +
        "        tr \n" +
        "            td \n" +
        `                +buttonRounded("${btnText}", "${btnHref}", 160, 45, "#ffffff", 16, "#000000", 3).bold.font`;

      if (addSpacing) {
        res += `\n\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "sizeGrid": {
      const sizesRaw = d.sizes || "";
      const linksRaw = d.links || "";

      const sizesArr = sizesRaw
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);
      const linksArr = linksRaw
        .split(",")
        .map((s) => s.trim())
        .filter(Boolean);

      const sizesString = "[" + sizesArr.map((s) => s).join(", ") + "]";
      const linksString = "[" + linksArr.map((s) => `"${s}"`).join(", ") + "]";

      const bottom = d.bottomSpacing ?? 20;
      const addSpacing = !d.removeBottomSpacing;

      let res = `+sizes(${sizesString}, ${linksString})`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "promocode": {
      const code = d.code || "";
      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;

      let res = `+promocode("${code}")`;

      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }

      return res;
    }

    case "dividerVA": {
      const w = d.width ?? 300;
      const h = d.height ?? 1;
      const bottom = d.bottomSpacing ?? 40;
      const addSpacing = !d.removeBottomSpacing;
      const top = d.topSpacing ?? 40;
      const addTop = !d.removeTopSpacing;

      let res = "";
      if (addTop) {
        res += `+spacerLine(${top})\n`;
      }
      // divider mixin ожидает третьего необязательного аргумента, поэтому оставляем завершающую запятую
      res += `+dividerVA(${w}, ${h},)`;
      if (addSpacing) {
        res += `\n+spacerLine(${bottom})`;
      }
      return res;
    }

    default:
      return `// TODO: неизвестный тип блока "${block.type}"`;
  }
}

export function generatePug(blocks, settings) {
  return blocks
    .map((b) => renderBlockToPug(b, settings))
    .filter(Boolean)
    .join("\n\n")
    .trim();
}
