<?php
declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\CurrentProduct;
use Magento\Framework\Escaper;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;

/** @var Template $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */

$currentProduct = $viewModels->require(CurrentProduct::class);
$product = $block->hasData('product') ? $block->getData('product') : $currentProduct->get();

/** Load Magento Media URL */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->get(StoreManagerInterface::class);
$mediaBaseUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

/** Get attribute content */
$rawContent = $product->getData('dimensions');

if (!is_string($rawContent) || trim($rawContent) === '') {
    return;
}

if ($rawContent) {
    // Extract accordion block
    $accordionPattern = '/<div class="accordion_container">.*<\/div>\s*<\/div>/is';
    preg_match($accordionPattern, $rawContent, $accordionMatches);
    $accordionHtml = $accordionMatches[0] ?? '';

    // Remove accordion part from raw
    $contentWithoutAccordion = str_replace($accordionHtml, '', $rawContent);

    // Extract media image paths
    preg_match_all('/\/media\/catalog\/product\/[^"<)]+(?:\s[^"<)]+)*/i', $contentWithoutAccordion, $imgMatches);
    $imageListRaw = $imgMatches[0] ?? [];
    $imageList = [];

    foreach (preg_split('/\r\n|\r|\n/', $contentWithoutAccordion) as $line) {
        $line = trim($line);
        if (str_starts_with($line, '/media/catalog/product/')) {
            $imageList[] = $line;
        }
    }
    // Extract table blocks (inside <div><table>...</table></div>)
    preg_match_all('/<div[^>]*>.*?<table[^>]*>.*?<\/table>.*?<\/div>/is', $contentWithoutAccordion, $tableMatches);
    $tableHtml = implode("\n", $tableMatches[0] ?? []);

    // Clean content: remove images and accordion
    $cleanContent = str_replace($imageList, '', $contentWithoutAccordion);

    // Extract all <ul>...</ul> blocks
    preg_match_all('/<ul[^>]*>(.*?)<\/ul>/is', $contentWithoutAccordion, $ulMatches);
    $cleanContent = implode("\n", $ulMatches[0]);

    // Improve bullet styling
    $cleanContent = str_replace('<ul class="list-disc">', '<ul class="list-disc marker:text-black pl-5">', $cleanContent);
    ?>

    <!-- ✅ Render cleaned HTML content (bullets) -->
    <div class="mb-6 prose max-w-none">
        <?= /* @noEscape */ $cleanContent ?>
    </div>

    <!-- ✅ Render extracted images -->
    <?php if (!empty($imageList)): ?>
        <?php $imageCount = count($imageList); ?>
        <div class="my-6">
            <?php if ($imageCount === 1): ?>
                <?php
                $imgPath = $imageList[0];
                $src = $mediaBaseUrl . ltrim(str_replace('/media/', '', $imgPath), '/');
                $altText = ucwords(str_replace(['-', '_'], ' ', pathinfo(basename($imgPath), PATHINFO_FILENAME))) . ' Dimensions';
                ?>
                <div class="flex justify-center px-4">
                    <div class="w-full sm:w-auto max-w-xl px-2 mb-4">
                        <img src="<?= $escaper->escapeUrl($src) ?>"
                             alt="<?= $escaper->escapeHtmlAttr($altText) ?>"
                             class="w-full h-auto object-contain rounded shadow"
                             loading="lazy" />
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($imageList as $index => $imgPath): ?>
                    <?php
                    $src = $mediaBaseUrl . ltrim(str_replace('/media/', '', $imgPath), '/');
                    $altText = ucwords(str_replace(['-', '_'], ' ', pathinfo(basename($imgPath), PATHINFO_FILENAME))) . ' Dimensions';

                    // Open a new row every two images
                    if ($index % 2 === 0): ?>
                        <div class="flex flex-wrap -mx-2">
                    <?php endif; ?>

                    <div class="w-full sm:w-1/2 px-2 mb-4">
                        <img src="<?= $escaper->escapeUrl($src) ?>"
                             alt="<?= $escaper->escapeHtmlAttr($altText) ?>"
                             class="w-full h-auto object-contain rounded shadow"
                             loading="lazy" />
                    </div>

                    <?php
                    // Close the row after 2nd image or at the last image
                    if ($index % 2 === 1 || $index === $imageCount - 1): ?>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>



    <!-- ✅ Render extracted table HTML -->
    <?php if (!empty($tableHtml)): ?>
        <div class="overflow-x-auto">
            <?= /* @noEscape */ $tableHtml ?>
        </div>
    <?php endif; ?>

    <!-- ✅ Render Accordion with Alpine.js -->
    <?php if ($accordionHtml): ?>
        <div class="mt-6 space-y-2" x-data="{ active: null }">
            <?php
            preg_match_all('/<div class="accordion_head">(.*?)<\/div>\s*<div class="accordion_body"[^>]*>(.*?)<\/div>/is', $accordionHtml, $sections, PREG_SET_ORDER);
            $index = 0;
            foreach ($sections as $section):
                $head = trim($section[1]);
                $body = trim($section[2]);
                ?>
                <div class="border border-gray-300 rounded">
                    <button @click="active === <?= $index ?> ? active = null : active = <?= $index ?>"
                            class="w-full text-left px-4 py-2 bg-gray-100 hover:bg-gray-200 font-semibold flex justify-between items-center">
                        <?= $escaper->escapeHtml($head) ?>
                        <span x-text="active === <?= $index ?> ? '-' : '+'"></span>
                    </button>
                    <div x-show="active === <?= $index ?>" x-transition class="px-4 py-3 bg-white border-t">
                        <?= /* @noEscape */ $body ?>
                    </div>
                </div>
                <?php $index++; endforeach; ?>
        </div>
    <?php endif; ?>
<?php } ?>

<style>
    .accordion_body {
        overflow: hidden;
        transition: max-height 0.3s ease-out;
    }
</style>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const heads = document.querySelectorAll(".accordion_head");

        heads.forEach((head) => {
            head.addEventListener("click", function () {
                document.querySelectorAll(".accordion_body").forEach(body => {
                    body.style.display = "none";
                });

                document.querySelectorAll(".plusminus").forEach(pm => {
                    pm.textContent = "+";
                });

                const body = this.nextElementSibling;
                const symbol = this.querySelector(".plusminus");

                if (body.style.display === "none") {
                    body.style.display = "block";
                    symbol.textContent = "–";
                } else {
                    body.style.display = "none";
                    symbol.textContent = "+";
                }
            });
        });
    });
</script>
