<?php

declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Magento\Catalog\Block\Category\View;
use Magento\Catalog\ViewModel\Category\Output as CategoryOutput;
use Magento\Framework\Escaper;
use Magento\Store\Model\StoreManagerInterface;

/** @var View $block */
/** @var Escaper $escaper */
/** @var ViewModelRegistry $viewModels */
/** @var StoreManagerInterface $storeManager */

/** @var CategoryOutput $categoryOutput */
$categoryOutput = $viewModels->require(CategoryOutput::class);

$currentCategory = $block->getCurrentCategory();

// Initialize variables with default empty values
$tab1Title = $tab1Content = $tab2Title = $tab2Content = $tab3Title = $tab3Content = $imageFile = '';

// Only try to get data if the category exists
if ($currentCategory) {
    $tab1Title = $currentCategory->getData('first_tab');
    $tab1Content = $currentCategory->getData('first_content');
    $tab2Title = $currentCategory->getData('second_tab');
    $tab2Content = $currentCategory->getData('second_content');
    $tab3Title = $currentCategory->getData('third_tab');
    $tab3Content = $currentCategory->getData('third_content');
    $imageFile = $currentCategory->getData('tab_image');
}

// Build full image URL if image is present
$fullImageUrl = '';
if ($imageFile) {
    try {
        $storeManager = \Magento\Framework\App\ObjectManager::getInstance()->get(StoreManagerInterface::class);
        $mediaUrl = $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    } catch (\Exception $e) {
        $mediaUrl = '/media/';
    }

    // Strip accidental 'media/' prefix if present
    $imageFile = preg_replace('#^media/#', '', ltrim($imageFile, '/'));

    // Ensure 'catalog/category/' is prepended
    if (strpos($imageFile, 'catalog/category/') !== 0) {
        $imageFile = 'catalog/category/' . $imageFile;
    }

    $fullImageUrl = $mediaUrl . ltrim($imageFile, '/');
}

?>

<?php if ($tab1Content || $tab2Content || $tab3Content): ?>
    <div class="2xl:container 3xl:max-w-screen-2xl py-1 px-3">
        <!-- Tab + Image Layout for Desktop -->
        <div class=" hidden md:flex justify-between gap-8 items-start pb-4">
            <!-- Left: Tab Content -->
            <div x-data="{ activeTab: 'tab1' }"
                 class="w-3/4"
                 :class="{ 'mx-auto text-center': <?= json_encode(empty($fullImageUrl)) ?> }">

                <!-- Tab Titles -->
                <div class="flex space-x-4 mb-4 lg:w-1/2 justify-around"
                     :class="{ 'mx-auto': <?= json_encode(empty($fullImageUrl)) ?> }">

                    <?php foreach (['tab1' => $tab1Title, 'tab2' => $tab2Title, 'tab3' => $tab3Title] as $tab => $title): ?>
                        <?php if ($title): ?>
                            <button @click="activeTab = '<?= $tab ?>'"
                                    :class="{ 'border-b-2 border-primary-darker text-primary-darker': activeTab === '<?= $tab ?>' }"
                                    class="mr-5 py-2 text-lg font-medium">
                                <?= $escaper->escapeHtml($title) ?>
                            </button>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>

                <!-- Tab Content -->
                <?php foreach (['tab1' => $tab1Content, 'tab2' => $tab2Content, 'tab3' => $tab3Content] as $tab => $content): ?>
                    <?php if ($content): ?>
                        <div x-show="activeTab === '<?= $tab ?>'"
                             x-data="{
                         showMore: false,
                         expandable: false,
                         init() {
                             this.$nextTick(() => {
                                 const container = this.$refs.content;
                                 const fullHeight = container.scrollHeight;
                                 const maxHeight = 120;
                                 if (fullHeight > maxHeight) {
                                     this.expandable = true;
                                 }
                             });
                         }
                     }"
                             class="tab-content text-base">

                            <div x-ref="content"
                                 :style="!showMore ? 'max-height: 120px; overflow: hidden;' : 'max-height: none;'"
                                 class="transition-all duration-300 ease-in-out">
                                <p class="leading-6 text-base font-inter">
                                    <?= ($content)?>
                                </p>
                            </div>

                            <!-- Toggle -->
                            <div x-show="expandable" class="mt-2">
                                <a href="#" @click.prevent="showMore = !showMore"
                                   class="text-red-500 underline text-base capitalize">
                                    <span x-show="!showMore">Read More</span>
                                    <span x-show="showMore" x-cloak>Show Less</span>
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>

            <!-- Right: Image -->
            <?php if (!empty($fullImageUrl)): ?>
                <div class="w-1/4">
                    <img src="<?= $fullImageUrl ?>" alt="Category Tab Image"
                         class="shadow-md w-full h-auto object-cover">
                </div>
            <?php endif; ?>
        </div>


        <!-- Accordion for Mobile -->
        <div class="md:hidden mb-4">
            <!-- Right: Image -->
            <?php if (!empty($fullImageUrl)): ?>
                <div>
                    <img src="<?= $fullImageUrl ?>" alt="Category Tab Image"
                         class="shadow-md w-full h-auto object-cover">
                </div>
            <?php endif; ?>
        </div>
        <div x-data="{ activeTab: null }" class="category-tab mobile md:hidden">
            <div class="space-y-2 ">
                <?php foreach (
                    [
                        'tab1' => ['title' => $tab1Title, 'content' => $tab1Content],
                        'tab2' => ['title' => $tab2Title, 'content' => $tab2Content],
                        'tab3' => ['title' => $tab3Title, 'content' => $tab3Content]
                    ] as $tab => $data
                ): ?>
                    <?php if ($data['content']): ?>
                        <div>
                            <button @click="activeTab = (activeTab === '<?= $tab ?>' ? null : '<?= $tab ?>')"
                                    :class="{ 'text-primary-darker': activeTab === '<?= $tab ?>' }"
                                    class="flex justify-between items-center w-full text-sm font-medium">
                                <span>
                                    <?= $escaper->escapeHtml($data['title']) ?>
                                </span>

                                <span x-text="activeTab === '<?= $tab ?>' ? '–' : '+'"
                                      class="text-base font-semibold click-btn">
                                </span>
                            </button>
                            <div x-show="activeTab === '<?= $tab ?>'" class="tab-content text-sm py-2" x-cloak>
                                <div x-data="{ showMore: false }">
                                    <div x-bind:class="{'max-h-20 overflow-hidden ': !showMore}">
                                        <?= /* @noEscape */
                                        $data['content'] ?>
                                    </div>
                                    <span x-show="!showMore" class="read block">
                                <a href="#" @click.prevent="showMore = true"
                                   class="underline text-red-500 capitalize text-sm">
                                    Read More
                                </a>
                            </span>
                                    <span x-show="showMore" class="read block">
                                <a href="#" @click.prevent="showMore = false"
                                   class="underline text-red-500 capitalize text-sm">
                                    Show Less
                                </a>
                            </span>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>

    </div>

<?php endif; ?>
