<?php
/**
 * Accordion Component
 * Collapsible content sections
 * 
 * Attributes:
 * - items: JSON array with title and content
 * - allow_multiple: Allow multiple items open (default: false)
 */

$items = $items ?? [];
if (is_string($items)) {
    $items = json_decode(html_entity_decode($items), true) ?: [];
}

if (empty($items)) {
    $items = [
        ['title' => 'Section 1', 'content' => 'Content for section 1. You can add any HTML here.'],
        ['title' => 'Section 2', 'content' => 'Content for section 2. This can include lists, images, etc.'],
        ['title' => 'Section 3', 'content' => 'Content for section 3. Make it as detailed as needed.']
    ];
}

$allow_multiple = $allow_multiple ?? false;
$accordionId = 'accordion-' . uniqid();
?>
<section class="section">
    <div class="container">
        <div class="accordion" id="<?= $accordionId ?>" data-allow-multiple="<?= $allow_multiple ? 'true' : 'false' ?>">
            <?php foreach ($items as $i => $item): ?>
                <div class="accordion-item card mb-2">
                    <header class="card-header accordion-header" style="cursor: pointer;">
                        <p class="card-header-title"><?= htmlspecialchars($item['title'] ?? '') ?></p>
                        <a class="card-header-icon">
                            <span class="icon accordion-icon">
                                <i class="fas fa-angle-down"></i>
                            </span>
                        </a>
                    </header>
                    <div class="accordion-content card-content" style="display: none;">
                        <?= $item['content'] ?? '' ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</section>

<style>
    .accordion-icon {
        transition: transform 0.3s;
    }

    .accordion-item.is-active .accordion-icon {
        transform: rotate(180deg);
    }
</style>

<script>
    document.querySelectorAll('#<?= $accordionId ?> .accordion-header').forEach(header => {
        header.addEventListener('click', function () {
            const item = this.closest('.accordion-item');
            const content = item.querySelector('.accordion-content');
            const accordion = this.closest('.accordion');
            const allowMultiple = accordion.dataset.allowMultiple === 'true';

            if (!allowMultiple) {
                accordion.querySelectorAll('.accordion-item').forEach(i => {
                    if (i !== item) {
                        i.classList.remove('is-active');
                        i.querySelector('.accordion-content').style.display = 'none';
                    }
                });
            }

            item.classList.toggle('is-active');
            content.style.display = item.classList.contains('is-active') ? 'block' : 'none';
        });
    });
</script>