<?php
/**
 * FAQ Section
 * Displays frequently asked questions in accordion layout
 */

$settings = $section['settings'] ?? [];

$subtitle = trim($settings['subtitle'] ?? '');
$items    = $settings['items'] ?? [];

// Normalize items
if (!is_array($items)) {
    return;
}

// Keep only valid items
$items = array_values(array_filter($items, function ($item) {
    return !empty($item['question']) && !empty($item['answer']);
}));

if (empty($items)) {
    return;
}

// Unique base ID
$baseFaqId = 'faq-' . ($section['id'] ?? uniqid());
?>

<section class="home-faq-section reveal">
    <div class="container">

<div class="section-head--styled">
    <h2>
        <?= __('homepage.faq.title', 'Frequently Asked Questions') ?>
    </h2>

    <?php if ($subtitle): ?>
        <div class="section-subtitle">
            <?= htmlspecialchars($subtitle, ENT_QUOTES, 'UTF-8') ?>
        </div>
    <?php endif; ?>
</div>


        <div class="faq-grid">

            <?php foreach ($items as $index => $item): ?>

                <?php
                $question = trim($item['question']);
                $answer   = trim($item['answer']);

                $faqId = $baseFaqId . '-' . $index;
                ?>

                <div class="faq-item">
                    <button type="button"
                            class="faq-question"
                            data-faq-target="<?= $faqId ?>">
<h3 class="faq-question-text">
    <?= htmlspecialchars($question, ENT_QUOTES, 'UTF-8') ?>
</h3>
                        <span class="faq-toggle">+</span>
                    </button>

                    <div class="faq-answer"
                         id="<?= $faqId ?>">
                        <div class="faq-answer-inner">
                            <?= nl2br(htmlspecialchars($answer, ENT_QUOTES, 'UTF-8')) ?>
                        </div>
                    </div>
                </div>

            <?php endforeach; ?>

        </div>

    </div>
</section>

<script>
(function () {

    const container = document.querySelector('.home-faq-section');
    if (!container) return;

    const questions = container.querySelectorAll('.faq-question');

    function closeAll() {
        container.querySelectorAll('.faq-item').forEach(item => {
            item.classList.remove('is-open');
        });
    }

    questions.forEach(btn => {
        btn.addEventListener('click', function () {

            const item = btn.closest('.faq-item');
            if (!item) return;

            const isOpen = item.classList.contains('is-open');

            closeAll();

            if (!isOpen) {
                item.classList.add('is-open');
            }
        });
    });

})();
</script>
