<script>
  import SpacerBlock from "./blocks/SpacerBlock.svelte";
  import TitleActualBlock from "./blocks/TitleActualBlock.svelte";
  import ParagraphBlock from "./blocks/ParagraphBlock.svelte";
  import ButtonSingleBlock from "./blocks/ButtonSingleBlock.svelte";
  import ButtonDoubleBlock from "./blocks/ButtonDoubleBlock.svelte";
  import ButtonTripleBlock from "./blocks/ButtonTripleBlock.svelte";
  import BannerBlock from "./blocks/BannerBlock.svelte";
  import BannerNoLinkBlock from "./blocks/BannerNoLinkBlock.svelte";
  import TwoBannersWithTextBlock from "./blocks/TwoBannersWithTextBlock.svelte";
  import TwoBannersNoTextBlock from "./blocks/TwoBannersNoTextBlock.svelte";
  import ThreeBannersNoTextBlock from "./blocks/ThreeBannersNoTextBlock.svelte";
  import ProductsRowBlock from "./blocks/ProductsRowBlock.svelte";
  import ProductsImageBlock from "./blocks/ProductsImageBlock.svelte";
  import TextImageBlock from "./blocks/TextImageBlock.svelte";
  import SizeGridBlock from "./blocks/SizeGridBlock.svelte";
  import PromocodeBlock from "./blocks/PromocodeBlock.svelte";
  import DividerBlock from "./blocks/DividerBlock.svelte";

  export let block;
  export let index;
  export let femaleIndex = 0;
  export let maleIndex = 0;
  export let onChange;
  export let onRemove;
  export let forceCollapse = null;
  export let colorizeTitles = false;
  export let onHandlePointerDown = () => {};
  export let isDragging = false;

  const handleChange = (data) => onChange(block.id, data);

  const segmentLabelFor = (seg, fIdx, mIdx) => {
    if (seg === "female") return `Ж${fIdx || ""}`;
    if (seg === "male") return `М${mIdx || ""}`;
    return "О";
  };

  let segLocal = block.segment || "common";
  let segBadge = segmentLabelFor(segLocal, femaleIndex, maleIndex);
  $: segLocal = block.segment || "common";
  $: segBadge = segmentLabelFor(segLocal, femaleIndex, maleIndex);

  let collapsed = false;
  $: if (forceCollapse !== null) collapsed = forceCollapse;

  const setSegment = (value) => {
    segLocal = value;
    segBadge = segmentLabelFor(value);
    onChange(block.id, { segment: value });
  };

  const getBlockLabel = (type) => {
    switch (type) {
      case "titleActual":
        return "АКТУАЛЬНЫЙ заголовок";
      case "paragraph":
        return "Текстовый блок";
      case "buttonSingle":
        return "Кнопка по центру";
      case "buttonDouble":
        return "Две кнопки";
      case "buttonTriple":
        return "Три кнопки";
      case "banner":
        return "Баннер с ссылкой";
      case "bannerNoLink":
        return "Баннер без ссылки";
      case "twoBannersWithText":
        return "Два баннера с текстом";
      case "twoBannersNoText":
        return "Два баннера без текста";
      case "threeBannersNoText":
        return "Три баннера без текста";
      case "products4Row":
        return "4 товара в ряд";
      case "products3Row":
        return "3 товара в ряд";
    case "productsImageLeft":
      return "Товары + картинка слева";
    case "productsImageRight":
      return "Товары + картинка справа";
    case "productsImageLeft3":
      return "3 товара + картинка слева";
    case "productsImageRight3":
      return "3 товара + картинка справа";
      case "textImageLeft":
        return "Текст справа, картинка слева";
      case "textImageRight":
        return "Текст слева, картинка справа";
      case "sizeGrid":
        return "Размерная сетка";
      case "promocode":
        return "Промокод";
      case "spacer":
        return "Отступ";
      case "dividerVA":
        return "Разделитель";
      default:
        return type;
    }
  };

  const toggleCollapse = () => (collapsed = !collapsed);

  const handleKeyToggle = (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      toggleCollapse();
    }
  };

  const typeColors = {
    titleActual: "#e85a5a",
    paragraph: "#b388ff",
    buttonSingle: "#2ab27b",
    buttonDouble: "#26a69a",
    buttonTriple: "#0097a7",
    banner: "#ffb74d",
    bannerNoLink: "#ff9800",
    twoBannersWithText: "#c27447",
    twoBannersNoText: "#bf6d3f",
    threeBannersNoText: "#b0552c",
    products4Row: "#4dabf5",
    products3Row: "#42a5f5",
    productsImageLeft: "#ec6a7d",
    productsImageRight: "#ec6a7d",
    productsImageLeft3: "#ec6a7d",
    productsImageRight3: "#ec6a7d",
    textImageLeft: "#7fd1b9",
    textImageRight: "#7fd1b9",
    sizeGrid: "#90a4ae",
    promocode: "#f06292",
    spacer: "#cfd8dc",
    dividerVA: "#8bc34a"
  };

  const computeTitleColor = (blk, enabled) => {
    if (!enabled) return null;
    return typeColors[blk?.type] || "#9aa0a6";
  };

  // пересчитываем при смене палитры или изменении блока
  $: titleColor = computeTitleColor(block, colorizeTitles);

  const PRODUCT_REQUIREMENTS = {
    products4Row: { field: "productIds", count: 4 },
    products3Row: { field: "productIds", count: 3 },
    productsImageLeft: { field: "productIds", count: 4 },
    productsImageRight: { field: "productIds", count: 4 },
    productsImageLeft3: { field: "productIds", count: 3 },
    productsImageRight3: { field: "productIds", count: 3 }
  };

  const cleanText = (value = "") => {
    const stripped = value.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
    return stripped;
  };

  const textPreview = (value = "", limit = 80) => {
    const text = cleanText(value);
    if (!text) return "";
    return text.length > limit ? `${text.slice(0, limit - 1).trim()}…` : text;
  };

  const shortLink = (value = "", limit = 32) => {
    if (!value) return "";
    const trimmed = value.trim().replace(/^https?:\/\//i, "");
    return trimmed.length > limit ? `${trimmed.slice(0, limit - 1)}…` : trimmed;
  };

  const splitList = (value = "") =>
    value
      .split(/[\n,]/)
      .map((part) => part.trim())
      .filter(Boolean);

  const formatButtons = (buttons) =>
    buttons
      .map((btn) => `${btn.label}: ${textPreview(btn.text || btn.image || "—", 18) || "—"} → ${shortLink(btn.href) || "нет"}`)
      .join(" • ");

  const getProductInfo = (blk) => {
    const requirement = PRODUCT_REQUIREMENTS[blk?.type];
    if (!requirement) return null;
    const raw = blk?.data?.[requirement.field] || "";
    const ids = splitList(raw);
    return {
      summary: `ID ${ids.length}/${requirement.count}`,
      count: ids.length,
      expected: requirement.count
    };
  };

  const computeSummary = (blk) => {
    if (!blk) return "";
    const data = blk.data || {};
    switch (blk.type) {
      case "titleActual":
      case "paragraph":
        return textPreview(data.text);
      case "buttonSingle":
        return `${textPreview(data.text, 26) || "Кнопка"} → ${shortLink(data.href) || "нет ссылки"}`;
      case "buttonDouble":
        return formatButtons([
          { label: "Л", text: data.leftText, href: data.leftHref },
          { label: "П", text: data.rightText, href: data.rightHref }
        ]);
      case "buttonTriple":
        return formatButtons([
          { label: "Л", text: data.leftText, href: data.leftHref },
          { label: "С", text: data.centerText, href: data.centerHref },
          { label: "П", text: data.rightText, href: data.rightHref }
        ]);
      case "banner":
        return `${data.imageBaseName ? `${data.imageBaseName}${data.imageExtension || ".png"}` : "Файл не задан"} → ${
          shortLink(data.href) || "нет ссылки"
        }`;
      case "bannerNoLink":
        return data.imageBaseName ? `${data.imageBaseName}${data.imageExtension || ".png"}` : "";
      case "twoBannersWithText":
        return formatButtons([
          { label: "Л", text: data.leftText || data.leftImageBaseName, href: data.leftHref },
          { label: "П", text: data.rightText || data.rightImageBaseName, href: data.rightHref }
        ]);
      case "twoBannersNoText":
        return formatButtons([
          { label: "Л", text: data.leftImageBaseName, href: data.leftHref },
          { label: "П", text: data.rightImageBaseName, href: data.rightHref }
        ]);
      case "threeBannersNoText":
        return [1, 2, 3]
          .map((num, idx) => {
            const image = data[`imgBaseName${num}`];
            const href = data[`href${num}`];
            const label = ["Л", "Ц", "П"][idx];
            return `${label}: ${image || "—"}${href ? ` → ${shortLink(href)}` : ""}`;
          })
          .join(" • ");
      case "products4Row":
      case "products3Row":
      case "productsImageLeft":
      case "productsImageRight":
      case "productsImageLeft3":
      case "productsImageRight3":
        return getProductInfo(blk)?.summary || "";
      case "textImageLeft":
      case "textImageRight":
        return `${textPreview(data.header, 32) || "Без заголовка"} • ${data.buttonText || "кнопка"}`;
      case "sizeGrid":
        return `Размеры ${splitList(data.sizes).length}${data.links ? ` • Ссылки ${splitList(data.links).length}` : ""}`;
      case "promocode":
        return data.code ? `Код: ${data.code}` : "";
      case "spacer":
        return `${data.height ?? 40}px`;
      case "dividerVA":
        return `${data.width ?? 300}×${data.height ?? 1}px`;
      default:
        return "";
    }
  };

  const pushIssue = (arr, issue) => {
    if (issue && !arr.includes(issue)) arr.push(issue);
  };

  const computeIssues = (blk) => {
    const issues = [];
    if (!blk) return issues;
    const data = blk.data || {};
    const summaryInfo = getProductInfo(blk);
    if (summaryInfo && summaryInfo.count !== summaryInfo.expected) {
      issues.push(`ID ${summaryInfo.count}/${summaryInfo.expected}`);
    }

    const ensureText = (value, label) => {
      if (!value || !value.trim()) pushIssue(issues, label ? `Нет текста (${label})` : "Нет текста");
    };
    const ensureHref = (value, label) => {
      if (!value || !value.trim()) pushIssue(issues, label ? `Нет ссылки (${label})` : "Нет ссылки");
    };
    const ensureImage = (baseName, directUrl, label) => {
      const hasBase = baseName && baseName.trim();
      const hasDirect = directUrl && directUrl.trim();
      if (!hasBase && !hasDirect) {
        pushIssue(issues, label ? `Нет изображения (${label})` : "Нет изображения");
      }
    };

    switch (blk.type) {
      case "titleActual":
      case "paragraph":
        ensureText(data.text);
        break;
      case "buttonSingle":
        ensureText(data.text);
        ensureHref(data.href);
        break;
      case "buttonDouble":
        ensureText(data.leftText, "Л");
        ensureHref(data.leftHref, "Л");
        ensureText(data.rightText, "П");
        ensureHref(data.rightHref, "П");
        break;
      case "buttonTriple":
        ensureText(data.leftText, "Л");
        ensureHref(data.leftHref, "Л");
        ensureText(data.centerText, "С");
        ensureHref(data.centerHref, "С");
        ensureText(data.rightText, "П");
        ensureHref(data.rightHref, "П");
        break;
      case "banner":
        ensureImage(data.imageBaseName, data.imageUrl);
        ensureHref(data.href);
        break;
      case "bannerNoLink":
        ensureImage(data.imageBaseName, data.imageUrl);
        break;
      case "twoBannersWithText":
        ensureImage(data.leftImageBaseName, data.leftImage, "Л");
        ensureHref(data.leftHref, "Л");
        ensureImage(data.rightImageBaseName, data.rightImage, "П");
        ensureHref(data.rightHref, "П");
        break;
      case "twoBannersNoText":
        ensureImage(data.leftImageBaseName, data.leftImage, "Л");
        ensureHref(data.leftHref, "Л");
        ensureImage(data.rightImageBaseName, data.rightImage, "П");
        ensureHref(data.rightHref, "П");
        break;
      case "threeBannersNoText":
        [1, 2, 3].forEach((num, idx) => {
          const label = ["Л", "Ц", "П"][idx];
          ensureImage(data[`imgBaseName${num}`], data[`img${num}`], label);
          ensureHref(data[`href${num}`], label);
        });
        break;
      case "textImageLeft":
      case "textImageRight":
        ensureText(data.header);
        ensureText(data.buttonText, "Кнопка");
        ensureHref(data.buttonHref, "Кнопка");
        ensureHref(data.link, "Картинка");
        ensureImage(data.imageBaseName, data.imageUrl, "Картинка");
        break;
      case "sizeGrid":
        if (!splitList(data.sizes).length) pushIssue(issues, "Нет размеров");
        if (data.links && splitList(data.sizes).length !== splitList(data.links).length) {
          pushIssue(issues, "Размеры ≠ ссылки");
        }
        break;
      case "promocode":
        ensureText(data.code, "Промокод");
        break;
      default:
        break;
    }

    return issues;
  };

  $: blockSummary = computeSummary(block);
  $: blockIssues = computeIssues(block);
</script>

<div
  class="block-card"
  class:collapsed={collapsed}
  class:marker-female={segLocal === "female"}
  class:marker-male={segLocal === "male"}
  class:marker-common={segLocal === "common"}
  class:marker-center={block.type === "dividerVA" && block.data?.swapCenter}
  class:dragging={isDragging}
>
  <div class="block-header">
    <div
      class="block-title clickable"
      role="button"
      aria-expanded={!collapsed}
      tabindex="0"
      on:click={toggleCollapse}
      on:keydown={handleKeyToggle}
    >
      <span class="segment-badge" title="Назначение блока">{segBadge}</span>
      <span class="block-index">{index + 1}</span>
      <span class="block-name" style:color={titleColor}>{getBlockLabel(block.type)}</span>
    </div>
    <div class="block-actions">
      <div class="segment-toggle compact">
        <button type="button" class:active={segLocal === "common"} on:click={() => setSegment("common")}>О</button>
        <button type="button" class:active={segLocal === "female"} on:click={() => setSegment("female")}>Ж</button>
        <button type="button" class:active={segLocal === "male"} on:click={() => setSegment("male")}>М</button>
      </div>
      <span
        class="block-drag-handle"
        title="Перетащить"
        role="button"
        tabindex="0"
        on:pointerdown|stopPropagation={onHandlePointerDown}
      >
        <svg class="icon" viewBox="0 0 16 16" aria-hidden="true">
          <circle cx="6" cy="4.5" r="0.85" />
          <circle cx="10" cy="4.5" r="0.85" />
          <circle cx="6" cy="8" r="0.85" />
          <circle cx="10" cy="8" r="0.85" />
          <circle cx="6" cy="11.5" r="0.85" />
          <circle cx="10" cy="11.5" r="0.85" />
        </svg>
      </span>
      <button class="icon-btn danger" aria-label="Удалить" title="Удалить" on:click={() => onRemove(block.id)}>
        <svg class="icon" viewBox="0 0 16 16" aria-hidden="true">
          <path d="M5 5 11 11M11 5 5 11" />
        </svg>
      </button>
    </div>
  </div>
  {#if (collapsed && blockSummary) || blockIssues.length}
    <div class="block-meta">
      {#if collapsed && blockSummary}
        <div class="block-summary">{blockSummary}</div>
      {/if}
      {#if blockIssues.length}
        <div class="block-issues">
          {#each blockIssues as issue}
            <span class="issue-badge">{issue}</span>
          {/each}
        </div>
      {/if}
    </div>
  {/if}

  {#if !collapsed}
    <div class="block-body">
      {#if block.type === "spacer"}
        <SpacerBlock {block} onChange={handleChange} />
      {:else if block.type === "titleActual"}
        <TitleActualBlock {block} onChange={handleChange} />
      {:else if block.type === "paragraph"}
        <ParagraphBlock {block} onChange={handleChange} />
      {:else if block.type === "buttonSingle"}
        <ButtonSingleBlock {block} onChange={handleChange} />
      {:else if block.type === "buttonDouble"}
        <ButtonDoubleBlock {block} onChange={handleChange} />
      {:else if block.type === "buttonTriple"}
        <ButtonTripleBlock {block} onChange={handleChange} />
      {:else if block.type === "banner"}
        <BannerBlock {block} onChange={handleChange} />
      {:else if block.type === "bannerNoLink"}
        <BannerNoLinkBlock {block} onChange={handleChange} />
      {:else if block.type === "twoBannersWithText"}
        <TwoBannersWithTextBlock {block} onChange={handleChange} />
      {:else if block.type === "twoBannersNoText"}
        <TwoBannersNoTextBlock {block} onChange={handleChange} />
      {:else if block.type === "threeBannersNoText"}
        <ThreeBannersNoTextBlock {block} onChange={handleChange} />
      {:else if block.type === "products4Row" || block.type === "products3Row"}
        <ProductsRowBlock {block} onChange={handleChange} />
      {:else if block.type.startsWith("productsImageLeft") || block.type.startsWith("productsImageRight")}
        <ProductsImageBlock {block} onChange={handleChange} />
      {:else if block.type === "textImageLeft" || block.type === "textImageRight"}
        <TextImageBlock {block} onChange={handleChange} />
      {:else if block.type === "sizeGrid"}
        <SizeGridBlock {block} onChange={handleChange} />
      {:else if block.type === "promocode"}
        <PromocodeBlock {block} onChange={handleChange} />
      {:else if block.type === "dividerVA"}
        <DividerBlock {block} onChange={handleChange} />
      {:else}
        <div>Редактор для "{block.type}" ещё не реализован</div>
      {/if}
    </div>
  {/if}
</div>

<style>
  .block-index { font-weight: 700; color: var(--muted, var(--text)); }
  .block-name { font-weight: 700; }
</style>
