"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import ProductZoom from "./ProductZoom";
import PageLoading from "@/components/PageLoading";
import { parseProductSeoMetaFromDetail, type ProductSeoMeta } from "@/lib/metadata";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  getStoredLocaleRaw,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";
import { stripKnownLocalePrefix } from "@/i18n/localePathPrefix";

export type ProductDetailPageProps = {
  productId?: string;
};

function IconQuantity() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="57" height="57" viewBox="0 0 57 57" fill="none">
      <rect width="57" height="57" rx="7" fill="#DAE6DC" />
      <g clipPath="url(#clip0_1094_57390)">
        <path d="M43.35 26.0242H37.9677C38.2435 25.724 38.3977 25.3319 38.4 24.9242V14.4742C38.4 14.0366 38.2262 13.6169 37.9167 13.3075C37.6073 12.9981 37.1876 12.8242 36.75 12.8242H26.3C25.8798 12.8242 25.4756 12.9854 25.1709 13.2747L20.1042 16.8332C19.82 16.9654 19.5792 17.1758 19.4102 17.4399C19.2412 17.704 19.151 18.0107 19.15 18.3242V26.0242C18.7298 26.0242 18.3256 26.1854 18.0208 26.4747L12.9543 30.0332C12.67 30.1654 12.4292 30.3758 12.2602 30.6399C12.0912 30.904 12.001 31.2107 12 31.5242V42.5242C12 42.9618 12.1738 43.3815 12.4833 43.6909C12.7927 44.0004 13.2124 44.1742 13.65 44.1742H25.2C25.6072 44.1728 25.9993 44.0199 26.3 43.7452C26.6009 44.0202 26.993 44.1726 27.4 44.1742H38.95C39.3961 44.1742 39.8234 43.9922 40.1325 43.6704L44.5094 39.2935C44.8229 38.9855 45 38.5642 45 38.1242V27.6742C44.9978 27.2373 44.8233 26.8189 44.5143 26.5099C44.2054 26.2009 43.7869 26.0264 43.35 26.0242ZM39.6837 30.0541C39.4566 29.9375 39.2053 29.8759 38.95 29.8742H34.1287L36.8787 27.1242H43.0321L39.6837 30.0541ZM25.2 29.8742H20.8C20.6541 29.8742 20.5142 29.8163 20.4111 29.7131C20.3079 29.61 20.25 29.4701 20.25 29.3242V18.3242C20.25 18.1783 20.3079 18.0385 20.4111 17.9353C20.5142 17.8322 20.6541 17.7742 20.8 17.7742H32.35C32.4959 17.7742 32.6358 17.8322 32.7389 17.9353C32.8421 18.0385 32.9 18.1783 32.9 18.3242V29.3242C32.9005 29.4682 32.8442 29.6065 32.7432 29.7092L32.7323 29.7202C32.6298 29.8194 32.4926 29.8747 32.35 29.8742H25.2ZM33.8499 17.6455L37.3 14.6266V24.9242C37.2996 24.9962 37.2848 25.0673 37.2565 25.1334C37.2281 25.1995 37.1868 25.2593 37.135 25.3092L34 28.4492V18.3242C33.9993 18.0898 33.9481 17.8583 33.8499 17.6455ZM33.0837 16.8541C32.8566 16.7375 32.6053 16.6759 32.35 16.6742H28.4533L31.9886 13.9242H36.4321L33.0837 16.8541ZM25.8408 14.1486C25.8686 14.1291 25.8945 14.107 25.9183 14.0826C25.9682 14.0322 26.0277 13.9922 26.0932 13.965C26.1587 13.9378 26.229 13.9239 26.3 13.9242H30.1968L26.6614 16.6742H22.2449L25.8408 14.1486ZM18.6908 27.3486C18.7186 27.3291 18.7445 27.307 18.7683 27.2826C18.8182 27.2322 18.8777 27.1922 18.9432 27.165C19.0087 27.1378 19.079 27.1239 19.15 27.1242V29.3242C19.1516 29.5118 19.1863 29.6982 19.2512 29.8742H15.0949L18.6908 27.3486ZM13.65 43.0742C13.5041 43.0742 13.3642 43.0163 13.2611 42.9131C13.1579 42.81 13.1 42.6701 13.1 42.5242V31.5242C13.1 31.3783 13.1579 31.2385 13.2611 31.1353C13.3642 31.0322 13.5041 30.9742 13.65 30.9742H25.2C25.3459 30.9742 25.4858 31.0322 25.5889 31.1353C25.6921 31.2385 25.75 31.3783 25.75 31.5242V42.5242C25.75 42.6682 25.6935 42.8064 25.5927 42.9092L25.5828 42.9186C25.4805 43.0186 25.3431 43.0745 25.2 43.0742H13.65ZM27.4 43.0742C27.2541 43.0742 27.1142 43.0163 27.0111 42.9131C26.9079 42.81 26.85 42.6701 26.85 42.5242V31.5242C26.85 31.3783 26.9079 31.2385 27.0111 31.1353C27.1142 31.0322 27.2541 30.9742 27.4 30.9742H38.95C39.0959 30.9742 39.2358 31.0322 39.3389 31.1353C39.4421 31.2385 39.5 31.3783 39.5 31.5242V42.5242C39.499 42.6647 39.4443 42.7995 39.3471 42.901L39.335 42.9092L39.3273 42.918C39.2262 43.0166 39.0912 43.0725 38.95 43.0742H27.4ZM43.735 38.5092L40.6 41.6442V31.5242C40.5993 31.2898 40.5481 31.0583 40.4499 30.8455L43.9 27.8266V38.1242C43.8996 38.1962 43.8848 38.2673 43.8565 38.3334C43.8281 38.3995 43.7868 38.4593 43.735 38.5092Z" fill="#053F31" />
        <path d="M24.6531 25.4746H22.4531C22.1614 25.4746 21.8816 25.5905 21.6753 25.7968C21.469 26.0031 21.3531 26.2829 21.3531 26.5746V27.6746C21.3531 27.9663 21.469 28.2461 21.6753 28.4524C21.8816 28.6587 22.1614 28.7746 22.4531 28.7746H24.6531C24.9449 28.7746 25.2247 28.6587 25.4309 28.4524C25.6372 28.2461 25.7531 27.9663 25.7531 27.6746V26.5746C25.7531 26.2829 25.6372 26.0031 25.4309 25.7968C25.2247 25.5905 24.9449 25.4746 24.6531 25.4746ZM22.4531 27.6746V26.5746H24.6531V27.6746H22.4531ZM31.2531 25.4746H29.6031C29.4573 25.4746 29.3174 25.5326 29.2142 25.6357C29.1111 25.7388 29.0531 25.8787 29.0531 26.0246C29.0531 26.1705 29.1111 26.3104 29.2142 26.4135C29.3174 26.5167 29.4573 26.5746 29.6031 26.5746H31.2531C31.399 26.5746 31.5389 26.5167 31.642 26.4135C31.7452 26.3104 31.8031 26.1705 31.8031 26.0246C31.8031 25.8787 31.7452 25.7388 31.642 25.6357C31.5389 25.5326 31.399 25.4746 31.2531 25.4746ZM31.2531 27.6746H29.6031C29.4573 27.6746 29.3174 27.7326 29.2142 27.8357C29.1111 27.9388 29.0531 28.0787 29.0531 28.2246C29.0531 28.3705 29.1111 28.5104 29.2142 28.6135C29.3174 28.7167 29.4573 28.7746 29.6031 28.7746H31.2531C31.399 28.7746 31.5389 28.7167 31.642 28.6135C31.7452 28.5104 31.8031 28.3705 31.8031 28.2246C31.8031 28.0787 31.7452 27.9388 31.642 27.8357C31.5389 27.7326 31.399 27.6746 31.2531 27.6746ZM17.5031 38.6746H15.3031C15.0114 38.6746 14.7316 38.7905 14.5253 38.9968C14.319 39.2031 14.2031 39.4829 14.2031 39.7746V40.8746C14.2031 41.1663 14.319 41.4461 14.5253 41.6524C14.7316 41.8587 15.0114 41.9746 15.3031 41.9746H17.5031C17.7949 41.9746 18.0747 41.8587 18.2809 41.6524C18.4872 41.4461 18.6031 41.1663 18.6031 40.8746V39.7746C18.6031 39.4829 18.4872 39.2031 18.2809 38.9968C18.0747 38.7905 17.7949 38.6746 17.5031 38.6746ZM15.3031 40.8746V39.7746H17.5031V40.8746H15.3031ZM24.1031 38.6746H22.4531C22.3073 38.6746 22.1674 38.7326 22.0642 38.8357C21.9611 38.9388 21.9031 39.0787 21.9031 39.2246C21.9031 39.3705 21.9611 39.5104 22.0642 39.6135C22.1674 39.7167 22.3073 39.7746 22.4531 39.7746H24.1031C24.249 39.7746 24.3889 39.7167 24.492 39.6135C24.5952 39.5104 24.6531 39.3705 24.6531 39.2246C24.6531 39.0787 24.5952 38.9388 24.492 38.8357C24.3889 38.7326 24.249 38.6746 24.1031 38.6746ZM24.1031 40.8746H22.4531C22.3073 40.8746 22.1674 40.9326 22.0642 41.0357C21.9611 41.1388 21.9031 41.2787 21.9031 41.4246C21.9031 41.5705 21.9611 41.7104 22.0642 41.8135C22.1674 41.9167 22.3073 41.9746 22.4531 41.9746H24.1031C24.249 41.9746 24.3889 41.9167 24.492 41.8135C24.5952 41.7104 24.6531 41.5705 24.6531 41.4246C24.6531 41.2787 24.5952 41.1388 24.492 41.0357C24.3889 40.9326 24.249 40.8746 24.1031 40.8746ZM31.2531 38.6746H29.0531C28.7614 38.6746 28.4816 38.7905 28.2753 38.9968C28.069 39.2031 27.9531 39.4829 27.9531 39.7746V40.8746C27.9531 41.1663 28.069 41.4461 28.2753 41.6524C28.4816 41.8587 28.7614 41.9746 29.0531 41.9746H31.2531C31.5449 41.9746 31.8247 41.8587 32.0309 41.6524C32.2372 41.4461 32.3531 41.1663 32.3531 40.8746V39.7746C32.3531 39.4829 32.2372 39.2031 32.0309 38.9968C31.8247 38.7905 31.5449 38.6746 31.2531 38.6746ZM29.0531 40.8746V39.7746H31.2531V40.8746H29.0531ZM37.8531 38.6746H36.2031C36.0573 38.6746 35.9174 38.7326 35.8142 38.8357C35.7111 38.9388 35.6531 39.0787 35.6531 39.2246C35.6531 39.3705 35.7111 39.5104 35.8142 39.6135C35.9174 39.7167 36.0573 39.7746 36.2031 39.7746H37.8531C37.999 39.7746 38.1389 39.7167 38.242 39.6135C38.3452 39.5104 38.4031 39.3705 38.4031 39.2246C38.4031 39.0787 38.3452 38.9388 38.242 38.8357C38.1389 38.7326 37.999 38.6746 37.8531 38.6746ZM37.8531 40.8746H36.2031C36.0573 40.8746 35.9174 40.9326 35.8142 41.0357C35.7111 41.1388 35.6531 41.2787 35.6531 41.4246C35.6531 41.5705 35.7111 41.7104 35.8142 41.8135C35.9174 41.9167 36.0573 41.9746 36.2031 41.9746H37.8531C37.999 41.9746 38.1389 41.9167 38.242 41.8135C38.3452 41.7104 38.4031 41.5705 38.4031 41.4246C38.4031 41.2787 38.3452 41.1388 38.242 41.0357C38.1389 40.9326 37.999 40.8746 37.8531 40.8746Z" fill="#053F31" />
      </g>
      <defs>
        <clipPath id="clip0_1094_57390">
          <rect width="33" height="33" fill="white" transform="translate(12 12)" />
        </clipPath>
      </defs>
    </svg>
  );
}

function IconFrequency() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="57" height="57" viewBox="0 0 57 57" fill="none">
      <rect width="57" height="57" rx="7" fill="#DAE6DC" />
      <path d="M30.2875 41.4238C29.4193 41.4238 29.0913 40.3861 28.9836 40.0452C28.7832 39.4103 28.6253 38.5112 28.5022 37.2969C28.2779 35.0862 28.1999 32.1999 28.1167 29.1436C28.031 25.9854 27.9427 22.7202 27.6791 20.2903C27.4039 17.756 27.0172 16.9942 26.8277 16.7673C26.6968 17.0773 26.4732 17.8939 26.2437 20.0357C26.0401 21.9358 25.8873 24.3064 25.7397 26.599C25.3382 32.8374 25.15 34.5944 24.5937 35.0707C24.4513 35.1925 24.2747 35.2505 24.0961 35.2337C22.9895 35.1319 22.7523 33.5683 22.6627 32.9798C22.5009 31.9118 22.4603 30.5158 22.421 29.1655C22.3868 27.995 22.352 26.7852 22.2367 25.8584C22.0897 24.6725 21.8674 24.4301 21.8203 24.3914C21.7004 24.4011 21.5109 24.4301 21.384 24.9264C21.2654 25.3885 21.2621 26.0253 21.2596 26.6402C21.2551 27.5722 21.2512 28.3766 20.869 28.8464C19.9273 30.0034 16.7156 29.8049 16.0814 29.7533C15.7798 29.7288 15.5555 29.4646 15.58 29.1629C15.6044 28.8613 15.8693 28.637 16.1703 28.6615C17.7217 28.7865 19.6347 28.6286 20.0195 28.1549C20.1581 27.9847 20.1619 27.1397 20.1639 26.6351C20.1671 25.9531 20.1703 25.2474 20.3224 24.6538C20.5925 23.6012 21.2467 23.3357 21.7481 23.2977C22.0478 23.2751 22.3263 23.3724 22.5551 23.5787C23.3362 24.2832 23.4291 26.1484 23.5161 29.1339C23.5528 30.403 23.5908 31.7153 23.7301 32.7046C23.8061 33.2492 23.9002 33.5896 23.9834 33.8016C24.0613 33.4329 24.1606 32.7955 24.2669 31.6946C24.4062 30.2593 24.5228 28.4468 24.6466 26.5287C24.8084 24.0112 24.9759 21.4086 25.2118 19.4086C25.5496 16.5443 25.9285 15.5781 26.7142 15.5781C27.3536 15.5781 27.8493 16.0847 28.1883 17.0831C28.4313 17.7992 28.6214 18.8092 28.769 20.1723C29.0378 22.6467 29.1267 25.9345 29.2124 29.1146C29.2891 31.9537 29.362 34.6356 29.5515 36.7542C29.6514 37.8744 29.7745 38.722 29.9266 39.3459C30.0664 39.9182 30.2018 40.1689 30.2778 40.2727C30.408 40.0768 30.6749 39.4335 30.8566 37.3536C31.0081 35.616 31.0603 33.3833 31.1112 31.2241C31.166 28.8987 31.2176 26.7027 31.3819 25.0147C31.4728 24.0808 31.5914 23.3879 31.7448 22.8981C31.9826 22.1349 32.3623 21.7527 32.8689 21.7656C34.5169 21.803 34.6607 24.9393 34.8269 28.5699C34.874 29.596 34.9185 30.5654 35.0003 31.3395C35.0802 32.0923 35.175 32.432 35.2349 32.5809C35.5134 32.3127 35.5881 31.1867 35.6378 30.4378C35.7029 29.46 35.7589 28.6151 36.1321 28.1555C36.5781 27.607 37.5172 27.3196 39.0035 27.2777C40.0083 27.2487 40.8978 27.3447 40.9352 27.3492C41.0067 27.357 41.076 27.3788 41.1392 27.4134C41.2023 27.448 41.2579 27.4948 41.303 27.5509C41.348 27.6071 41.3815 27.6716 41.4015 27.7407C41.4216 27.8098 41.4278 27.8822 41.4199 27.9538C41.387 28.2548 41.1156 28.4713 40.8153 28.4385C39.2684 28.2702 37.3625 28.3779 36.9816 28.8471C36.8282 29.0359 36.7696 29.9235 36.7302 30.5106C36.6529 31.6785 36.5723 32.887 35.9265 33.431C35.6732 33.6443 35.3568 33.7384 35.0119 33.7023C34.2907 33.6276 34.0761 32.7491 33.9517 31.8113C33.8376 30.9502 33.7854 29.8184 33.7306 28.6202C33.6629 27.141 33.5927 25.6115 33.4012 24.4449C33.2272 23.3866 33.0132 23.0302 32.9075 22.9142C32.7947 23.123 32.5775 23.7508 32.4286 25.5935C32.3004 27.1816 32.2514 29.2499 32.205 31.2493C32.1496 33.614 32.0922 36.0588 31.904 37.8957C31.7177 39.7281 31.3922 41.4238 30.2875 41.4238Z" fill="#053F31" />
    </svg>
  );
}

function IconLocation() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="57" height="57" viewBox="0 0 57 57" fill="none">
      <rect width="57" height="57" rx="7" fill="#DAE6DC" />
      <path d="M32.7664 33.1785C35.5331 28.8371 35.1853 29.3787 35.265 29.2655C36.2723 27.8448 36.8047 26.1726 36.8047 24.4297C36.8047 19.8076 33.0539 16 28.4258 16C23.8127 16 20.0469 19.8001 20.0469 24.4297C20.0469 26.1715 20.5904 27.8874 21.6307 29.3273L24.0851 33.1786C21.461 33.5818 17 34.7836 17 37.4297C17 38.3943 17.6296 39.7689 20.6289 40.8401C22.7232 41.5881 25.4922 42 28.4258 42C33.9114 42 39.8516 40.4526 39.8516 37.4297C39.8516 34.7831 35.3958 33.5827 32.7664 33.1785ZM22.9033 28.4894C22.8949 28.4763 22.8861 28.4635 22.877 28.4509C22.0113 27.26 21.5703 25.8486 21.5703 24.4297C21.5703 20.6202 24.6378 17.5234 28.4258 17.5234C32.2059 17.5234 35.2812 20.6216 35.2812 24.4297C35.2812 25.8509 34.8485 27.2144 34.0297 28.3739C33.9563 28.4707 34.3392 27.876 28.4258 37.1549L22.9033 28.4894ZM28.4258 40.4766C22.4339 40.4766 18.5234 38.7153 18.5234 37.4297C18.5234 36.5656 20.5328 35.1448 24.9852 34.591L27.7834 38.9817C27.8522 39.0897 27.9471 39.1786 28.0594 39.2402C28.1717 39.3018 28.2977 39.334 28.4257 39.334C28.5538 39.334 28.6798 39.3018 28.7921 39.2402C28.9043 39.1786 28.9993 39.0897 29.0681 38.9817L31.8662 34.591C36.3188 35.1448 38.3281 36.5656 38.3281 37.4297C38.3281 38.7044 34.4529 40.4766 28.4258 40.4766Z" fill="#053F31" />
      <path d="M28.4258 20.6211C26.3257 20.6211 24.6172 22.3296 24.6172 24.4297C24.6172 26.5297 26.3257 28.2383 28.4258 28.2383C30.5258 28.2383 32.2344 26.5297 32.2344 24.4297C32.2344 22.3296 30.5258 20.6211 28.4258 20.6211ZM28.4258 26.7148C27.1657 26.7148 26.1406 25.6897 26.1406 24.4297C26.1406 23.1697 27.1657 22.1445 28.4258 22.1445C29.6858 22.1445 30.7109 23.1697 30.7109 24.4297C30.7109 25.6897 29.6858 26.7148 28.4258 26.7148Z" fill="#053F31" />
    </svg>
  );
}

function IconWasteType() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="57" height="57" viewBox="0 0 57 57" fill="none">
      <rect width="57" height="57" rx="7" fill="#DAE6DC" />
      <path d="M37.895 20.104L33.8347 19.171L33.9303 18.755C34.2132 17.5238 33.4416 16.292 32.2105 16.0091L28.0736 15.0586C27.4791 14.922 26.8654 15.026 26.3456 15.3516C25.8258 15.6771 25.4643 16.1839 25.3277 16.7784L25.2321 17.1944L21.1718 16.2615C19.9321 15.9765 18.6926 16.7533 18.4079 17.9926L18.0139 19.7072C17.9978 19.7771 17.9957 19.8496 18.0076 19.9204C18.0195 19.9913 18.0452 20.059 18.0834 20.1199C18.1215 20.1808 18.1712 20.2335 18.2297 20.2752C18.2883 20.3168 18.3544 20.3465 18.4244 20.3626L33.0445 23.7219H18.8975C18.8213 23.7218 18.746 23.7377 18.6763 23.7685C18.6066 23.7993 18.5441 23.8444 18.4929 23.9008C18.4416 23.9571 18.4027 24.0236 18.3786 24.0959C18.3546 24.1682 18.3459 24.2447 18.3531 24.3206L19.9472 41.0508C20.0531 42.162 20.9746 43 22.0909 43H34.6733C35.7896 43 36.7112 42.162 36.8171 41.0508L38.352 24.9414L38.5767 24.993C38.6179 25.0024 38.6591 25.007 38.6996 25.007C38.9488 25.007 39.174 24.8356 39.2321 24.5825L39.6261 22.8679C39.7636 22.2694 39.6588 21.6517 39.3312 21.1285C39.0036 20.6053 38.4935 20.2415 37.895 20.104ZM35.7284 40.947C35.7043 41.2099 35.5826 41.4541 35.3873 41.6317C35.1921 41.8093 34.9373 41.9072 34.6734 41.9063H22.091C21.827 41.9072 21.5723 41.8093 21.3771 41.6317C21.1818 41.4542 21.0601 41.2099 21.0361 40.9471L19.499 24.8156H37.2654L35.7284 40.947ZM26.3937 17.0233C26.4649 16.7135 26.654 16.449 26.9262 16.2785C27.1983 16.1081 27.5186 16.0533 27.8287 16.1246L31.9656 17.0751C32.609 17.223 33.0122 17.8667 32.8644 18.5101L32.7688 18.9261L26.2981 17.4394L26.3937 17.0233ZM38.5602 22.623L38.2887 23.8046L19.2024 19.4191L19.4739 18.2376C19.6236 17.586 20.2756 17.178 20.9269 17.3275L33.0567 20.1145L33.0569 20.1146H33.057L37.6501 21.1699C38.3016 21.3196 38.7099 21.9715 38.5602 22.623ZM31.9127 40.1847L32.5808 26.4839C32.5955 26.1822 32.8516 25.9505 33.1537 25.9643C33.4554 25.9791 33.688 26.2355 33.6733 26.5372L33.0051 40.238C32.9908 40.5306 32.749 40.7582 32.4593 40.7582C32.4503 40.7582 32.4413 40.758 32.4322 40.7576C32.1305 40.7429 31.8979 40.4864 31.9127 40.1847ZM23.7593 40.238L23.0912 26.5372C23.0765 26.2355 23.309 25.979 23.6108 25.9643C23.9124 25.9504 24.1689 26.1821 24.1837 26.4839L24.8518 40.1847C24.8665 40.4864 24.6338 40.7428 24.3322 40.7576C24.3231 40.758 24.3141 40.7582 24.3051 40.7582C24.0152 40.7582 23.7736 40.5306 23.7593 40.238ZM27.8353 40.2114V26.5105C27.8353 26.2086 28.0802 25.9637 28.3822 25.9637C28.6842 25.9637 28.9291 26.2086 28.9291 26.5105V40.2114C28.9291 40.5133 28.6842 40.7582 28.3822 40.7582C28.0802 40.7582 27.8353 40.5133 27.8353 40.2114Z" fill="#053F31" />
    </svg>
  );
}

function IconArrowRight() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
      <path d="M0 18C0 8.05888 8.05888 0 18 0C27.9411 0 36 8.05888 36 18C36 27.9411 27.9411 36 18 36C8.05888 36 0 27.9411 0 18Z" fill="#F7FAF8" />
      <path d="M10.25 17.75L25.75 17.75M25.75 17.75L19.75 11.75M25.75 17.75L19.75 24.25" stroke="#053F31" strokeWidth="2" />
    </svg>
  );
}

function IconDownload() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
      <path d="M0 18C0 8.05888 8.05888 0 18 0C27.9411 0 36 8.05888 36 18C36 27.9411 27.9411 36 18 36C8.05888 36 0 27.9411 0 18Z" fill="#F7FAF8" />
      <path d="M18.25 10.25L18.25 25.75M18.25 25.75L24.25 19.75M18.25 25.75L11.75 19.75" stroke="#053F31" strokeWidth="2" />
    </svg>
  );
}

function IconCheck() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="15" height="14" viewBox="0 0 15 14" fill="none">
      <mask id="path-1-inside-1_1094_57353" fill="white">
        <path d="M1.55916 6.39374C1.26393 6.39453 0.974969 6.47534 0.725703 6.62681C0.476436 6.77828 0.277055 6.99422 0.150625 7.24966C0.0241944 7.50509 -0.0241172 7.78958 0.0112789 8.07021C0.046675 8.35083 0.164332 8.61613 0.350639 8.83541L4.32226 13.4935C4.46386 13.6619 4.64538 13.7955 4.85173 13.8832C5.05808 13.9709 5.28331 14.0101 5.50871 13.9978C5.99078 13.973 6.426 13.7261 6.70348 13.3201L14.9535 0.598961C14.9549 0.596851 14.9563 0.594741 14.9578 0.592662C15.0352 0.478865 15.0101 0.253351 14.8503 0.11168C14.8064 0.072775 14.7546 0.0428855 14.6982 0.0238517C14.6418 0.00481798 14.5819 -0.00295704 14.5223 0.0010057C14.4626 0.00496843 14.4044 0.020585 14.3513 0.0468935C14.2981 0.073202 14.2512 0.109645 14.2133 0.153979C14.2104 0.157465 14.2073 0.160898 14.2042 0.164279L5.88389 9.16483C5.85224 9.19908 5.81378 9.22697 5.77077 9.24687C5.72776 9.26677 5.68105 9.27829 5.63335 9.28076C5.58565 9.28323 5.53791 9.2766 5.49291 9.26126C5.4479 9.24592 5.40653 9.22216 5.3712 9.19138L2.60985 6.78549C2.32306 6.53379 1.94822 6.39402 1.55916 6.39374Z" />
      </mask>
      <path d="M1.55916 6.39374L1.56281 1.39374L1.55428 1.39374L1.54574 1.39376L1.55916 6.39374ZM0.350639 8.83541L-3.45973 12.0729L-3.45414 12.0794L0.350639 8.83541ZM4.32226 13.4935L8.14861 10.275L8.13787 10.2622L8.12703 10.2495L4.32226 13.4935ZM5.50871 13.9978L5.25195 9.00437L5.24324 9.00482L5.23453 9.00529L5.50871 13.9978ZM6.70348 13.3201L10.8313 16.1416L10.8655 16.0916L10.8985 16.0407L6.70348 13.3201ZM14.9535 0.598961L19.1486 3.31957L19.1576 3.30565L19.1665 3.29167L14.9535 0.598961ZM14.9578 0.592662L19.061 3.44979L19.0766 3.42739L19.092 3.40481L14.9578 0.592662ZM14.8503 0.11168L18.1675 -3.62949L18.1668 -3.63006L14.8503 0.11168ZM14.2133 0.153979L10.4112 -3.09315L10.4025 -3.08295L14.2133 0.153979ZM14.2042 0.164279L10.5386 -3.23624L10.5326 -3.22978L14.2042 0.164279ZM5.88389 9.16483L2.21234 5.77077L2.21218 5.77094L5.88389 9.16483ZM5.3712 9.19138L2.08664 12.9612L2.08685 12.9614L5.3712 9.19138ZM2.60985 6.78549L-0.688354 10.5434L-0.681541 10.5494L-0.674706 10.5553L2.60985 6.78549ZM1.55916 6.39374L1.54574 1.39376C0.351031 1.39697 -0.832897 1.72316 -1.87081 2.35386L0.725703 6.62681L3.32222 10.8998C2.78284 11.2275 2.17683 11.3921 1.57258 11.3937L1.55916 6.39374ZM0.725703 6.62681L-1.87081 2.35386C-2.91041 2.98558 -3.77317 3.90564 -4.33051 5.03168L0.150625 7.24966L4.63176 9.46764C4.32728 10.0828 3.86328 10.571 3.32222 10.8998L0.725703 6.62681ZM0.150625 7.24966L-4.33051 5.03168C-4.88907 6.16017 -5.10872 7.43296 -4.94942 8.69591L0.0112789 8.07021L4.97197 7.4445C5.06048 8.1462 4.93746 8.85002 4.63176 9.46764L0.150625 7.24966ZM0.0112789 8.07021L-4.94942 8.69591C-4.79024 9.95791 -4.26353 11.1268 -3.45973 12.0729L0.350639 8.83541L4.161 5.59795C4.59219 6.10545 4.88359 6.74376 4.97197 7.4445L0.0112789 8.07021ZM0.350639 8.83541L-3.45414 12.0794L0.517482 16.7376L4.32226 13.4935L8.12703 10.2495L4.15541 5.59138L0.350639 8.83541ZM4.32226 13.4935L0.495898 16.7121C1.15364 17.494 1.9805 18.0957 2.89608 18.4848L4.85173 13.8832L6.80739 9.28148C7.31026 9.4952 7.77409 9.82975 8.14861 10.275L4.32226 13.4935ZM4.85173 13.8832L2.89608 18.4848C3.811 18.8737 4.7995 19.0443 5.78289 18.9902L5.50871 13.9978L5.23453 9.00529C5.76713 8.97604 6.30517 9.06805 6.80739 9.28148L4.85173 13.8832ZM5.50871 13.9978L5.76547 18.9912C7.84064 18.8845 9.69284 17.8072 10.8313 16.1416L6.70348 13.3201L2.57563 10.4986C3.15916 9.64493 4.14091 9.0615 5.25195 9.00437L5.50871 13.9978ZM6.70348 13.3201L10.8985 16.0407L19.1486 3.31957L14.9535 0.598961L10.7585 -2.12165L2.50845 10.5995L6.70348 13.3201ZM14.9535 0.598961L19.1665 3.29167C19.1294 3.34971 19.094 3.40249 19.061 3.44979L14.9578 0.592662L10.8545 -2.26446C10.8187 -2.21301 10.7803 -2.15601 10.7406 -2.09375L14.9535 0.598961ZM14.9578 0.592662L19.092 3.40481C20.0777 1.95565 20.0914 0.422101 19.9072 -0.559511C19.7014 -1.65616 19.1386 -2.76843 18.1675 -3.62949L14.8503 0.11168L11.5331 3.85285C10.7218 3.13346 10.2514 2.20478 10.0787 1.28476C9.92768 0.479771 9.9152 -0.884119 10.8235 -2.21949L14.9578 0.592662ZM14.8503 0.11168L18.1668 -3.63006C17.6149 -4.11929 16.9768 -4.4843 16.2967 -4.71376L14.6982 0.0238517L13.0998 4.76146C12.5325 4.57007 11.9979 4.26484 11.5338 3.85342L14.8503 0.11168ZM14.6982 0.0238517L16.2967 -4.71376C15.6169 -4.94313 14.9011 -5.03517 14.1909 -4.988L14.5223 0.0010057L14.8536 4.99002C14.2627 5.02926 13.6668 4.95276 13.0998 4.76146L14.6982 0.0238517ZM14.5223 0.0010057L14.1909 -4.988C13.4807 -4.94084 12.7804 -4.7547 12.1325 -4.43384L14.3513 0.0468935L16.5701 4.52763C16.0284 4.79587 15.4445 4.95077 14.8536 4.99002L14.5223 0.0010057ZM14.3513 0.0468935L12.1325 -4.43384C11.4841 -4.11277 10.8956 -3.6603 10.4112 -3.09314L14.2133 0.153979L18.0155 3.4011C17.6068 3.8796 17.1122 4.25918 16.5701 4.52763L14.3513 0.0468935ZM14.2133 0.153979L10.4025 -3.08295C10.4475 -3.1359 10.4929 -3.18698 10.5386 -3.23623L14.2042 0.164279L17.8698 3.56479C17.9217 3.50878 17.9732 3.45083 18.0241 3.39091L14.2133 0.153979ZM14.2042 0.164279L10.5326 -3.22978L2.21234 5.77077L5.88389 9.16483L9.55545 12.5589L17.8757 3.55834L14.2042 0.164279ZM5.88389 9.16483L2.21218 5.77094C2.6319 5.31686 3.13007 4.95944 3.67108 4.7091L5.77077 9.24687L7.87046 13.7846C8.4975 13.4945 9.07257 13.0813 9.55561 12.5587L5.88389 9.16483ZM5.77077 9.24687L3.67108 4.7091C4.2117 4.45895 4.79041 4.31772 5.37475 4.28745L5.63335 9.28076L5.89194 14.2741C6.57169 14.2389 7.24382 14.0746 7.87046 13.7846L5.77077 9.24687ZM5.63335 9.28076L5.37475 4.28745C5.95904 4.25719 6.54687 4.33797 7.10647 4.52878L5.49291 9.26126L3.87934 13.9937C4.52895 14.2152 5.21226 14.3093 5.89194 14.2741L5.63335 9.28076ZM5.49291 9.26126L7.10647 4.52878C7.66636 4.71967 8.1944 5.01962 8.65555 5.42136L5.3712 9.19138L2.08685 12.9614C2.61867 13.4247 3.22944 13.7722 3.87934 13.9937L5.49291 9.26126ZM5.3712 9.19138L8.65576 5.42154L5.89441 3.01566L2.60985 6.78549L-0.674706 10.5553L2.08664 12.9612L5.3712 9.19138ZM2.60985 6.78549L5.90806 3.02759C4.69057 1.95904 3.13822 1.39489 1.56281 1.39374L1.55916 6.39374L1.55552 11.3937C0.758219 11.3932 -0.044448 11.1085 -0.688354 10.5434L2.60985 6.78549Z" fill="#053F31" mask="url(#path-1-inside-1_1094_57353)" />
    </svg>
  );
}

const TAB_KEYS = ["productDetails", "certifications", "transportInfo", "compliance"] as const;
type TabKey = (typeof TAB_KEYS)[number];

type VerifiedServiceCard = {
  svg: string;
  title: string;
  description: string;
};

type ProductDetailData = {
  title: string;
  subtitle: string;
  code: string;
  description: string;
  image: string;
  images: string[];
  quantity: string;
  supplyFrequency: string;
  location: string;
  locationDetail: string;
  wasteType: string;
  price: string;
  currency_symbol: string;
  priceUnit: string;
  technicalSheetUrl: string;
  technicalSheetFilename: string;
  variantId: string;
  currentAvailableQuantity: number | null;
  availability: string;
};

type AvailabilityDisplayStyle = {
  label: string;
  className: string;
};

function normalizeAvailabilityKey(raw: unknown): string {
  return String(raw ?? "")
    .trim()
    .toLowerCase()
    .replace(/\s+/g, " ");
}

function resolveAvailabilityDisplay(
  availability: string,
  currentAvailableQuantity: number | null,
  outOfStockLabel: string,
): AvailabilityDisplayStyle | null {
  const value = String(availability ?? "").trim();
  if (!value) {
    if (currentAvailableQuantity == null || currentAvailableQuantity < 1) {
      return {
        label: outOfStockLabel,
        className: "border-[#FF4D4D] text-[#FF4D4D]",
      };
    }
    return null;
  }

  const key = normalizeAvailabilityKey(availability);

  if (key === "in stock" || key === "en stock") {
    return { label: value, className: "border-[#053F31] text-[#053F31]" };
  }
  if (key === "recurring supply" || key.includes("recurring") || key.includes("recurrente")) {
    return { label: value, className: "border-[#1A6BBA] text-[#1A6BBA]" };
  }
  if (key === "on request" || key.includes("on request") || key.includes("bajo pedido") || key === "a pedido") {
    return { label: value, className: "border-[#D97706] text-[#D97706]" };
  }
  if (key === "out of stock" || key.includes("out of stock") || key.includes("agotado") || key.includes("sin stock")) {
    return { label: value, className: "border-[#FF4D4D] text-[#FF4D4D]" };
  }

  if (currentAvailableQuantity == null || currentAvailableQuantity < 1) {
    return { label: value, className: "border-[#FF4D4D] text-[#FF4D4D]" };
  }

  return { label: value, className: "border-[#757575] text-[#757575]" };
}

function mapApiProductToDetail(item: any): ProductDetailData | null {
  if (!item) return null;
  const apiImages = Array.isArray(item?.images)
    ? item.images
      .map((img: any) => String(img ?? "").trim())
      .filter((img: string) => Boolean(img))
    : [];

  return {
    title: String(item?.title ?? ""),
    subtitle: String(item?.category?.name ?? ""),
    code: String(item?.ler_code ?? ""),
    description: String(item?.description ?? ""),
    image: String(apiImages[0] ?? item?.image ?? ""),
    images: apiImages,
    quantity: String(item?.available_quantity ?? ""),
    supplyFrequency: String(item?.supply_frequency ?? item?.supplyFrequency ?? ""),
    location: String(item?.location_display ?? ""),
    locationDetail: String(item?.location_detail ?? ""),
    wasteType: String(item?.waste_type ?? ""),
    price: String(item?.price_amount ?? ""),
    currency_symbol: item.currency_symbol ?? "",
    priceUnit: String(item?.unit ?? ""),
    technicalSheetUrl: String(
      item?.technical_sheet_url ??
      item?.technical_sheet ??
      item?.technicalSheetUrl ??
      item?.technicalSheet ??
      item?.datasheet_url ??
      item?.datasheet ??
      item?.pdf_url ??
      ""
    ).trim(),
    technicalSheetFilename: String(
      item?.technical_sheet_filename
    ).trim(),
    variantId: String(
      item?.variant_id ??
      item?.variants?.[0]?.id ??
      item?.variant?.id ??
      item?.default_variant_id ??
      ""
    ).trim(),
    currentAvailableQuantity: (() => {
      const raw = item?.current_available_quantity;
      if (raw == null || raw === "") return null;
      const n = Number(raw);
      if (!Number.isFinite(n) || n < 1) return null;
      return Math.floor(n);
    })(),
    availability: String(item?.availability ?? ""),
  };
}

function collectCategoryTreePathSlugs(tree: unknown): string[] {
  const slugs: string[] = [];
  let node: unknown = tree;
  while (node && typeof node === "object" && !Array.isArray(node)) {
    const rec = node as Record<string, unknown>;
    const slug = String(rec.slug ?? "").trim();
    if (slug) slugs.push(slug);
    node = rec.sub_category ?? rec.subcategory ?? null;
  }
  return slugs;
}

function marketplaceProductUrlPathMatches(
  pathnameWithPossibleLocale: string,
  categoryTree: unknown,
  productHandle: string,
): boolean {
  const handle = String(productHandle ?? "").trim();
  if (!handle) return false;

  const { pathnameWithoutPrefix } = stripKnownLocalePrefix(pathnameWithPossibleLocale);
  const parts = pathnameWithoutPrefix.split("/").filter(Boolean);
  if (parts[0] !== "marketplace" || parts.length < 2) return false;

  const marketplaceParts = parts.slice(1);
  const urlHandle = decodeURIComponent(String(marketplaceParts[marketplaceParts.length - 1] ?? ""));
  if (urlHandle !== handle) return false;

  const urlCategorySegments = marketplaceParts
    .slice(0, -1)
    .map((segment) => decodeURIComponent(segment));
  const expectedCategorySegments = collectCategoryTreePathSlugs(categoryTree);

  if (expectedCategorySegments.length === 0) {
    return urlCategorySegments.length === 0;
  }

  if (urlCategorySegments.length !== expectedCategorySegments.length) return false;
  return urlCategorySegments.every((segment, index) => segment === expectedCategorySegments[index]);
}

/** True when URL is /marketplace/.../{handle} and the last segment matches the product (e.g. search listing links). */
function marketplaceProductUrlHandleMatches(
  pathnameWithPossibleLocale: string,
  productHandle: string,
): boolean {
  const handle = String(productHandle ?? "").trim();
  if (!handle) return false;

  const { pathnameWithoutPrefix } = stripKnownLocalePrefix(pathnameWithPossibleLocale);
  const parts = pathnameWithoutPrefix.split("/").filter(Boolean);
  if (parts[0] !== "marketplace" || parts.length < 2) return false;

  const urlHandle = decodeURIComponent(String(parts[parts.length - 1] ?? "")).trim();
  return urlHandle.toLowerCase() === handle.toLowerCase();
}

type CheckoutTransportOption = {
  id: string;
  code: string;
  transport_type: string;
  label: string;
  description: string;
  delivery_window: string;
  amount: number;
  display_price: string;
};

type CheckoutTruckTypeOption = {
  value: string;
  label: string;
  description: string;
};

export default function ProductDetailPage({
  productId,
}: ProductDetailPageProps) {
  const router = useRouter();
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);
  const [apiResolved, setApiResolved] = useState<ProductDetailData | null>(null);
  const [apiChecked, setApiChecked] = useState(false);
  const [activeTab, setActiveTab] = useState<TabKey>("productDetails");
  const [imageIndex, setImageIndex] = useState(0);
  const [hoveredBottomCard, setHoveredBottomCard] = useState<number | null>(null);
  const [verifiedServicesTitle, setVerifiedServicesTitle] = useState("");
  const [verifiedServiceCards, setVerifiedServiceCards] = useState<VerifiedServiceCard[]>([]);
  const [technicalSpecsTitle, setTechnicalSpecsTitle] = useState("");
  const [technicalSpecs, setTechnicalSpecs] = useState<{ label: string; value: string }[]>([]);
  const [typicalCompositionTitle, setTypicalCompositionTitle] = useState("");
  const [typicalComposition, setTypicalComposition] = useState<{ label: string; value_label: string; percentage?: number }[]>([]);
  const [recommendedAppsTitle, setRecommendedAppsTitle] = useState("");
  const [recommendedApplications, setRecommendedApplications] = useState<string[]>([]);
  const [certificationsTitle, setCertificationsTitle] = useState("");
  const [certificationsData, setCertificationsData] = useState<string[]>([]);
  const [transportInfoTitle, setTransportInfoTitle] = useState("");
  const [transportInfoData, setTransportInfoData] = useState<string[]>([]);
  const [complianceTitle, setComplianceTitle] = useState("");
  const [complianceData, setComplianceData] = useState<string[]>([]);
  const [configureModalOpen, setConfigureModalOpen] = useState(false);
  const [configQuantity, setConfigQuantity] = useState(1);
  const configQuantityRef = useRef(1);
  const [configTransport, setConfigTransport] = useState("standard");
  const [checkoutTransportOptions, setCheckoutTransportOptions] = useState<CheckoutTransportOption[]>([]);
  const [checkoutTruckTypeOptions, setCheckoutTruckTypeOptions] = useState<CheckoutTruckTypeOption[]>([]);
  const [checkoutRegionId, setCheckoutRegionId] = useState("");
  const [configTruckType, setConfigTruckType] = useState("");
  const [configTruckTypeError, setConfigTruckTypeError] = useState("");
  const [configQuantityError, setConfigQuantityError] = useState("");
  const [quoteRequestSubmitted, setQuoteRequestSubmitted] = useState(false);
  const [quoteRequestSending, setQuoteRequestSending] = useState(false);
  const [seoMeta, setSeoMeta] = useState<ProductSeoMeta | null>(null);
  const [authReady, setAuthReady] = useState(false);

  useEffect(() => {
    try {
      const raw = localStorage.getItem("currentUser") || localStorage.getItem("biomket_user");
      const user = raw ? JSON.parse(raw) : null;
      const loggedIn = !!(user && (user.fullName || user.name));
      if (!loggedIn) {
        window.location.href = "/login";
        return;
      }
      setAuthReady(true);
    } catch {
      window.location.href = "/login";
    }
  }, []);

  useEffect(() => {
    setUiLocale(getStoredLocale());
    const syncLocale = () => setUiLocale(getStoredLocale());
    window.addEventListener(LOCALE_CHANGE_EVENT, syncLocale);
    return () => window.removeEventListener(LOCALE_CHANGE_EVENT, syncLocale);
  }, []);

  const pd =
    staticCopy.productDetail[uiLocale as keyof typeof staticCopy.productDetail] ??
    staticCopy.productDetail["en-EN"];
  const tc =
    staticCopy.configurePurchaseModal[uiLocale as keyof typeof staticCopy.configurePurchaseModal] ??
    staticCopy.configurePurchaseModal["en-EN"];

  useEffect(() => {
    let isMounted = true;
    const loadCheckoutConfig = async () => {
      try {
        const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
        if (!base) return;
        const headers: Record<string, string> = {
          "content-type": "application/json",
          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
          "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
        };

        const res = await fetch(`${base}/store/checkout-config`, {
          method: "GET",
          headers,
          cache: "no-store",
        });
        if (!res.ok || !isMounted) return;
        const data = await res.json();
        const raw = data?.transport_options ?? data?.data?.transport_options;
        const arr = Array.isArray(raw) ? raw : [];
        const mapped: CheckoutTransportOption[] = arr
          .map((o: Record<string, unknown>) => ({
            id: String(o?.id ?? ""),
            code: String(o?.code ?? "").trim(),
            transport_type: String(o?.transport_type ?? "").trim(),
            label: String(o?.label ?? o?.name ?? "").trim(),
            description: String(o?.description ?? "").trim(),
            delivery_window: String(o?.delivery_window ?? "").trim(),
            amount: Number(o?.amount ?? 0),
            display_price: String(o?.display_price ?? "").trim(),
          }))
          .filter((o) => o.transport_type);
        const regionFromConfig = String(
          data?.region?.id ?? ""
        ).trim();
        const rawTrucks = data?.truck_types ?? data?.data?.truck_types;
        const truckArr = Array.isArray(rawTrucks) ? rawTrucks : [];
        if (isMounted) {
          setCheckoutTransportOptions(mapped);
          if (regionFromConfig) setCheckoutRegionId(regionFromConfig);
        }
      } catch {
      }
    };
    loadCheckoutConfig();
    return () => {
      isMounted = false;
    };
  }, [uiLocale]);

  useEffect(() => {
    let isMounted = true;

    const loadTruckTypesFromFormOptions = async () => {
      try {
        const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
        if (!base) return;
        const headers: Record<string, string> = {
          "content-type": "application/json",
          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
          "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
        };
        const res = await fetch(`${base}/store/form-options`, {
          method: "GET",
          headers,
          cache: "no-store",
        });
        if (!res.ok || !isMounted) return;
        const json = (await res.json()) as Record<string, unknown>;
        const forms = json?.forms as Record<string, unknown> | undefined;
        const block = forms?.["Checkout & Transport"] as Record<string, unknown> | undefined;
        const raw = block?.truck_type as Array<Record<string, unknown>> | undefined;
        if (!Array.isArray(raw)) return;

        const mapped = raw
          .map((item) => {
            const value = String(item?.value ?? "").trim();
            if (!value) return null;
            return {
              value,
              label: String(item?.label ?? value).trim() || value,
            } as CheckoutTruckTypeOption;
          })
          .filter(Boolean) as CheckoutTruckTypeOption[];

        if (mapped.length > 0) {
          setCheckoutTruckTypeOptions(mapped);
        }
      } catch {
      }
    };

    loadTruckTypesFromFormOptions();
    return () => {
      isMounted = false;
    };
  }, [uiLocale]);

  useEffect(() => {
    if (checkoutTransportOptions.length === 0) return;
    setConfigTransport((prev) => {
      const types = checkoutTransportOptions.map((o) => o.transport_type);
      if (types.includes(prev)) return prev;
      if (types.includes("standard")) return "standard";
      return types[0]!;
    });
  }, [checkoutTransportOptions]);

  useEffect(() => {
    if (checkoutTruckTypeOptions.length === 0) return;
    setConfigTruckType((prev) => {
      if (!prev) return prev;
      const values = checkoutTruckTypeOptions.map((o) => o.value);
      return values.includes(prev) ? prev : "";
    });
  }, [checkoutTruckTypeOptions]);

  useEffect(() => {
    if (!configureModalOpen) {
      setQuoteRequestSubmitted(false);
      setQuoteRequestSending(false);
    }
  }, [configureModalOpen]);

  useEffect(() => {
    if (!quoteRequestSubmitted) return;
    const timer = window.setTimeout(() => {
      setConfigureModalOpen(false);
      router.push("/");
    }, 5000);
    return () => window.clearTimeout(timer);
  }, [quoteRequestSubmitted, router]);

  useEffect(() => {
    if (configureModalOpen) {
      const prev = document.body.style.overflow;
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = prev;
      };
    }
  }, [configureModalOpen]);

  const visibleTabs = useMemo((): TabKey[] => {
    const tabs: TabKey[] = [];
    if (
      technicalSpecs.length > 0 ||
      typicalComposition.length > 0 ||
      recommendedApplications.length > 0
    ) {
      tabs.push("productDetails");
    }
    if (certificationsData.length > 0) tabs.push("certifications");
    if (transportInfoData.length > 0) tabs.push("transportInfo");
    if (complianceData.length > 0) tabs.push("compliance");
    return tabs;
  }, [
    technicalSpecs,
    typicalComposition,
    recommendedApplications,
    certificationsData,
    transportInfoData,
    complianceData,
  ]);

  useEffect(() => {
    if (visibleTabs.length === 0) return;
    if (!visibleTabs.includes(activeTab)) {
      setActiveTab(visibleTabs[0]!);
    }
  }, [visibleTabs, activeTab]);

  const currentTabIndex = visibleTabs.indexOf(activeTab);
  const goPrevTab = () => {
    if (visibleTabs.length === 0) return;
    const i = currentTabIndex < 0 ? 0 : currentTabIndex;
    setActiveTab(visibleTabs[(i - 1 + visibleTabs.length) % visibleTabs.length]!);
  };
  const goNextTab = () => {
    if (visibleTabs.length === 0) return;
    const i = currentTabIndex < 0 ? 0 : currentTabIndex;
    setActiveTab(visibleTabs[(i + 1) % visibleTabs.length]!);
  };

  useEffect(() => {
    let isMounted = true;
    const loadById = async () => {
      setApiResolved(null);
      setApiChecked(false);
      setSeoMeta(null);
      setCertificationsData([]);
      setTransportInfoData([]);
      setComplianceData([]);
      try {
        const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
        const id = decodeURIComponent(String(productId ?? "")).trim();
        if (!base || !id) {
          if (isMounted) setApiChecked(true);
          return;
        }

        let resolvedFromApi: ProductDetailData | null = null;

        const singleRes = await fetch(`${base}/store/product-detail/${encodeURIComponent(id)}`, {
          method: "GET",
          headers: {
            "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
            "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
          },
          cache: "no-store",
        });

        if (singleRes.ok) {
          const singleData = await singleRes.json();
          const singleItem = singleData?.product ?? singleData?.data ?? singleData;
          const productSlug = String(singleItem?.handle ?? id ?? "").trim();
          const urlMatchesProduct =
            typeof window !== "undefined" &&
            (marketplaceProductUrlPathMatches(
              window.location.pathname,
              singleItem?.category_tree,
              productSlug,
            ) ||
              marketplaceProductUrlHandleMatches(window.location.pathname, productSlug) ||
              marketplaceProductUrlHandleMatches(window.location.pathname, id));

          resolvedFromApi = mapApiProductToDetail(singleItem);
          if (!urlMatchesProduct || !resolvedFromApi) {
            resolvedFromApi = null;
          } else {
          const productDetails = singleItem?.product_details;
          const productDetailsRows = Array.isArray(productDetails?.data) ? productDetails.data : [];
          const technicalSection = productDetailsRows.find((row: any) => row?.slug === "technical-specifications");
          const typicalSection = productDetailsRows.find((row: any) => row?.slug === "typical-composition");
          const recommendedSection = productDetailsRows.find((row: any) => row?.slug === "recommended-applications");
          let apiTechnicalSpecs = Array.isArray(technicalSection?.data)
            ? technicalSection.data
              .map((item: any) => ({ label: String(item?.label ?? ""), value: String(item?.value ?? "") }))
              .filter((item: { label: string; value: string }) => item.label || item.value)
            : [];
          let apiTypicalComposition = Array.isArray(typicalSection?.data)
            ? typicalSection.data
              .map((item: any) => ({
                label: String(item?.label ?? ""),
                value_label: String(item?.value_label ?? ""),
                percentage: typeof item?.percentage === "number" ? item.percentage : undefined,
              }))
              .filter((item: { label: string; value_label: string }) => item.label || item.value_label)
            : [];
          let apiRecommendedApplications = Array.isArray(recommendedSection?.data)
            ? recommendedSection.data
              .map((item: any) => String(item ?? ""))
              .filter((item: string) => item.trim().length > 0)
            : [];
          if (apiTechnicalSpecs.length === 0) {
            const specs = singleItem?.technical_specifications;
            if (specs && typeof specs === "object" && !Array.isArray(specs)) {
              apiTechnicalSpecs = Object.entries(specs as Record<string, unknown>)
                .map(([label, value]) => ({
                  label: String(label),
                  value: String(value ?? ""),
                }))
                .filter((item) => item.label || item.value);
            }
          }
          if (apiTypicalComposition.length === 0 && Array.isArray(singleItem?.composition)) {
            apiTypicalComposition = singleItem.composition
              .map((item: any) => ({
                label: String(item?.label ?? ""),
                value_label: String(item?.value_label ?? ""),
                percentage: typeof item?.percentage === "number" ? item.percentage : undefined,
              }))
              .filter((item: { label: string; value_label: string }) => item.label || item.value_label);
          }
          if (apiRecommendedApplications.length === 0 && Array.isArray(singleItem?.recommended_applications)) {
            apiRecommendedApplications = singleItem.recommended_applications
              .map((item: any) => (typeof item === "string" ? item : String(item?.label ?? item?.value ?? "")))
              .filter((item: string) => item.trim().length > 0);
          }
          const certificationsSection = singleItem?.certifications;
          const transportInfoSection = singleItem?.transport_info;
          const complianceSection = singleItem?.compliance;
          const normalizeSectionData = (arr: any): string[] =>
            Array.isArray(arr)
              ? arr
                .map((item: any) => {
                  if (typeof item === "string") return item;
                  return String(item?.label ?? item?.name ?? item?.value ?? "");
                })
                .filter((item: string) => item.trim().length > 0)
              : [];
          let apiCertifications = normalizeSectionData(certificationsSection?.data);
          if (apiCertifications.length === 0) {
            apiCertifications = normalizeSectionData(singleItem?.certifications);
          }
          const apiTransportInfo = normalizeSectionData(transportInfoSection?.data);
          const apiCompliance = normalizeSectionData(complianceSection?.data);
          if (isMounted) {
            if (technicalSection?.name) setTechnicalSpecsTitle(String(technicalSection.name));
            if (typicalSection?.name) setTypicalCompositionTitle(String(typicalSection.name));
            if (recommendedSection?.name) setRecommendedAppsTitle(String(recommendedSection.name));
            if (certificationsSection?.name) setCertificationsTitle(String(certificationsSection.name));
            if (transportInfoSection?.name) setTransportInfoTitle(String(transportInfoSection.name));
            if (complianceSection?.name) setComplianceTitle(String(complianceSection.name));
            setTechnicalSpecs(apiTechnicalSpecs);
            setTypicalComposition(apiTypicalComposition);
            setRecommendedApplications(apiRecommendedApplications);
            setCertificationsData(apiCertifications);
            setTransportInfoData(apiTransportInfo);
            setComplianceData(apiCompliance);
          }
          }
        } else {
          resolvedFromApi = null;
        }

        if (isMounted) {
          setApiResolved(resolvedFromApi);
          setApiChecked(true);
        }
      } catch {
        if (isMounted) setApiChecked(true);
      }
    };

    loadById();
    return () => {
      isMounted = false;
    };
  }, [productId, uiLocale]);

  useEffect(() => {
    let isMounted = true;

    const loadVerifiedServices = async () => {
      try {
        const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
        if (!base) return;
        const res = await fetch(`${base}/store/pages/product-detail-page`, {
          method: "GET",
          headers: {
            "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
            "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
          },
          cache: "no-store",
        });
        if (!res.ok) return;
        const data = await res.json();
        const sections = data?.page?.sections ?? [];
        const sectionDataList = sections.flatMap((s: any) =>
          Array.isArray(s?.components) ? s.components.map((c: any) => c?.instance?.data) : []
        );
        const verifiedServicesData = sectionDataList.find((d: any) => d?.cards?.items);
        const title = String(verifiedServicesData?.title ?? "").trim();
        const cards = Array.isArray(verifiedServicesData?.cards?.items)
          ? verifiedServicesData.cards.items
            .map((item: any) => ({
              svg: String(item?.svg ?? ""),
              title: String(item?.title ?? ""),
              description: String(item?.description ?? ""),
            }))
            .filter((item: VerifiedServiceCard) => item.title || item.description || item.svg)
          : [];
        if (!isMounted) return;
        if (title) setVerifiedServicesTitle(title);
        setVerifiedServiceCards(cards);
      } catch {
      }
    };

    loadVerifiedServices();
    return () => {
      isMounted = false;
    };
  }, [uiLocale]);

  configQuantityRef.current = configQuantity;

  useEffect(() => {
    if (!configureModalOpen) {
      setConfigQuantityError("");
      return;
    }
    const max = apiResolved?.currentAvailableQuantity ?? null;
    if (max == null) return;
    const q = configQuantityRef.current;
    if (q > max) {
      setConfigQuantity(max);
      setConfigQuantityError(tc.quantityExceedsAvailable);
    }
  }, [configureModalOpen, apiResolved, tc.quantityExceedsAvailable]);

  const resolved = apiResolved;
  const isLoading = !apiChecked;
  const notFound = apiChecked && resolved == null;

  if (!authReady || isLoading) {
    return <PageLoading />;
  }

  if (notFound) {
    return (
      <div className="min-h-screen bg-[#F0F0F0] flex items-center justify-center px-4">
        <div className="text-center">
          <h1 className="font-outfit text-2xl font-bold text-[#333333] mb-2">{pd.notFoundTitle}</h1>
          <p className="font-outfit text-[#757575] mb-6">{pd.notFoundDescription}</p>
          <Link href="/marketplace" className="font-outfit text-[#053F31] font-medium underline hover:no-underline">
            {pd.backToMarketplace}
          </Link>
        </div>
      </div>
    );
  }

  const display = resolved!;
  const productImages = display.images.length > 0 ? display.images : (display.image ? [display.image] : []);
  const isInStock =
    display.currentAvailableQuantity != null && display.currentAvailableQuantity >= 1;
  const availabilityDisplay = resolveAvailabilityDisplay(
    display.availability,
    display.currentAvailableQuantity,
    pd.outOfStock,
  );

  const maxPurchaseQty = display.currentAvailableQuantity;

  const applyConfigQuantityFromInput = (raw: number) => {
    const base = Number.isFinite(raw) ? Math.floor(raw) : 1;
    const low = Math.max(1, base);
    if (maxPurchaseQty != null && low > maxPurchaseQty) {
      setConfigQuantity(maxPurchaseQty);
      setConfigQuantityError(tc.quantityExceedsAvailable);
      return;
    }
    setConfigQuantity(low);
    setConfigQuantityError("");
  };

  const handleProceedToCheckout = async () => {
    if (!configTruckType.trim()) {
      setConfigTruckTypeError(pd.truckTypeRequired);
      return;
    }
    setConfigTruckTypeError("");
    const capQty = display.currentAvailableQuantity;
    if (capQty != null && configQuantity > capQty) {
      setConfigQuantity(capQty);
      setConfigQuantityError(tc.quantityExceedsAvailable);
      return;
    }

    /*
    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
    const publishable = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "";
    const raw = localStorage.getItem("currentUser");
    const user = raw ? JSON.parse(raw) : null;
    const selectedTransport = checkoutTransportOptions.find((o) => o.transport_type === configTransport);
    const transportOptionId = selectedTransport?.code || selectedTransport?.id || "";
    const regionId = (checkoutRegionId || process.env.NEXT_PUBLIC_MEDUSA_REGION_ID || "").trim();
    const body = {
      variant_id: display.variantId,
      region_id: regionId,
      quantity: configQuantity,
      transport_option_id: transportOptionId,
      truck_type: configTruckType,
    };
    let cartIdParam = "";
    if (base) {
      try {
        const postHeaders: Record<string, string> = {
          "Content-Type": "application/json",
          "x-publishable-api-key": publishable,
        };
        const authTok = String(user?.token ?? user?.access_token ?? "").trim();
        if (authTok) postHeaders.Authorization = `Bearer ${authTok}`;
        const res = await fetch(`${base}/store/cart`, {
          method: "POST",
          headers: postHeaders,
          body: JSON.stringify(body),
        });
        if (res.ok) {
          const json = (await res.json().catch(() => ({}))) as {
            cart_id?: string;
            cartId?: string;
            id?: string;
            cart?: { id?: string };
            data?: { cart_id?: string; cart?: { id?: string } };
          };
          cartIdParam = String(
            json.cart_id ?? ""
          ).trim();
        }
        if (cartIdParam) {
          setConfigureModalOpen(false);
          router.push(`/payment?cartId=${encodeURIComponent(cartIdParam)}`);
        }
        return;
      } catch {
      }
    }
    setConfigureModalOpen(false);
    router.push(`/payment?cartId=${encodeURIComponent(cartIdParam)}`);
    */

    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
    const publishable = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "";
    const raw = localStorage.getItem("currentUser");
    const user = raw ? JSON.parse(raw) : null;
    const authTok = String(user?.token ?? user?.access_token ?? "").trim();
    const unitPrice = parseFloat(display.price);
    const basePrice = Number.isFinite(unitPrice) ? unitPrice : 0;
    const totalPrice = Math.round(basePrice * configQuantity * 100) / 100;
    const currencySymbol = String(display.currency_symbol ?? "").trim();
    const currencyCode =
      currencySymbol === "€" ? "EUR" : currencySymbol === "$" ? "USD" : currencySymbol === "£" ? "GBP" : "EUR";
    const quoteBody = {
      product_name: display.title,
      product_url: typeof window !== "undefined" ? window.location.href : "",
      quantity: configQuantity,
      quantity_unit: display.priceUnit.trim() || "t",
      truck_type: configTruckType,
      base_price: Math.round(basePrice * 100) / 100,
      total_price: totalPrice,
      currency_code: currencyCode,
    };

    setQuoteRequestSending(true);
    if (base) {
      try {
        const postHeaders: Record<string, string> = {
          "Content-Type": "application/json",
          "x-publishable-api-key": publishable,
        };
        if (authTok) postHeaders.Authorization = `Bearer ${authTok}`;
        const res = await fetch(`${base}/store/quote-request`, {
          method: "POST",
          headers: postHeaders,
          body: JSON.stringify(quoteBody),
        });
        const json = (await res.json().catch(() => ({}))) as { success?: boolean };
        if (res.ok && json.success === true) {
          setQuoteRequestSubmitted(true);
        }
      } catch {
      } finally {
        setQuoteRequestSending(false);
      }
      return;
    }
    setQuoteRequestSending(false);

  };

  return (
    <div className="mx-auto max-w-[1360px] 2xl:max-w-[1840px] pb-[70px] px-[20px] md:px-[40px] xl:px-[60px] overflow-x-hidden">
      <div className="mb-10 overflow-hidden rounded-2xl ">
        <div className="
  grid 
  grid-cols-1 
  min-[1024px]:grid-cols-2 
  min-[1280px]:grid-cols-[3fr_5fr_2fr]
  lg:gap-[50px]
  pt-4 pb-6 
  lg:pt-[50px] lg:pb-[25px]
">
          <div className="w-full min-w-0 px-4 pt-2 lg:px-0 lg:pt-0">
            <ProductZoom
              mainImageSrc={productImages[imageIndex] ?? ""}
              highResImageSrc={productImages[imageIndex] ?? ""}
            >
              <div className="absolute z-30 bottom-6 left-1/2 -translate-x-1/2 flex gap-2.5 items-center justify-center rounded-full bg-[#DDDDDD]/90 px-6 py-2 w-fit select-none">
                {productImages.map((_, i) => (
                  <button
                    key={i}
                    type="button"
                    onClick={() => setImageIndex(i)}
                    className={`h-2.5 w-2.5 shrink-0 rounded-full transition-all duration-300 ${i === imageIndex ? "bg-[#053F31] scale-110" : "bg-white/80 hover:bg-white"}`}
                    aria-label={pd.imageAriaLabel.replace("{n}", String(i + 1))}
                  />
                ))}
              </div>
            </ProductZoom>
          </div>

          <div className="flex flex-col w-full min-w-0 px-4 lg:px-0 md:mt-5 lg:mt-0">
            <div className="pb-4 lg:pb-[25px] border-b border-[#D9D9D9] flex flex-wrap items-start lg:items-center justify-between gap-3">
              <span className="font-outfit text-[22px] font-semibold text-[#333333] lg:text-[30px] leading-tight mt-[50px] md:mt-0 lg:mt-0">{display.title}</span>
              <div className="flex flex-wrap items-center gap-2 shrink-0">
                {display.subtitle && (
                  <span className="rounded-[10px] border border-[#053F31]/20 bg-[#DAE6DC] px-3 py-1.5 font-outfit text-[14px] font-semibold text-[#053F31]">
                    {display.subtitle}
                  </span>
                )}
                {/* {availabilityDisplay && (
                  <span
                    className={`rounded-[10px] border px-3 py-1.5 font-outfit text-[14px] font-semibold ${availabilityDisplay.className}`}
                  >
                    {availabilityDisplay.label}
                  </span>
                )} */}
              </div>
            </div>
            {display.code && <div className="flex items-center justify-between gap-3 border-b border-[#D9D9D9] py-4">
              <span className="font-outfit text-[16px] leading-[150%] font-semibold text-[#000000]">{pd.codeLabel}</span>
              <span className="font-outfit text-[18px] lg:text-[20px] leading-5 font-semibold text-[#757575]">{display.code}</span>
            </div>}
            <p className="mb-5 lg:mb-[25px] font-outfit font-light text-[15px] lg:text-base text-[#757575] leading-relaxed">
              {display.description}
            </p>

            <div className="mb-5 lg:mb-[25px] grid grid-cols-1 gap-4 sm:grid-cols-2 sm:gap-4 pb-5 lg:pb-[25px] border-b border-[#D9D9D9]">
              <div className="group flex items-center gap-4">
                <div className="shrink-0 w-[57px] sm:h-[57px] flex items-center justify-center rounded-[10px] bg-[#DAE6DC] overflow-hidden transition-transform duration-300 ease-in-out hover:scale-x-[-1] group-hover:scale-x-[-1]">
                  <span className=" origin-center">
                    <IconQuantity />
                  </span>
                </div>
                <div className="min-w-0 flex-1">
                  <p className="font-outfit text-[14px] leading-[150%] font-light text-[#757575] sm:text-[16px]">{pd.availableQuantity}</p>
                  <p className="font-outfit text-[15px] sm:text-[16px] font-semibold text-[#333333] mt-0.5">{display.quantity}</p>
                </div>
              </div>
              <div className="group flex items-center gap-4">
                <div className="shrink-0 w-[57px] sm:h-[57px] flex items-center justify-center rounded-[10px] bg-[#DAE6DC] overflow-hidden transition-transform duration-300 ease-in-out hover:scale-x-[-1] group-hover:scale-x-[-1]">
                  <span className=" origin-center">
                    <IconFrequency />
                  </span>
                </div>
                <div className="min-w-0 flex-1">
                  <p className="font-outfit text-[14px] leading-[150%] font-light text-[#757575] sm:text-[16px]">{pd.supplyFrequency}</p>
                  <p className="font-outfit text-[15px] sm:text-[16px] font-semibold text-[#333333] mt-0.5">{display.supplyFrequency}</p>
                </div>
              </div>
              <div className="group flex items-center gap-4">
                <div className="shrink-0 w-[57px] sm:h-[57px] flex items-center justify-center rounded-[10px] bg-[#DAE6DC] overflow-hidden transition-transform duration-300 ease-in-out hover:scale-x-[-1] group-hover:scale-x-[-1]">
                  <span className=" origin-center">
                    <IconLocation />
                  </span>
                </div>
                <div className="min-w-0 flex-1 ">
                  <p className="font-outfit text-[14px] leading-[150%] font-light text-[#757575] sm:text-[16px]">{pd.productLocation}</p>
                  <p className="font-outfit text-[15px] sm:text-[16px] font-semibold text-[#333333] mt-0.5">{display.location}</p>
                  <p className="font-outfit text-[13px] sm:text-sm text-[#757575] mt-0.5">{display.locationDetail}</p>
                </div>
              </div>
              <div className="group flex items-center gap-4">
                <div className="shrink-0 w-[57px] sm:h-[57px] flex items-center justify-center rounded-[10px] bg-[#DAE6DC] overflow-hidden transition-transform duration-300 ease-in-out hover:scale-x-[-1] group-hover:scale-x-[-1]">
                  <span className=" origin-center">
                    <IconWasteType />
                  </span>
                </div>
                <div className="min-w-0 flex-1">
                  <p className="font-outfit text-[14px] leading-[150%] font-light text-[#757575] sm:text-[16px]">{pd.wasteType}</p>
                  <p className="font-outfit text-[15px] sm:text-[16px] font-semibold text-[#333333] mt-0.5">{display.wasteType}</p>
                </div>
              </div>
            </div>
          </div>

          <div className="flex flex-col w-full min-w-0 px-4 lg:px-0">
            <div className="mb-5 lg:mb-[25px] pb-5 lg:pb-[25px] flex flex-col flex-row flex-wrap items-baseline justify-between gap-2 border-b border-[#D9D9D9] mt-0">
              <div className="flex items-center gap-1.5 flex-wrap ">

                <span className="font-outfit leading-tight font-semibold text-[#053F31] text-[22px] sm:text-[25px]">{display.currency_symbol}{display.price}</span>
                <span className="font-outfit text-[14px] sm:text-[16px] leading-[150%] font-light text-[#757575]">{pd.priceUnitSlash} {display.priceUnit} </span>
              </div>
              <span className="font-outfit leading-[150%] font-light ">{pd.transportCostsNote}</span>
            </div>

            <div className="flex flex-col gap-4 sm:gap-5 w-full max-w-full">
              {isInStock ? (
                <button
                  type="button"
                  onClick={() => setConfigureModalOpen(true)}
                  className="group relative w-full min-w-0 h-[50px] cursor-pointer flex items-center justify-start md:justify-center pl-4 rounded-full bg-[#053F31] text-[#FFFFFF] font-semibold text-[16px] sm:text-[18px] transition-colors hover:bg-white hover:text-[#053F31] hover:border-2 hover:border-[#053F31]"
                >
                  <span>{pd.buyNow}</span>
                  <span className="absolute right-2 flex items-center justify-center w-9 h-9 [&_path:first-of-type]:transition-[fill] [&_path:last-of-type]:transition-[stroke] group-hover:[&_path:first-of-type]:fill-[#053F31] group-hover:[&_path:last-of-type]:stroke-white">
                    <IconArrowRight />
                  </span>
                </button>
              ) : (
                <p
                  className={`w-full min-w-0 h-[50px] flex items-center justify-center rounded-full border-2 font-outfit font-semibold text-[16px] sm:text-[18px] ${
                    availabilityDisplay?.className ?? "border-[#FF4D4D] text-[#FF4D4D]"
                  }`}
                >
                  {availabilityDisplay?.label ?? pd.outOfStock}
                </p>
              )}

              {display.technicalSheetUrl ? (
                <button
                  type="button"
                  onClick={() => {
                    const link = document.createElement("a");
                    link.href = display.technicalSheetUrl;
                    link.download = display.technicalSheetFilename || pd.technicalSheetDefaultFilename;
                    link.target = "_blank";
                    link.rel = "noopener noreferrer";
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                  }}
                  className="group relative w-full min-w-0 h-[50px] cursor-pointer flex items-center md:justify-center justify-start pl-4 xl:pr-10 rounded-full bg-[#053F31] text-[#FFFFFF] font-semibold text-[16px] sm:text-[18px] transition-colors hover:bg-white hover:text-[#053F31] hover:border-2 hover:border-[#053F31]"
                >
                  <span className="truncate">{pd.downloadTechnicalSheet}</span>
                  <span className="absolute right-2 flex items-center justify-center w-9 h-9 [&_path:first-of-type]:transition-[fill] [&_path:last-of-type]:transition-[stroke] group-hover:[&_path:first-of-type]:fill-[#053F31] group-hover:[&_path:last-of-type]:stroke-white">
                    <IconDownload />
                  </span>
                </button>
              ) : null}
            </div>
          </div>
        </div>
      </div>

      {visibleTabs.length > 0 ? (
        <div className="mb-6 sm:mb-[40px] overflow-x-hidden">
          <div className="flex items-center justify-between gap-2 py-3 px-4 sm:bg-transparent sm:py-0 sm:px-0 sm:block sm:border-b sm:border-[#D9D9D9] sm:pb-6 sm:pb-[30px]">
            <button
              type="button"
              onClick={goPrevTab}
              className="shrink-0 flex items-center justify-center w-10 h-10 rounded-full text-[#053F31] hover:bg-[#053F31]/10 sm:hidden"
              aria-label={pd.ariaPreviousTab}
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6" /></svg>
            </button>
            <nav className="flex items-center overflow-x-auto min-w-0 flex-1 justify-center 2xl:justify-between sm:flex-initial">
              {visibleTabs.map((tab) => (
                <button
                  key={tab}
                  type="button"
                  onClick={() => setActiveTab(tab)}
                  className={`w-[208px] h-[50px] shrink-0 cursor-pointer px-4 sm:px-6 py-2.5 sm:py-3 font-outfit rounded-[10px] text-[20px] leading-[20%] font-regular transition-colors ${activeTab === tab
                    ? "2xl:w-[472px] bg-[#053F31] text-white font-bold"
                    : "2xl:w-[340px] text-[#000000] hover:text-[#053F31] hidden sm:inline-block"
                    }`}
                >
                  {pd.tabs[tab]}
                </button>
              ))}
            </nav>
            <button
              type="button"
              onClick={goNextTab}
              className="shrink-0 flex items-center justify-center w-10 h-10 rounded-full text-[#053F31] hover:bg-[#053F31]/10 sm:hidden"
              aria-label={pd.ariaNextTab}
            >
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 18l6-6-6-6" /></svg>
            </button>
          </div>
        </div>
      ) : null}

      {visibleTabs.length > 0 && activeTab === "productDetails" && (
        <div className="flex flex-col xl:flex-row gap-4 2xl:gap-5 min-w-0 px-4 sm:px-6 md:px-0">

          <div className="w-full xl:w-[58%] rounded-[20px] border border-[#DAE6DC] bg-white sm:bg-[#F7FAF8] p-4 sm:p-[30px] min-w-0">
            <h3 className="font-outfit font-semibold text-[#053F31]">
              {technicalSpecsTitle || pd.technicalSpecsDefaultTitle}
            </h3>
            <div className="border-b border-[#D9D9D9] block mt-5" />
            <div className="space-y-0">
              {technicalSpecs.map(({ label, value }, i) => (
                <div
                  key={label}
                  className={`flex flex-col sm:flex-row sm:items-start sm:justify-between gap-1 py-4 sm:pb-[20px] sm:pt-[20px] min-w-0 border-b border-[#DDDDDD] last:border-none last:pb-0`}
                >
                  <p className="font-outfit text-[14px] font-medium text-[#000000] shrink-0 sm:max-w-[45%]">
                    {label}
                  </p>
                  <p className="font-outfit text-[14px] font-light text-[#757575] sm:text-right break-words">
                    {value}
                  </p>
                </div>
              ))}
            </div>
          </div>

          <div className="w-full xl:w-[42%] space-y-6 min-w-0">

            <div className="rounded-[20px] border border-[#DAE6DC] bg-[#F7FAF8] p-4 sm:p-[30px]">
              <h3 className="font-outfit text-[18px] sm:text-[22px] font-semibold text-[#053F31]">
                {typicalCompositionTitle || pd.typicalCompositionDefaultTitle}
              </h3>
              <div className="mt-5 border-t border-[#D9D9D9]" />
              <div className="mt-5 space-y-4 sm:space-y-6">
                {typicalComposition.map(({ label, value_label, percentage }) => {
                  const fill = Math.max(0, Math.min(100, Number(percentage ?? 0)));
                  return (
                    <div key={label} className="flex items-center gap-4 min-w-0 flex-wrap">
                      <div className="relative h-[2px] w-full 2xl:max-w-[670px] xl:max-w-[310px] shrink-0 rounded-full bg-[#DAE6DC]">
                        <div
                          className="absolute left-0 top-1/2 -translate-y-1/2 h-[6px] rounded-full bg-[#053F31]"
                          style={{ width: `${fill}%` }}
                        />
                        <div
                          className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2"
                          style={{ left: `${fill}%` }}
                        >
                          <div className="flex h-3.5 w-3.5 items-center justify-center rounded-full border-2 border-[#053F31] bg-[#DAE6DC]">
                            <div className="h-1.5 w-1.5 rounded-full bg-[#0B4D3B]" />
                          </div>
                        </div>
                      </div>
                      <div className="flex flex-1 items-center  min-w-0 gap-2 flex-wrap">
                        <span className="font-outfit font-light text-[18px] text-[#757575] truncate">{label}</span>

                        <span className="font-outfit font-light text-[18px] text-[#757575] shrink-0">{value_label}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            <div className="rounded-[20px] border border-[#DAE6DC] bg-[#F7FAF8] p-4 sm:p-[30px]">
              <h3 className="font-outfit text-[18px] sm:text-[22px] font-semibold text-[#053F31]">
                {recommendedAppsTitle || pd.recommendedAppsDefaultTitle}
              </h3>
              <div className="mt-5 border-t border-[#D9D9D9]" />
              <ul className="mt-5 space-y-2 sm:space-y-[10px]">
                {recommendedApplications.map((item) => (
                  <li
                    key={item}
                    className="flex items-center gap-2 sm:gap-[10px] font-outfit text-[16px] sm:text-[20px] leading-[150%] font-light text-[#757575]"
                  >
                    <span className="flex items-center justify-center shrink-0">
                      <IconCheck />
                    </span>
                    {item}
                  </li>
                ))}
              </ul>
            </div>

          </div>
        </div>
      )}

      {visibleTabs.length > 0 && activeTab === "certifications" && (
        <div className="flex flex-col gap-6 lg:flex-row lg:gap-8 2xl:gap-[40px] min-w-0 px-4 sm:px-6 md:px-0">
          <div className="w-full rounded-[20px] border border-[#DAE6DC] bg-white sm:bg-[#F7FAF8] p-4 sm:p-[30px] min-w-0">
            <h3 className="font-outfit text-[18px] sm:text-[22px] font-semibold text-[#053F31] mb-6">{certificationsTitle || pd.certificationsDefaultTitle}</h3>
            {certificationsData.length > 0 ? (
              <ul className="space-y-2 sm:space-y-[10px]">
                {certificationsData.map((item) => (
                  <li key={item} className="flex items-center gap-2 sm:gap-[10px] font-outfit text-[16px] sm:text-[20px] leading-[150%] font-light text-[#757575]">
                    <span className="flex items-center justify-center shrink-0">
                      <IconCheck />
                    </span>
                    {item}
                  </li>
                ))}
              </ul>
            ) : (
              <p className="font-outfit text-[14px] sm:text-base font-light text-[#757575]">{pd.dataNotFound}</p>
            )}
          </div>
        </div>
      )}

      {visibleTabs.length > 0 && activeTab === "transportInfo" && (
        <div className="flex flex-col gap-6 lg:flex-row lg:gap-8 2xl:gap-[40px] min-w-0 px-4 sm:px-6 md:px-0">
          <div className="w-full rounded-[20px] border border-[#DAE6DC] bg-white sm:bg-[#F7FAF8] p-4 sm:p-[30px] min-w-0">
            <h3 className="font-outfit text-[18px] sm:text-[22px] font-semibold text-[#053F31] mb-6">{transportInfoTitle || pd.transportInfoDefaultTitle}</h3>
            {transportInfoData.length > 0 ? (
              <ul className="space-y-2 sm:space-y-[10px]">
                {transportInfoData.map((item) => (
                  <li key={item} className="flex items-center gap-2 sm:gap-[10px] font-outfit text-[16px] sm:text-[20px] leading-[150%] font-light text-[#757575]">
                    <span className="flex items-center justify-center shrink-0">
                      <IconCheck />
                    </span>
                    {item}
                  </li>
                ))}
              </ul>
            ) : (
              <p className="font-outfit text-[14px] sm:text-base font-light text-[#757575]">{pd.dataNotFound}</p>
            )}
          </div>
        </div>
      )}

      {visibleTabs.length > 0 && activeTab === "compliance" && (
        <div className="flex flex-col gap-6 lg:flex-row lg:gap-8 2xl:gap-[40px] min-w-0 px-4 sm:px-6 md:px-0">
          <div className="w-full rounded-[20px] border border-[#DAE6DC] bg-white sm:bg-[#F7FAF8] p-4 sm:p-[30px] min-w-0">
            <h3 className="font-outfit text-[18px] sm:text-[22px] font-semibold text-[#053F31] mb-6">{complianceTitle || pd.complianceDefaultTitle}</h3>
            {complianceData.length > 0 ? (
              <ul className="space-y-2 sm:space-y-[10px]">
                {complianceData.map((item) => (
                  <li key={item} className="flex items-center gap-2 sm:gap-[10px] font-outfit text-[16px] sm:text-[20px] leading-[150%] font-light text-[#757575]">
                    <span className="flex items-center justify-center shrink-0">
                      <IconCheck />
                    </span>
                    {item}
                  </li>
                ))}
              </ul>
            ) : (
              <p className="font-outfit text-[14px] sm:text-base font-light text-[#757575]">{pd.dataNotFound}</p>
            )}
          </div>
        </div>
      )}
      <div className="mx-[50px] sm:mx-12 md:mx-14 lg:mx-16 xl:mx-[70px] mt-[50px] sm:mt-12 md:mt-14 lg:mt-16 xl:mt-[70px]">
        <h2 className="font-extralight mb-8 md:mb-[72px] text-black leading-tight text-center">
          {(() => {
            const title = verifiedServicesTitle.trim() || pd.verifiedServicesDefaultTitle;
            const words = title.trim().split(/\s+/).filter(Boolean);
            if (words.length <= 1) return title;
            return (
              <>
                {words[0]}{" "}
                <span className="font-medium">{words.slice(1).join(" ")}</span>
              </>
            );
          })()}
        </h2>
        <div className="flex flex-col gap-6 md:flex-row md:gap-6 min-w-0 justify-center">
          {verifiedServiceCards.map(({ title, description, svg }, index) => {
            const isElevated = hoveredBottomCard === index;
            return (
              <div
                key={title}
                onMouseEnter={() => setHoveredBottomCard(index)}
                onMouseLeave={() => setHoveredBottomCard(null)}
                className={`rounded-[20px] max-w-[500px] max-h-[300px] border border-[#E6E6E6] bg-white px-[30px] pt-[30px] pb-[120px] transition-all duration-500 ease-out cursor-pointer md:flex-1 ${isElevated ? "md:-mt-[50px] shadow-[inset_0_3px_0_#053F31,0_15px_20px_-10px_rgba(0,0,0,0.15)] z-10" : "md:mt-0"}`}
              >
                <div className="mb-[20px]">
                  <span className="block [&_svg]:h-[50px] [&_svg]:w-[50px]" dangerouslySetInnerHTML={{ __html: svg }} />
                </div>
                <h3 className="mb-[20px] font-outfit text-[20px] font-bold text-[#000000]">{title}</h3>
                <p className="font-outfit text-[16px] font-light leading-relaxed text-[#757575]">{description}</p>
              </div>
            );
          })}
        </div>
      </div>
      {typeof document !== "undefined" &&
        configureModalOpen &&
        createPortal(
          <div className="fixed inset-0 z-[1000] flex items-center justify-center p-4 font-outfit bg-black/50 backdrop-blur-sm" onClick={() => setConfigureModalOpen(false)}>
          <div className="relative w-full max-w-[710px] max-h-[100vh] overflow-y-auto rounded-[20px] border border-[#053F31]/20 bg-[#F7FAF8] shadow-xl font-outfit" onClick={(e) => e.stopPropagation()}>
            <div className="sticky top-0 z-10 bg-white rounded-t-[20px]">
              <div className="flex flex-col items-start justify-between p-[20px]">
                <div className="flex w-full flex-row items-center justify-between pb-5 border-b border-[#000000]/10">
                  <div>
                    <p className="text-[25px] leading-[25%] font-semibold text-[#053F31]">{tc.title}</p>
                  </div>
                  <button type="button" onClick={() => setConfigureModalOpen(false)} className="shrink-0 p-1 rounded-md hover:bg-[#DAE6DC]/50 text-[#424242] cursor-pointer" aria-label={tc.closeAria}>
                    <svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" viewBox="0 0 21 21" fill="none">
                      <path d="M0.707718 20.2905C0.774058 20.3569 0.852839 20.4096 0.939555 20.4456C1.02627 20.4815 1.11922 20.5 1.2131 20.5C1.30697 20.5 1.39992 20.4815 1.48664 20.4456C1.57335 20.4096 1.65213 20.3569 1.71847 20.2905L10.4974 11.5124L19.2799 20.2905C19.4139 20.4245 19.5957 20.4998 19.7853 20.4998C19.9748 20.4998 20.1566 20.4245 20.2907 20.2905C20.4247 20.1565 20.5 19.9747 20.5 19.7852C20.5 19.5956 20.4247 19.4139 20.2907 19.2799L11.5082 10.5017L20.2871 1.71998C20.4211 1.58596 20.4964 1.40419 20.4964 1.21465C20.4964 1.02511 20.4211 0.843338 20.2871 0.709316C20.1531 0.575293 19.9713 0.5 19.7817 0.5C19.5922 0.5 19.4104 0.575293 19.2763 0.709316L10.4974 9.49104L1.7149 0.712887C1.57825 0.595874 1.40248 0.53473 1.2227 0.541673C1.04292 0.548616 0.872389 0.623136 0.745174 0.75034C0.617958 0.877544 0.543432 1.04806 0.536488 1.22782C0.529544 1.40758 0.590694 1.58334 0.707718 1.71998L9.48665 10.5017L0.707718 19.2834C0.574676 19.4172 0.5 19.5983 0.5 19.787C0.5 19.9757 0.574676 20.1567 0.707718 20.2905Z" fill="#053F31" stroke="#053F31" />
                    </svg>
                  </button>
                </div>

                <div className="w-full pt-5 space-y-[15px]">
                  <p className="font-light text-[#000000]">{tc.intro}</p>
                  <div className="flex items-center gap-[22px]">
                    <img src={display.image} alt={tc.productImageAlt} className="h-16 w-16 rounded-[10px] object-cover bg-[#F5F5F5]" />
                    <div>
                      <p className="font-thin text-[#000000] uppercase">{tc.productLabel}</p>
                      <p className="font-medium text-[#000000]">{display.title}</p>
                    </div>
                  </div>

                  <div className="rounded-[20px] bg-[#DAE6DC]/70 border border-[#053F31]/10 p-4">
                    <div className="flex items-center gap-5 pb-[5px] mb-2.5 border-b border-[#DDDDDD]">
                      <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 30 30" fill="none">
                        <path d="M29.0552 16.1016L22.0629 12.0645V4.48194C22.0629 4.39902 22.0411 4.31754 21.9997 4.24572C21.9582 4.1739 21.8986 4.11427 21.8267 4.07281L14.8819 0.0632621C14.8101 0.0218176 14.7286 0 14.6457 0C14.5628 0 14.4813 0.0218176 14.4095 0.0632621L7.46478 4.07288C7.39294 4.11433 7.3333 4.17396 7.29184 4.24579C7.25038 4.31761 7.22856 4.39908 7.22859 4.48201V12.2231L0.243291 16.0977C0.169556 16.1386 0.108107 16.1984 0.0653245 16.2711C0.0225421 16.3437 -1.3297e-05 16.4265 1.82283e-08 16.5108V24.6938C-2.30203e-05 24.7767 0.0217929 24.8582 0.0632532 24.93C0.104714 25.0018 0.164356 25.0614 0.236181 25.1029L7.32286 29.1944C7.39466 29.2359 7.47612 29.2577 7.55904 29.2577C7.64196 29.2577 7.72342 29.2359 7.79522 29.1944L14.6457 25.2391L21.4962 29.1943C21.568 29.2357 21.6495 29.2576 21.7324 29.2576C21.8153 29.2576 21.8968 29.2357 21.9686 29.1943L29.0552 25.1028C29.127 25.0613 29.1867 25.0017 29.2281 24.9299C29.2696 24.858 29.2914 24.7766 29.2914 24.6936V16.5107C29.2914 16.4278 29.2696 16.3463 29.2281 16.2745C29.1867 16.2027 29.127 16.143 29.0552 16.1016ZM1.43158 16.5189L7.69638 13.044L13.7009 16.5107L7.55918 20.0567L1.43158 16.5189ZM14.1733 8.76425V15.6925L8.17346 12.2284V5.30027L14.1733 8.76425ZM21.1181 12.2284L15.1182 15.6925V8.76425L21.1181 5.30014V12.2284ZM15.1182 17.3289L21.26 20.8749V27.9669L15.1182 24.4209V17.3289ZM21.7324 20.0567L15.5905 16.5107L21.7324 12.9647L27.8741 16.5107L21.7324 20.0567ZM14.6457 1.01783L20.6457 4.48194L14.6457 7.94605L8.64582 4.48201L14.6457 1.01783ZM0.944863 17.3289L7.08675 20.8749V27.9669L0.944863 24.4209V17.3289ZM8.03154 27.9669V20.8749L14.1733 17.3289V24.4209L8.03154 27.9669ZM22.2048 27.9669V20.8749L28.3466 17.329V24.4209L22.2048 27.9669Z" fill="black" />
                      </svg>
                      <div className="flex items-center gap-1">
                      <span className="text-[20px] leading-[150%] font-medium text-[#000000]">{tc.quantity}</span>
                      <p className="font-light text-[#000000]">
                        {display.priceUnit.trim() ? `(${display.priceUnit.trim()})` : tc.tonnesParens}
                      </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-3 flex-wrap">
                      <button
                        type="button"
                        onClick={() => {
                          setConfigQuantity((q) => {
                            const max = display.currentAvailableQuantity;
                            const next = Math.max(1, q - 1);
                            if (max == null || next <= max) setConfigQuantityError("");
                            return next;
                          });
                        }}
                        className="flex h-[50px] w-[47px] shrink-0 items-center justify-center rounded-[5px] border border-[#053F31]/10 bg-white text-[#053F31] font-semibold hover:bg-[#F0F0F0] transition-colors"
                      >
                        −
                      </button>
                      <input
                        type="number"
                        min={1}
                        max={maxPurchaseQty ?? undefined}
                        value={configQuantity}
                        onChange={(e) => {
                          const parsed = parseInt(e.target.value, 10);
                          applyConfigQuantityFromInput(Number.isNaN(parsed) ? 1 : parsed);
                        }}
                        aria-invalid={!!configQuantityError}
                        className={`w-[136px] h-[50px] text-center rounded-[5px] border text-[#053F31] bg-white text-[20px] leading-[150%] font-semibold ${configQuantityError ? "border-red-600" : "border-[#053F31]/10"}`}
                      />
                      <button
                        type="button"
                        onClick={() => {
                          setConfigQuantity((q) => {
                            const max = display.currentAvailableQuantity;
                            const wanted = q + 1;
                            if (max != null && wanted > max) {
                              setConfigQuantityError(tc.quantityExceedsAvailable);
                              return max;
                            }
                            setConfigQuantityError("");
                            return wanted;
                          });
                        }}
                        className="flex h-[50px] w-[47px] shrink-0 items-center justify-center rounded-[5px] border border-[#053F31]/10 bg-white text-[#053F31] font-semibold hover:bg-[#F0F0F0] transition-colors"
                      >
                        +
                      </button>
                      <div className="ml-auto text-right">
                        <p className="font-thin text-[#000000] uppercase">{tc.basePriceUppercase}</p>
                        <p className="font-medium text-[#000000]">€{(parseFloat(display.price) * configQuantity).toFixed(2)}</p>
                      </div>
                    </div>
                    {configQuantityError ? (
                      <p className="mt-2 text-[13px] text-red-600" role="alert">
                        {configQuantityError}
                      </p>
                    ) : null}
                  </div>
                  {/* <div className="rounded-[20px] bg-[#DAE6DC]/70 border border-[#053F31]/10 p-4">
                    <div className="flex items-center gap-5 pb-[5px] mb-2.5 border-b border-[#DDDDDD]">
                      <svg xmlns="http://www.w3.org/2000/svg" width="35" height="19" viewBox="0 0 35 19" fill="none">
                        <path d="M30.0516 18.9459C29.4585 18.9463 28.8785 18.7708 28.3852 18.4416C27.8918 18.1124 27.5072 17.6443 27.2799 17.0965C27.0526 16.5486 26.9929 15.9457 27.1084 15.3639C27.2238 14.7822 27.5092 14.2477 27.9285 13.8282C28.3477 13.4086 28.8819 13.1229 29.4636 13.007C30.0453 12.8911 30.6483 12.9504 31.1963 13.1772C31.7443 13.4041 32.2127 13.7884 32.5422 14.2815C32.8718 14.7747 33.0477 15.3544 33.0477 15.9476C33.0473 16.7423 32.7316 17.5043 32.1699 18.0665C31.6081 18.6286 30.8463 18.9449 30.0516 18.9459ZM30.0516 14.043C29.6748 14.0425 29.3063 14.1539 28.9928 14.3629C28.6793 14.5719 28.4349 14.8692 28.2904 15.2172C28.1459 15.5652 28.1079 15.9482 28.1811 16.3178C28.2544 16.6874 28.4356 17.0269 28.7019 17.2935C28.9681 17.5601 29.3075 17.7417 29.677 17.8154C30.0465 17.889 30.4296 17.8515 30.7777 17.7074C31.1259 17.5633 31.4235 17.3192 31.6328 17.0059C31.8422 16.6927 31.954 16.3243 31.954 15.9476C31.9538 15.4429 31.7533 14.9589 31.3967 14.6018C31.04 14.2447 30.5563 14.0437 30.0516 14.043ZM14.2513 18.9459C13.6581 18.9465 13.0781 18.7711 12.5847 18.442C12.0912 18.1129 11.7065 17.6448 11.4791 17.097C11.2517 16.5492 11.1919 15.9462 11.3073 15.3644C11.4226 14.7826 11.708 14.2481 12.1272 13.8284C12.5464 13.4088 13.0806 13.123 13.6623 13.007C14.244 12.8911 14.847 12.9503 15.3951 13.1772C15.9431 13.404 16.4116 13.7883 16.7412 14.2815C17.0707 14.7746 17.2467 15.3544 17.2467 15.9476C17.2461 16.7421 16.9304 17.5039 16.3689 18.066C15.8073 18.6281 15.0458 18.9445 14.2513 18.9459ZM14.2513 14.043C13.8744 14.0424 13.5059 14.1536 13.1923 14.3625C12.8787 14.5715 12.6342 14.8687 12.4896 15.2167C12.345 15.5646 12.3068 15.9477 12.38 16.3173C12.4532 16.687 12.6343 17.0266 12.9006 17.2933C13.1668 17.5599 13.5062 17.7416 13.8757 17.8153C14.2452 17.889 14.6283 17.8515 14.9765 17.7074C15.3247 17.5634 15.6223 17.3193 15.8317 17.006C16.0411 16.6927 16.1529 16.3244 16.1529 15.9476C16.1525 15.443 15.9521 14.9593 15.5957 14.6023C15.2392 14.2453 14.7558 14.0441 14.2513 14.043Z" fill="black" />
                        <path d="M34.0003 16.4946H32.5048C32.3598 16.4946 32.2207 16.4369 32.1181 16.3344C32.0155 16.2318 31.9579 16.0927 31.9579 15.9477C31.9579 15.8026 32.0155 15.6635 32.1181 15.561C32.2207 15.4584 32.3598 15.4008 32.5048 15.4008H33.8457V12.5009C33.8454 12.1088 33.745 11.7233 33.5541 11.3809L30.5936 6.07331C30.5684 6.02801 30.5314 5.99028 30.4867 5.964C30.442 5.93773 30.391 5.92386 30.3392 5.92383H26.3047V15.403H27.607C27.752 15.403 27.8911 15.4606 27.9937 15.5632C28.0962 15.6657 28.1539 15.8048 28.1539 15.9499C28.1539 16.0949 28.0962 16.234 27.9937 16.3366C27.8911 16.4391 27.752 16.4967 27.607 16.4967H25.7578C25.6128 16.4967 25.4737 16.4391 25.3711 16.3366C25.2686 16.234 25.2109 16.0949 25.2109 15.9499V5.37695C25.2109 5.23191 25.2686 5.09281 25.3711 4.99025C25.4737 4.88769 25.6128 4.83008 25.7578 4.83008H30.3392C30.5859 4.82996 30.8282 4.89572 31.041 5.02058C31.2537 5.14544 31.4293 5.32485 31.5496 5.54029L34.5093 10.8486C34.7907 11.3539 34.9385 11.9226 34.9388 12.5009V15.5561C34.9384 15.8049 34.8394 16.0434 34.6635 16.2193C34.4876 16.3952 34.2491 16.4942 34.0003 16.4946ZM11.8059 16.4946H6.5625C6.41746 16.4946 6.27836 16.4369 6.1758 16.3344C6.07324 16.2318 6.01562 16.0927 6.01562 15.9477V11.7418C6.01562 11.5968 6.07324 11.4577 6.1758 11.3551C6.27836 11.2526 6.41746 11.195 6.5625 11.195C6.70754 11.195 6.84664 11.2526 6.9492 11.3551C7.05176 11.4577 7.10938 11.5968 7.10938 11.7418V15.4008H11.8059C11.951 15.4008 12.0901 15.4584 12.1926 15.561C12.2952 15.6635 12.3528 15.8026 12.3528 15.9477C12.3528 16.0927 12.2952 16.2318 12.1926 16.3344C12.0901 16.4369 11.951 16.4946 11.8059 16.4946ZM6.5625 9.80154C6.41746 9.80154 6.27836 9.74392 6.1758 9.64136C6.07324 9.5388 6.01563 9.3997 6.01562 9.25466V5.58258C6.01562 5.43754 6.07324 5.29844 6.1758 5.19588C6.27836 5.09332 6.41746 5.0357 6.5625 5.0357C6.70754 5.0357 6.84664 5.09332 6.9492 5.19588C7.05176 5.29844 7.10938 5.43754 7.10938 5.58258V9.25685C7.1088 9.40151 7.05092 9.54005 6.94843 9.64213C6.84593 9.74422 6.70716 9.80154 6.5625 9.80154Z" fill="black" />
                        <path d="M25.7555 16.4945H16.7015C16.5564 16.4945 16.4173 16.4369 16.3148 16.3343C16.2122 16.2317 16.1546 16.0926 16.1546 15.9476C16.1546 15.8026 16.2122 15.6635 16.3148 15.5609C16.4173 15.4583 16.5564 15.4007 16.7015 15.4007H25.2086V1.09375H7.10708V3.34615C7.10708 3.49119 7.04947 3.63029 6.94691 3.73284C6.84435 3.8354 6.70525 3.89302 6.56021 3.89302C6.41517 3.89302 6.27607 3.8354 6.17351 3.73284C6.07095 3.63029 6.01333 3.49119 6.01333 3.34615V0.993125C6.01372 0.729724 6.11858 0.477233 6.3049 0.291048C6.49122 0.104864 6.74379 0.000192826 7.00719 0H25.3093C25.5725 0.000385751 25.8249 0.105142 26.0111 0.291305C26.1973 0.477469 26.302 0.72985 26.3024 0.993125V15.9476C26.3024 16.0926 26.2448 16.2317 26.1422 16.3343C26.0397 16.4369 25.9006 16.4945 25.7555 16.4945ZM8.72219 12.2886H1.78125C1.63621 12.2886 1.49711 12.231 1.39455 12.1285C1.29199 12.0259 1.23438 11.8868 1.23438 11.7418C1.23438 11.5967 1.29199 11.4576 1.39455 11.3551C1.49711 11.2525 1.63621 11.1949 1.78125 11.1949H8.72219C8.86723 11.1949 9.00633 11.2525 9.10889 11.3551C9.21145 11.4576 9.26906 11.5967 9.26906 11.7418C9.26906 11.8868 9.21145 12.0259 9.10889 12.1285C9.00633 12.231 8.86723 12.2886 8.72219 12.2886Z" fill="black" />
                        <path d="M14.2532 9.80102H4.56771C4.42267 9.80102 4.28357 9.7434 4.18101 9.64084C4.07845 9.53828 4.02083 9.39918 4.02083 9.25414C4.02083 9.1091 4.07845 8.97 4.18101 8.86744C4.28357 8.76488 4.42267 8.70727 4.56771 8.70727H14.2532C14.3983 8.70727 14.5374 8.76488 14.6399 8.86744C14.7425 8.97 14.8001 9.1091 14.8001 9.25414C14.8001 9.39918 14.7425 9.53828 14.6399 9.64084C14.5374 9.7434 14.3983 9.80102 14.2532 9.80102ZM4.26656 6.91352H0.484375C0.339335 6.91352 0.200235 6.8559 0.097676 6.75334C-0.00488298 6.65078 -0.0625 6.51168 -0.0625 6.36664C-0.0625 6.2216 -0.00488298 6.0825 0.097676 5.97994C0.200235 5.87738 0.339335 5.81977 0.484375 5.81977H4.26656C4.4116 5.81977 4.5507 5.87738 4.65326 5.97994C4.75582 6.0825 4.81344 6.2216 4.81344 6.36664C4.81344 6.51168 4.75582 6.65078 4.65326 6.75334C4.5507 6.8559 4.4116 6.91352 4.26656 6.91352ZM10.331 3.89258H3.65479C3.50975 3.89258 3.37065 3.83496 3.26809 3.7324C3.16553 3.62984 3.10792 3.49074 3.10792 3.3457C3.10792 3.20066 3.16553 3.06156 3.26809 2.959C3.37065 2.85645 3.50975 2.79883 3.65479 2.79883H10.331C10.4761 2.79883 10.6152 2.85645 10.7177 2.959C10.8203 3.06156 10.8779 3.20066 10.8779 3.3457C10.8779 3.49074 10.8203 3.62984 10.7177 3.7324C10.6152 3.83496 10.4761 3.89258 10.331 3.89258Z" fill="black" />
                      </svg>
                      <p className="text-[14px] font-semibold text-[#1a1a1a]">{tc.transportType}</p>
                    </div>
                    <div className="flex flex-wrap gap-3">
                      {checkoutTransportOptions.map((opt) => (
                        <button
                          key={opt.id || opt.transport_type}
                          type="button"
                          onClick={() => setConfigTransport(opt.transport_type)}
                          className={`flex-1 min-w-[100px] p-4 rounded-[20px] text-[#000000] text-left transition-colors ${configTransport === opt.transport_type ? "border-[#053F31] border-t-2 border-t-[#053F31] bg-white" : "border-[#E8E8E8] bg-white hover:border-[#053F31]/50 hover:border-t-2 hover:border-t-[#053F31]"}`}
                        >
                          <p className="block font-medium border-b border-b-[#DDDDDD] pb-2 mb-[10px]">{opt.label}</p>
                          <span className="min-h-[45px] block font-thin text-[15px] leading-[150%]">
                            {opt.description || opt.delivery_window}
                          </span>
                          <span className="block font-medium text-[18px] leading-[150%]">
                            {opt.display_price
                              ? opt.display_price.startsWith("+")
                                ? opt.display_price
                                : `+${opt.display_price}`
                              : `+€${Number(opt.amount).toFixed(2)}`}
                          </span>
                        </button>
                      ))}
                    </div>
                  </div> */}

                  <div className="rounded-[20px] bg-[#DAE6DC]/70 border border-[#053F31]/10 p-4">
                    <div className="flex items-center gap-5 mb-2.5">
                      <svg xmlns="http://www.w3.org/2000/svg" width="35" height="19" viewBox="0 0 35 19" fill="none">
                        <path d="M30.0516 18.9459C29.4585 18.9463 28.8785 18.7708 28.3852 18.4416C27.8918 18.1124 27.5072 17.6443 27.2799 17.0965C27.0526 16.5486 26.9929 15.9457 27.1084 15.3639C27.2238 14.7822 27.5092 14.2477 27.9285 13.8282C28.3477 13.4086 28.8819 13.1229 29.4636 13.007C30.0453 12.8911 30.6483 12.9504 31.1963 13.1772C31.7443 13.4041 32.2127 13.7884 32.5422 14.2815C32.8718 14.7747 33.0477 15.3544 33.0477 15.9476C33.0473 16.7423 32.7316 17.5043 32.1699 18.0665C31.6081 18.6286 30.8463 18.9449 30.0516 18.9459ZM30.0516 14.043C29.6748 14.0425 29.3063 14.1539 28.9928 14.3629C28.6793 14.5719 28.4349 14.8692 28.2904 15.2172C28.1459 15.5652 28.1079 15.9482 28.1811 16.3178C28.2544 16.6874 28.4356 17.0269 28.7019 17.2935C28.9681 17.5601 29.3075 17.7417 29.677 17.8154C30.0465 17.889 30.4296 17.8515 30.7777 17.7074C31.1259 17.5633 31.4235 17.3192 31.6328 17.0059C31.8422 16.6927 31.954 16.3243 31.954 15.9476C31.9538 15.4429 31.7533 14.9589 31.3967 14.6018C31.04 14.2447 30.5563 14.0437 30.0516 14.043ZM14.2513 18.9459C13.6581 18.9465 13.0781 18.7711 12.5847 18.442C12.0912 18.1129 11.7065 17.6448 11.4791 17.097C11.2517 16.5492 11.1919 15.9462 11.3073 15.3644C11.4226 14.7826 11.708 14.2481 12.1272 13.8284C12.5464 13.4088 13.0806 13.123 13.6623 13.007C14.244 12.8911 14.847 12.9503 15.3951 13.1772C15.9431 13.404 16.4116 13.7883 16.7412 14.2815C17.0707 14.7746 17.2467 15.3544 17.2467 15.9476C17.2461 16.7421 16.9304 17.5039 16.3689 18.066C15.8073 18.6281 15.0458 18.9445 14.2513 18.9459ZM14.2513 14.043C13.8744 14.0424 13.5059 14.1536 13.1923 14.3625C12.8787 14.5715 12.6342 14.8687 12.4896 15.2167C12.345 15.5646 12.3068 15.9477 12.38 16.3173C12.4532 16.687 12.6343 17.0266 12.9006 17.2933C13.1668 17.5599 13.5062 17.7416 13.8757 17.8153C14.2452 17.889 14.6283 17.8515 14.9765 17.7074C15.3247 17.5634 15.6223 17.3193 15.8317 17.006C16.0411 16.6927 16.1529 16.3244 16.1529 15.9476C16.1525 15.443 15.9521 14.9593 15.5957 14.6023C15.2392 14.2453 14.7558 14.0441 14.2513 14.043Z" fill="black" />
                        <path d="M34.0003 16.4946H32.5048C32.3598 16.4946 32.2207 16.4369 32.1181 16.3344C32.0155 16.2318 31.9579 16.0927 31.9579 15.9477C31.9579 15.8026 32.0155 15.6635 32.1181 15.561C32.2207 15.4584 32.3598 15.4008 32.5048 15.4008H33.8457V12.5009C33.8454 12.1088 33.745 11.7233 33.5541 11.3809L30.5936 6.07331C30.5684 6.02801 30.5314 5.99028 30.4867 5.964C30.442 5.93773 30.391 5.92386 30.3392 5.92383H26.3047V15.403H27.607C27.752 15.403 27.8911 15.4606 27.9937 15.5632C28.0962 15.6657 28.1539 15.8048 28.1539 15.9499C28.1539 16.0949 28.0962 16.234 27.9937 16.3366C27.8911 16.4391 27.752 16.4967 27.607 16.4967H25.7578C25.6128 16.4967 25.4737 16.4391 25.3711 16.3366C25.2686 16.234 25.2109 16.0949 25.2109 15.9499V5.37695C25.2109 5.23191 25.2686 5.09281 25.3711 4.99025C25.4737 4.88769 25.6128 4.83008 25.7578 4.83008H30.3392C30.5859 4.82996 30.8282 4.89572 31.041 5.02058C31.2537 5.14544 31.4293 5.32485 31.5496 5.54029L34.5093 10.8486C34.7907 11.3539 34.9385 11.9226 34.9388 12.5009V15.5561C34.9384 15.8049 34.8394 16.0434 34.6635 16.2193C34.4876 16.3952 34.2491 16.4942 34.0003 16.4946ZM11.8059 16.4946H6.5625C6.41746 16.4946 6.27836 16.4369 6.1758 16.3344C6.07324 16.2318 6.01562 16.0927 6.01562 15.9477V11.7418C6.01562 11.5968 6.07324 11.4577 6.1758 11.3551C6.27836 11.2526 6.41746 11.195 6.5625 11.195C6.70754 11.195 6.84664 11.2526 6.9492 11.3551C7.05176 11.4577 7.10938 11.5968 7.10938 11.7418V15.4008H11.8059C11.951 15.4008 12.0901 15.4584 12.1926 15.561C12.2952 15.6635 12.3528 15.8026 12.3528 15.9477C12.3528 16.0927 12.2952 16.2318 12.1926 16.3344C12.0901 16.4369 11.951 16.4946 11.8059 16.4946ZM6.5625 9.80154C6.41746 9.80154 6.27836 9.74392 6.1758 9.64136C6.07324 9.5388 6.01563 9.3997 6.01562 9.25466V5.58258C6.01562 5.43754 6.07324 5.29844 6.1758 5.19588C6.27836 5.09332 6.41746 5.0357 6.5625 5.0357C6.70754 5.0357 6.84664 5.09332 6.9492 5.19588C7.05176 5.29844 7.10938 5.43754 7.10938 5.58258V9.25685C7.1088 9.40151 7.05092 9.54005 6.94843 9.64213C6.84593 9.74422 6.70716 9.80154 6.5625 9.80154Z" fill="black" />
                        <path d="M25.7555 16.4945H16.7015C16.5564 16.4945 16.4173 16.4369 16.3148 16.3343C16.2122 16.2317 16.1546 16.0926 16.1546 15.9476C16.1546 15.8026 16.2122 15.6635 16.3148 15.5609C16.4173 15.4583 16.5564 15.4007 16.7015 15.4007H25.2086V1.09375H7.10708V3.34615C7.10708 3.49119 7.04947 3.63029 6.94691 3.73284C6.84435 3.8354 6.70525 3.89302 6.56021 3.89302C6.41517 3.89302 6.27607 3.8354 6.17351 3.73284C6.07095 3.63029 6.01333 3.49119 6.01333 3.34615V0.993125C6.01372 0.729724 6.11858 0.477233 6.3049 0.291048C6.49122 0.104864 6.74379 0.000192826 7.00719 0H25.3093C25.5725 0.000385751 25.8249 0.105142 26.0111 0.291305C26.1973 0.477469 26.302 0.72985 26.3024 0.993125V15.9476C26.3024 16.0926 26.2448 16.2317 26.1422 16.3343C26.0397 16.4369 25.9006 16.4945 25.7555 16.4945ZM8.72219 12.2886H1.78125C1.63621 12.2886 1.49711 12.231 1.39455 12.1285C1.29199 12.0259 1.23438 11.8868 1.23438 11.7418C1.23438 11.5967 1.29199 11.4576 1.39455 11.3551C1.49711 11.2525 1.63621 11.1949 1.78125 11.1949H8.72219C8.86723 11.1949 9.00633 11.2525 9.10889 11.3551C9.21145 11.4576 9.26906 11.5967 9.26906 11.7418C9.26906 11.8868 9.21145 12.0259 9.10889 12.1285C9.00633 12.231 8.86723 12.2886 8.72219 12.2886Z" fill="black" />
                        <path d="M14.2532 9.80102H4.56771C4.42267 9.80102 4.28357 9.7434 4.18101 9.64084C4.07845 9.53828 4.02083 9.39918 4.02083 9.25414C4.02083 9.1091 4.07845 8.97 4.18101 8.86744C4.28357 8.76488 4.42267 8.70727 4.56771 8.70727H14.2532C14.3983 8.70727 14.5374 8.76488 14.6399 8.86744C14.7425 8.97 14.8001 9.1091 14.8001 9.25414C14.8001 9.39918 14.7425 9.53828 14.6399 9.64084C14.5374 9.7434 14.3983 9.80102 14.2532 9.80102ZM4.26656 6.91352H0.484375C0.339335 6.91352 0.200235 6.8559 0.097676 6.75334C-0.00488298 6.65078 -0.0625 6.51168 -0.0625 6.36664C-0.0625 6.2216 -0.00488298 6.0825 0.097676 5.97994C0.200235 5.87738 0.339335 5.81977 0.484375 5.81977H4.26656C4.4116 5.81977 4.5507 5.87738 4.65326 5.97994C4.75582 6.0825 4.81344 6.2216 4.81344 6.36664C4.81344 6.51168 4.75582 6.65078 4.65326 6.75334C4.5507 6.8559 4.4116 6.91352 4.26656 6.91352ZM10.331 3.89258H3.65479C3.50975 3.89258 3.37065 3.83496 3.26809 3.7324C3.16553 3.62984 3.10792 3.49074 3.10792 3.3457C3.10792 3.20066 3.16553 3.06156 3.26809 2.959C3.37065 2.85645 3.50975 2.79883 3.65479 2.79883H10.331C10.4761 2.79883 10.6152 2.85645 10.7177 2.959C10.8203 3.06156 10.8779 3.20066 10.8779 3.3457C10.8779 3.49074 10.8203 3.62984 10.7177 3.7324C10.6152 3.83496 10.4761 3.89258 10.331 3.89258Z" fill="black" />
                      </svg>
                      <p className="text-[14px] font-semibold text-[#1a1a1a]">{tc.truckType}</p>
                    </div>
                    <div className="relative">
                      <select
                        value={configTruckType}
                        onChange={(e) => {
                          const v = e.target.value;
                          setConfigTruckType(v);
                          if (v) setConfigTruckTypeError("");
                        }}
                        aria-invalid={!!configTruckTypeError}
                        className={`w-full h-[50px] rounded-[10px] border bg-white pl-4 pr-10 text-[16px] text-[#053F31]/70 focus:outline-none appearance-none ${configTruckTypeError ? "border-red-600 focus:border-red-600" : "border-[#053F31]/30 focus:border-[#053F31]/30"}`}
                      >
                        <option value="">{tc.selectTruckType}</option>
                        {checkoutTruckTypeOptions.map((opt) => (
                          <option key={opt.value} value={opt.value}>
                            {opt.label}
                          </option>
                        ))}
                      </select>
                      <span className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-[#053F31]">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6" /></svg>
                      </span>
                    </div>
                    {configTruckTypeError ? (
                      <p className="mt-2 text-[13px] text-red-600" role="alert">
                        {configTruckTypeError}
                      </p>
                    ) : null}
                  </div>

                  {(() => {
                    const basePrice = parseFloat(display.price) * configQuantity;
                    const total = basePrice;
                    return (
                      <div className="rounded-[20px] bg-[#DAE6DC]/70 border border-[#053F31]/10 p-4">
                        <div className="flex justify-between text-[#000000] pb-[10px] mb-[10px] border-b border-[#DDDDDD]">
                          <span className="font-light">{`${tc.basePriceLabel} (${configQuantity} ${display.priceUnit.trim() || tc.tonnesWord})`}</span>
                          <p className="font-medium">€{basePrice.toFixed(2)}</p>
                        </div>
                        {/*
                        const selectedTransport = checkoutTransportOptions.find((o) => o.transport_type === configTransport);
                        const transportCost = selectedTransport?.amount ?? 0;
                        const total = basePrice + transportCost;
                        <div className="flex justify-between text-[#000000] pb-[10px] mb-[10px] border-b border-[#DDDDDD]">
                          <span className="font-light">{tc.transportCost}</span>
                          <p className="font-medium">€{transportCost.toFixed(3)}</p>
                        </div>
                        */}
                        <div className="flex justify-between text-[#000000]">
                          <span className="font-medium">{tc.total}</span>
                          <p className="font-medium">€{total.toFixed(2)}</p>
                        </div>
                      </div>
                    );
                  })()}

                  {quoteRequestSubmitted ? (
                    <div className="rounded-[20px] bg-[#DAE6DC]/70 border border-[#053F31]/10 p-4 space-y-3 text-[14px] leading-[150%] text-[#000000]">
                      <p className="font-light">{tc.quoteAvailabilityNote}</p>
                      <p className="font-semibold">{tc.quoteSubmittedMessage}</p>
                    </div>
                  ) : null}

                  <div className="flex gap-5 pt-[14px]">
                    <button type="button" onClick={() => setConfigureModalOpen(false)} className="flex-1 h-[50px] cursor-pointer rounded-full bg-[#053F31] text-white font-semibold hover:bg-[#053F31]/90 transition-colors">
                      {tc.cancel}
                    </button>
                    <button
                      type="button"
                      onClick={() => void handleProceedToCheckout()}
                      disabled={quoteRequestSending || quoteRequestSubmitted}
                      className="flex-1 h-[50px] cursor-pointer rounded-full border-2 border-[#053F31] bg-white text-[#053F31] font-semibold hover:bg-[#053F31]/5 transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
                    >
                      {quoteRequestSending
                        ? uiLocale === "es-ES"
                          ? "Enviando..."
                          : "Sending..."
                        : tc.proceedToCheckout}
                    </button>
                  </div>
                </div>
              </div>
            </div>

          </div>

        </div>,
        document.body,
      )}
    </div>
  );
}
