<?php
require_once __DIR__ . '/theme.php';
if (!defined('BASE_DIR')) define('BASE_DIR', __DIR__ . '/');

// ---- HERO IMAGE: FOUND BEFORE THE <head> IS WRITTEN ----
// This detection used to sit further down, inside <main>. That mattered more
// than it looks. The hero is applied as a CSS background-image, and the
// browser's preload scanner — which races ahead through the raw HTML starting
// fetches — cannot see background images at all. It only discovers one after
// the stylesheet has downloaded AND the element has been matched to the rule,
// several round trips later. The hero is the largest thing on the page, so
// that is the Largest Contentful Paint measurement being taken the slowest
// possible way.
//
// Resolving the path up here, before header.php writes <head>, lets header.php
// emit a <link rel="preload"> for it, which the scanner does see. The markup
// below is unchanged and still uses $hero_bg exactly as before.
$hero_bg = '';
foreach (['jpg','jpeg','png','webp'] as $_e) {
    $_f = BASE_DIR . 'images/site/hero_1.' . $_e;
    if (file_exists($_f)) { $hero_bg = 'images/site/hero_1.' . $_e . '?v=' . filemtime($_f); break; }
}
$page_preload_image = $hero_bg;

// ---- HERO VIDEO: THE SAME TRICK, FOR THE SAME REASON ----
// Resolved up here rather than down in the markup so the decision is made
// once, before <head> is written. The film is optional: drop
// images/site/hero.mp4 (and optionally hero.webm, which is smaller) next to
// the hero still and the top panel becomes film. Delete the file and the
// page silently goes back to being the photograph it is today.
//
// The poster is that same hero still, so the first frame a visitor sees is
// identical whether the film loads or not — and on a metered connection, or
// for anyone who has asked for reduced motion, the still is all that loads.
// Two folders are searched, not one. The upload folder stages the media in a
// directory called images-site because a nested images/site cannot live
// inside it, and dragging that folder onto the server lands it at
// /images-site/ — which is exactly what happened, and cost an evening of me
// insisting the file had not been uploaded when it had. Looking in both
// costs one is_file() call and means the film plays either way.
$hero_video_sources = [];
foreach (["webm" => "video/webm", "mp4" => "video/mp4"] as $_ve => $_vt) {
    foreach (["images/site/", "images-site/"] as $_vdir) {
        $_vf = BASE_DIR . $_vdir . "hero." . $_ve;
        if (is_file($_vf)) {
            $hero_video_sources[] = [
                "src"  => $_vdir . "hero." . $_ve . "?v=" . filemtime($_vf),
                "type" => $_vt,
            ];
            break;
        }
    }
}
$hero_video_poster = $hero_bg;

require_once __DIR__ . '/header.php';
?>

    <main>
        <!-- OPEN RIGHT NOW -->
        <?php
        // ---- THE QUESTION EVERY VISITOR ACTUALLY HAS ----
        // The announcement bar prints the opening hours as a sentence, which
        // means a customer stood in a car park at ten past four has to read
        // it, work out what day it is and do the arithmetic. This does the
        // arithmetic for them.
        //
        // It is read from the same hours in stores.json that the admin edits,
        // so it cannot drift out of step with the sign on the door — and it is
        // right on a Monday, when two of the three are shut.
        $_now      = time();
        $_dow      = strtolower(date('D', $_now));
        $_dowmap   = ['mon'=>'mon','tue'=>'tue','wed'=>'wed','thu'=>'thu','fri'=>'fri','sat'=>'sat','sun'=>'sun'];
        $_today    = $_dowmap[$_dow] ?? 'mon';
        $_mins     = (int)date('G', $_now) * 60 + (int)date('i', $_now);
        $_daynames = ['mon'=>'Monday','tue'=>'Tuesday','wed'=>'Wednesday','thu'=>'Thursday','fri'=>'Friday','sat'=>'Saturday','sun'=>'Sunday'];
        $_order    = ['mon','tue','wed','thu','fri','sat','sun'];

        $_hhmm = function ($t) {
            $p = explode(':', (string)$t); $h = (int)($p[0] ?? 0); $m = $p[1] ?? '00';
            $ap = $h >= 12 ? 'pm' : 'am'; $hh = $h % 12; if ($hh === 0) $hh = 12;
            return $hh . ($m === '00' ? '' : ':' . $m) . $ap;
        };
        $_tomins = function ($t) { $p = explode(':', (string)$t); return (int)($p[0] ?? 0) * 60 + (int)($p[1] ?? 0); };

        // ---- WHICH LIST OF SHOPS ----
        // There are two, and they disagree. settings.json['stores'] holds the
        // trading names — "Squires High Seat & Recliner Centre" — while
        // stores.json holds the towns, the addresses and the phone numbers.
        //
        // A customer navigates by town: they say they will pop to the Skegness
        // one. It is also what the stock says, so "On the floor at Skegness"
        // and this strip name the same place. stores.json wins, and
        // stores_list() stays as the fallback for a shop that has not got one.
        $_stores_src = json_decode((string)@file_get_contents(BASE_DIR . 'stores.json'), true);
        if (!is_array($_stores_src) || !$_stores_src) $_stores_src = stores_list();

        $_shops = [];
        // $_store, not $_st: header.php puts this month's sale theme in $_st and
        // the sale banner further down still reads it. A store record has a
        // 'name' too, so borrowing the variable made the banner announce
        // "Hogsthorpe" as the sale.
        foreach ($_stores_src as $_store) {
            if (!is_array($_store)) continue;
            $_h = $_store['hours'] ?? [];
            if (!is_array($_h)) continue;
            $_day = $_h[$_today] ?? null;
            $_open = false; $_text = '';
            if (is_array($_day) && empty($_day['closed']) && !empty($_day['open'])) {
                $o = $_tomins($_day['open']); $c = $_tomins($_day['close'] ?? '00:00');
                if ($_mins >= $o && $_mins < $c) { $_open = true;  $_text = 'Open until ' . $_hhmm($_day['close']); }
                elseif ($_mins < $o)             { $_open = false; $_text = 'Opens at ' . $_hhmm($_day['open']); }
            }
            if ($_text === '') {
                // Walk forward for the next day it is actually open, so a
                // Sunday afternoon reads "Opens Tuesday 10am" and not "Closed".
                $i = array_search($_today, $_order, true);
                for ($k = 1; $k <= 7; $k++) {
                    $nd = $_order[($i + $k) % 7];
                    $ndh = $_h[$nd] ?? null;
                    if (is_array($ndh) && empty($ndh['closed']) && !empty($ndh['open'])) {
                        $_text = 'Opens ' . ($k === 1 ? 'tomorrow' : $_daynames[$nd]) . ' ' . $_hhmm($ndh['open']);
                        break;
                    }
                }
            }
            if ($_text === '') $_text = 'Closed';
            $_shops[] = ['name' => (string)($_store['name'] ?? ''), 'open' => $_open, 'text' => $_text];
        }
        $_open_count = count(array_filter($_shops, fn($x) => $x['open']));
        ?>
        <?php
        // Worked out before the hero rather than after it: the hero prints the
        // three shops in its own foot, and the band further down the classic
        // layout reuses the same array.
        ?>
        <!-- HERO -->
        <?php
        $_hero_layout   = tv('hero_layout', 'overlay-left');
        $_hero_eyebrow  = tv('hero_eyebrow', 'Beautiful Home Interiors');
        $_hero_heading  = tv('hero_heading', "Your Home,\nBeautifully\nFurnished.");
        $_hero_sub      = tv('hero_subheading', "Your local furniture & flooring destination. Quality you can feel, service you'll never forget.");
        $_hero_btn_text  = tv('hero_btn_text', 'Explore Our Range');
        $_hero_btn_url   = tv('hero_btn_url', '#categories');
        $_hero_btn2_text = tv('hero_btn2_text', 'Visit Our Showroom');
        $_hero_btn2_url  = tv('hero_btn2_url', '#find-us');
        $_hero_bg_color   = tv('hero_bg', '#0F203C');
        $_hero_text_color = tv('hero_text_color', '#ffffff');
        // Heading may contain line breaks from a textarea-style edit — convert to <br>,
        // otherwise fall back to italicising the middle word the way the original hardcoded version did
        //
        // ---- EMPHASIS, WITHOUT LETTING HTML INTO A SETTING ----
        // The design leans on one italic word — "Furniture that lives in *your*
        // light" — and that has to survive being typed into an admin field. So
        // the field stays plain text and is escaped as it always was; asterisks
        // around a word become <em> AFTER escaping, which means a setting still
        // cannot inject markup.
        $_hero_heading_html = nl2br(htmlspecialchars($_hero_heading));
        $_hero_heading_html = preg_replace('/\*([^*\r\n]{1,60})\*/u', '<em>$1</em>', $_hero_heading_html);

        // ---- THE EYEBROW KNOWS WHAT MONTH IT IS ----
        // {season} expands to this month's sale theme, which the shop already
        // maintains twelve of. Written once, right all year — and in January it
        // says New Year Sale without anybody remembering to change it.
        if (strpos($_hero_eyebrow, '{season}') !== false) {
            $_m = (int)date('n');
            $_hero_eyebrow = str_replace(
                ['{season}', '{until}'],
                [trim((string)tv('sale_month_' . $_m . '_name', 'Seasonal Event')), date('j F', (int)strtotime('last day of this month'))],
                $_hero_eyebrow
            );
        }
        ?>
        <?php if (block_enabled('home','hero')): ?>
        <section class="hero layout-<?= htmlspecialchars($_hero_layout) ?>" aria-label="Welcome to <?= tv('site_name') ?>"
            style="<?= $_hero_layout==='split' ? '' : ($hero_bg ? "background-image:url('".htmlspecialchars($hero_bg)."')" : "background-color:".htmlspecialchars($_hero_bg_color)) ?>">
        <?php if ($_hero_layout === 'split'): ?>
            <div class="hero-split-inner">
                <div class="hero-split-text">
                    <div class="hero-content" style="color:<?= htmlspecialchars($_hero_text_color) ?>">
                        <?php if ($_hero_eyebrow): ?><div class="hero-eyebrow"><?= htmlspecialchars($_hero_eyebrow) ?></div><?php endif; ?>
                        <h2><?= $_hero_heading_html ?></h2>
                        <?php if ($_hero_sub): ?><p class="hero-sub"><?= htmlspecialchars($_hero_sub) ?></p><?php endif; ?>
                        <div class="hero-btns">
                            <a href="<?= htmlspecialchars($_hero_btn_url) ?>" class="btn-primary"><?= htmlspecialchars($_hero_btn_text) ?></a>
                            <?php if ($_hero_btn2_text): ?><a href="<?= htmlspecialchars($_hero_btn2_url) ?>" class="btn-ghost"><?= htmlspecialchars($_hero_btn2_text) ?></a><?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="hero-split-img" style="<?= $hero_bg ? "background-image:url('".htmlspecialchars($hero_bg)."')" : '' ?>"></div>
            </div>
        <?php else: ?>
            <?php if ($hero_video_sources): ?>
            <?php
            // ---- THE FILM BEHIND THE WORDS ----
            // No autoplay attribute and no src on the sources: both are set from
            // script below, and only once we know the visitor wants them. Until
            // then this element costs one poster image, which the browser was
            // already fetching as the hero background.
            //
            // The layer order is deliberate. The film sits at z-index 0; the
            // gradient overlay comes later in the DOM so it paints above without
            // needing a z-index of its own; .hero-content is at z-index 2. The
            // heading therefore stays readable over footage of any brightness.
            ?>
            <video id="heroVideo" class="hero-video" muted loop playsinline preload="none"
                   poster="<?= htmlspecialchars($hero_video_poster) ?>" aria-hidden="true" tabindex="-1">
                <?php foreach ($hero_video_sources as $_hv): ?>
                <source data-src="<?= htmlspecialchars($_hv['src']) ?>" type="<?= htmlspecialchars($_hv['type']) ?>">
                <?php endforeach; ?>
            </video>
            <?php
            // ---- THE SECOND COPY ----
            // A six-second clip whose last frame does not match its first has a
            // visible cut every six seconds. Playing it forwards then backwards
            // hid the cut but made the furniture visibly rewind, which was worse.
            //
            // So: two copies, offset. B starts from the beginning while A is
            // still running, they dissolve over a second, and then they swap.
            // The join never happens because there is never a join — at every
            // moment at least one of them is mid-clip.
            //
            // It costs a second decode of a 450KB file, which is cheap; the
            // browser fetches the file once and both elements share it.
            ?>
            <video id="heroVideoB" class="hero-video is-under" muted playsinline preload="none"
                   aria-hidden="true" tabindex="-1">
                <?php foreach ($hero_video_sources as $_hv): ?>
                <source data-src="<?= htmlspecialchars($_hv['src']) ?>" type="<?= htmlspecialchars($_hv['type']) ?>">
                <?php endforeach; ?>
            </video>
            <div class="hero-grain" aria-hidden="true"></div>
            <?php endif; ?>
            <?php
            // ---- THE LIGHT ----
            // The idea the whole design rests on: this is a room on a coast, and
            // the light in it is real. Cold and blue at dawn, neutral by noon,
            // deep amber at dusk, with a shaft that travels across the wall as
            // the sun does.
            //
            // Two layers, both painted in CSS, both independent of the film:
            // .hero-light is the shaft, .hero-grade is the colour of the hour
            // laid over whatever is behind it. So the hour reads over the
            // photograph today and grades the footage when it lands — which is
            // better, because it is grading a real room rather than a gradient.
            ?>
            <div class="hero-light" aria-hidden="true"><span></span><span class="b"></span></div>
            <div class="hero-grade" aria-hidden="true"></div>
            <div class="hero-overlay"></div>
            <div class="hero-content" style="color:<?= htmlspecialchars($_hero_text_color) ?>">
                <?php if ($_hero_eyebrow): ?><div class="hero-eyebrow"><?= htmlspecialchars($_hero_eyebrow) ?></div><?php endif; ?>
                <h2><?= $_hero_heading_html ?></h2>
                <?php if ($_hero_sub): ?><p class="hero-sub"><?= htmlspecialchars($_hero_sub) ?></p><?php endif; ?>
                <div class="hero-btns">
                    <a href="<?= htmlspecialchars($_hero_btn_url) ?>" class="btn-primary"><?= htmlspecialchars($_hero_btn_text) ?></a>
                    <?php if ($_hero_btn2_text): ?><a href="<?= htmlspecialchars($_hero_btn2_url) ?>" class="btn-ghost"><?= htmlspecialchars($_hero_btn2_text) ?></a><?php endif; ?>
                </div>
            </div>
            <?php
            // The showrooms belong in the hero, not in a band underneath it. A
            // visitor deciding whether to drive over should not have to scroll
            // to find out that two of the three are shut on a Monday.
            ?>
            <?php if (!empty($_shops)): ?>
            <div class="hero-foot">
                <div class="hero-shops">
                    <?php foreach ($_shops as $_hs): ?>
                    <div class="hero-shop <?= $_hs['open'] ? 'is-open' : '' ?>">
                        <b><?= htmlspecialchars($_hs['name']) ?></b>
                        <span><?= htmlspecialchars($_hs['text']) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="hero-lightctl">
                    <span class="hero-lightlbl">The light today</span>
                    <input type="range" min="6" max="21" step="1" value="12" id="heroLight" aria-label="Time of day">
                    <span class="hero-lighttime" id="heroLightTime">&mdash;</span>
                </div>
            </div>
            <?php endif; ?>
            <div class="hero-scroll" aria-hidden="true">
                <div class="scroll-line"></div>
                <span>Scroll</span>
            </div>
            <div class="hero-stats" aria-hidden="true">
                <div class="hero-stat"><span class="hero-stat-num"><?= htmlspecialchars(tv('stat_1_num', '')) ?></span><span class="hero-stat-label"><?= htmlspecialchars(tv('stat_1_label', 'Years of Experience')) ?></span></div>
                <div class="hero-stat"><span class="hero-stat-num"><?= htmlspecialchars(tv('stat_2_num', '')) ?></span><span class="hero-stat-label"><?= htmlspecialchars(tv('stat_2_label', 'Happy Customers')) ?></span></div>
                <div class="hero-stat"><span class="hero-stat-num"><?= htmlspecialchars(tv('stat_3_num', '100%')) ?></span><span class="hero-stat-label"><?= htmlspecialchars(tv('stat_3_label', 'Price Guarantee')) ?></span></div>
            </div>
        <?php endif; ?>
        </section>
        <?php endif; ?>

        <script>
        /* North Sea light: hue runs 205 (cold dawn) to 44 (noon) to 24 (dusk),
           the shaft strengthens through the middle of the day and travels
           across the wall. The slider is there because nobody visits at every
           hour — drag it and you see the whole day. It starts at the real one. */
        (function () {
            var root = document.documentElement;
            var slider = document.getElementById('heroLight');
            var out    = document.getElementById('heroLightTime');
            if (!out) return;

            function setLight(h) {
                var hue, a, k;
                if (h <= 12) { k = (h - 6) / 6;  hue = 205 - k * 161; a = 0.20 + k * 0.24; }
                else         { k = (h - 12) / 9; hue = 44 - k * 20;   a = 0.44 - k * 0.28; }
                root.style.setProperty('--hero-hue', hue.toFixed(0));
                root.style.setProperty('--hero-ray', a.toFixed(2));
                root.style.setProperty('--hero-sx', (6 + (h - 6) / 15 * 56).toFixed(1) + '%');
                var ap = h >= 12 ? 'pm' : 'am', hh = h % 12; if (hh === 0) hh = 12;
                out.textContent = hh + ap;
            }

            var now = new Date().getHours();
            var start = Math.min(21, Math.max(6, now));
            if (slider) {
                slider.value = start;
                slider.addEventListener('input', function () { setLight(+slider.value); });
            }
            setLight(start);
        })();
        </script>

        <?php if ($hero_video_sources): ?>
        <script>
        /* Start the film only when it can actually play, and only for somebody
           who wants it. A refused autoplay is not a failure — the poster simply
           stays, which is the design at rest rather than a black hole.

           Then keep it looping without a seam: A plays, and a second before it
           ends B starts from zero and the two dissolve. Whichever finishes goes
           back under, rewinds, and waits its turn. */
        (function () {
            var a = document.getElementById('heroVideo');
            var b = document.getElementById('heroVideoB');
            if (!a) return;

            var mq   = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)');
            var conn = navigator.connection || {};
            if ((mq && mq.matches) || conn.saveData) return;

            var FADE = 1.0;          // seconds of dissolve
            var players = b ? [a, b] : [a];

            players.forEach(function (v) {
                var srcs = v.querySelectorAll('source[data-src]');
                for (var i = 0; i < srcs.length; i++) srcs[i].src = srcs[i].getAttribute('data-src');
                v.loop = false;      // the cross-fade replaces looping
                v.load();
            });

            a.addEventListener('canplay', function () {
                var p = a.play();
                if (p && p.catch) p.catch(function () {});
                a.classList.add('is-playing');
                a.classList.remove('is-under');
            }, { once: true });

            if (!b) { a.loop = true; return; }   // one element: plain loop, as before

            var current = a, waiting = b, handing = false;

            function tick() {
                if (!handing && current.duration && current.currentTime > 0 &&
                    current.duration - current.currentTime <= FADE) {
                    handing = true;
                    waiting.currentTime = 0;
                    var p = waiting.play();
                    if (p && p.catch) p.catch(function () {});
                    waiting.classList.add('is-playing');
                    waiting.classList.remove('is-under');
                    current.classList.add('is-under');

                    var finished = current;
                    setTimeout(function () {
                        finished.pause();
                        finished.currentTime = 0;
                    }, FADE * 1000);

                    var t = current; current = waiting; waiting = t;
                    handing = false;
                }
                requestAnimationFrame(tick);
            }
            requestAnimationFrame(tick);
        })();
        </script>
        <?php endif; ?>

        <!-- USP STRIP -->
        <div class="usp-strip" aria-label="Our Promises">
            <div class="usp-inner">
                <div class="usp-item"><span class="usp-icon"></span> Free Local Delivery</div>
                <div class="usp-item"><span class="usp-icon">✓</span> Price Match Guarantee</div>
                <div class="usp-item"><span class="usp-icon"></span> 5 Year Guarantee on Selected Pieces</div>
                <div class="usp-item"><span class="usp-icon"></span> UK-Made Options</div>
                <div class="usp-item"><span class="usp-icon"></span> Expert Fitting</div>
            </div>
        </div>

        <?php if ($_shops): ?>
        <div class="sf-open-now" aria-label="Showroom opening right now">
            <div class="container sf-open-inner">
                <div class="sf-open-head <?= $_open_count ? 'is-open' : '' ?>">
                    <span class="sf-open-dot" aria-hidden="true"></span>
                    <?= $_open_count
                        ? (int)$_open_count . ' of ' . count($_shops) . ' showrooms open now'
                        : 'Closed now &mdash; here is when we open' ?>
                </div>
                <div class="sf-open-list">
                    <?php foreach ($_shops as $_s): ?>
                    <div class="sf-open-shop <?= $_s['open'] ? 'is-open' : '' ?>">
                        <b><?= htmlspecialchars($_s['name']) ?></b>
                        <span><?= htmlspecialchars($_s['text']) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php
        // ---- WHICH HOMEPAGE ----
        // 'squires' is the design; 'classic' is everything that was here
        // before, which is still below and still works. One setting switches
        // between them, so this is reversible without touching a file.
        $_home_layout = trim((string)tv('home_layout', 'classic'));
        ?>
        <?php if ($_home_layout === 'squires'): ?>
            <?php require BASE_DIR . 'home-squires.php'; ?>
        <?php else: ?>

        <!-- WELCOME -->
        <?php if (block_enabled('home','promo_text')): ?>
        <section id="welcome" class="welcome" aria-label="Welcome Message">
            <?php
            $_promo_eyebrow  = tv('promo_eyebrow', 'Our Story');
            $_promo_heading  = tv('promo_heading', "A Name You Can\nTrust");
            $_promo_body     = tv('promo_body', '');
            $_promo_btn_text = tv('promo_btn_text', 'Our full story');
            $_promo_btn_url  = tv('promo_btn_url', 'about.php');
            $_promo_bg       = tv('promo_bg', 'light');
            $_promo_lines = explode("\n", $_promo_heading);
            ?>
            <div class="container" style="<?= $_promo_bg==='dark'?'background:var(--navy)':($_promo_bg==='white'?'background:#fff':'') ?>">
                <div class="welcome-grid">
                    <div class="welcome-text reveal-left">
                        <div class="eyebrow"><?= htmlspecialchars($_promo_eyebrow) ?></div>
                        <h2 class="section-title"><?php
                            if (count($_promo_lines) > 1) {
                                $_promo_last = array_pop($_promo_lines);
                                echo nl2br(htmlspecialchars(implode("\n", $_promo_lines))) . '<br><em>' . htmlspecialchars($_promo_last) . '</em>';
                            } else {
                                echo htmlspecialchars($_promo_heading);
                            }
                        ?></h2>
                        <?php if ($_promo_body): ?>
                        <p><?= nl2br(htmlspecialchars($_promo_body)) ?></p>
                        <?php else: ?>
                        <p><?= tv('site_name') ?> has proudly served our local community — building a reputation rooted in trust, quality, and genuine customer care.</p>
                        <p>We believe choosing furniture is personal. That's why our showroom is relaxed and unhurried, and our team is always on hand with <strong>honest, friendly advice</strong> — never a hard sell.</p>
                        <p>From your first sofa to your forever flooring, we're here to make your home beautiful.</p>
                        <?php endif; ?>
                        <a href="<?= htmlspecialchars($_promo_btn_url) ?>"><?= htmlspecialchars($_promo_btn_text) ?> &rarr;</a>
                    </div>
                    <div class="welcome-visual reveal-right delay-2">
                        <?php
                        $_wbg = '';
                        foreach (['jpg','jpeg','png','webp'] as $_e) {
                            $_wf = BASE_DIR . 'images/site/welcome-home.' . $_e;
                            if (file_exists($_wf)) { $_wbg = 'images/site/welcome-home.' . $_e . '?v=' . filemtime($_wf); break; }
                        }
                        ?>
                        <?php if ($_wbg): ?><img class="welcome-img-frame" src="<?= htmlspecialchars($_wbg) ?>" alt="<?= htmlspecialchars(tv('site_name')) ?> showroom"<?= img_attrs($_wbg, true) ?> style="object-fit:cover"><?php else: ?><div class="welcome-img-frame"></div><?php endif; ?>
                        <div class="welcome-badge">
                            <span class="welcome-badge-num"><?= htmlspecialchars(tv('est_year', 'Est.')) ?></span>
                            <span class="welcome-badge-text"><?= htmlspecialchars(tv('site_name')) ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- CATEGORIES -->
        <?php if (block_enabled('home','categories')): ?>
        <section id="categories" class="categories" aria-label="Our Product Range">
            <?php
            $_cats_heading = tv('cats_heading', "Everything Your\nHome Deserves");
            $_cats_subtext = tv('cats_subtext', 'From statement sofas to stunning flooring — we stock quality home furnishings across every room.');
            $_cats_columns = tv('cats_columns', '3');
            ?>
            <div class="container">
                <div class="categories-header reveal">
                    <div class="eyebrow">Browse Our Range</div>
                    <h2 class="section-title"><?php
                        $_cats_lines = explode("\n", $_cats_heading);
                        if (count($_cats_lines) > 1) {
                            $_cats_last = array_pop($_cats_lines);
                            echo nl2br(htmlspecialchars(implode("\n", $_cats_lines))) . '<br><em>' . htmlspecialchars($_cats_last) . '</em>';
                        } else {
                            echo htmlspecialchars($_cats_heading);
                        }
                    ?></h2>
                    <p class="section-sub"><?= htmlspecialchars($_cats_subtext) ?></p>
                </div>
                <div class="cat-grid"<?= $_cats_columns !== '3' ? ' style="grid-template-columns:repeat('.intval($_cats_columns).',1fr)"' : '' ?>>
                    <a href="livingroom.php" class="cat-card reveal delay-1"<?= $_cats_columns !== '3' ? ' style="grid-column:auto"' : '' ?>>
                        <img class="cat-img" src="<?php echo htmlspecialchars("images/site/cat-sofas.jpg?v=".(@filemtime(BASE_DIR."images/site/cat-sofas.jpg")?: "1")); ?>" alt="Sofas &amp; Corner Suites"<?= img_attrs("images/site/cat-sofas.jpg") ?> style="width:100%;height:100%;object-fit:cover">
                        <div class="cat-overlay"></div>
                        <div class="cat-content">
                            <span class="cat-label">Most Popular</span>
                            <span class="cat-name">Sofas &amp; Corner Suites</span>
                            <span class="cat-desc">Recliners, corner sofas, sofa beds &amp; more</span>
                            <span class="cat-arrow">Shop Now</span>
                        </div>
                    </a>
                    <a href="flooring.php" class="cat-card reveal delay-2">
                        <img class="cat-img" src="<?php echo htmlspecialchars("images/site/cat-flooring.jpg?v=".(@filemtime(BASE_DIR."images/site/cat-flooring.jpg")?: "1")); ?>" alt="Flooring &amp; Carpets"<?= img_attrs("images/site/cat-flooring.jpg") ?> style="width:100%;height:100%;object-fit:cover">
                        <div class="cat-overlay"></div>
                        <div class="cat-content">
                            <span class="cat-label">Third Generation Specialists</span>
                            <span class="cat-name">Flooring &amp; Carpets</span>
                            <span class="cat-desc">Carpet, LVT, vinyl, rugs &amp; expert fitting</span>
                            <span class="cat-arrow">Shop Now</span>
                        </div>
                    </a>
                    <a href="bedroom.php" class="cat-card reveal delay-2">
                        <img class="cat-img" src="<?php echo htmlspecialchars("images/site/cat-beds.jpg?v=".(@filemtime(BASE_DIR."images/site/cat-beds.jpg")?: "1")); ?>" alt="Beds &amp; Mattresses"<?= img_attrs("images/site/cat-beds.jpg") ?> style="width:100%;height:100%;object-fit:cover">
                        <div class="cat-overlay"></div>
                        <div class="cat-content">
                            <span class="cat-label">Adjustable &amp; Custom Sizes</span>
                            <span class="cat-name">Beds &amp; Mattresses</span>
                            <span class="cat-desc">Including specialist caravan mattresses</span>
                            <span class="cat-arrow">Shop Now</span>
                        </div>
                    </a>
                    <a href="accent.php" class="cat-card reveal delay-3">
                        <img class="cat-img" src="<?php echo htmlspecialchars("images/site/cat-recliners.jpg?v=".(@filemtime(BASE_DIR."images/site/cat-recliners.jpg")?: "1")); ?>" alt="Riser Recliners"<?= img_attrs("images/site/cat-recliners.jpg") ?> style="width:100%;height:100%;object-fit:cover">
                        <div class="cat-overlay"></div>
                        <div class="cat-content">
                            <span class="cat-label">Lift &amp; Tilt Models</span>
                            <span class="cat-name">Riser Recliners</span>
                            <span class="cat-desc">Comfort chairs by leading UK manufacturers</span>
                            <span class="cat-arrow">Shop Now</span>
                        </div>
                    </a>
                    <a href="misc.php" class="cat-card reveal delay-4">
                        <img class="cat-img" src="<?php echo htmlspecialchars("images/site/cat-decor.jpg?v=".(@filemtime(BASE_DIR."images/site/cat-decor.jpg")?: "1")); ?>" alt="Home Decor"<?= img_attrs("images/site/cat-decor.jpg") ?> style="width:100%;height:100%;object-fit:cover">
                        <div class="cat-overlay"></div>
                        <div class="cat-content">
                            <span class="cat-label">Lighting, Mirrors &amp; More</span>
                            <span class="cat-name">Home Decor</span>
                            <span class="cat-desc">The finishing touches that make it home</span>
                            <span class="cat-arrow">Shop Now</span>
                        </div>
                    </a>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- FEATURED PRODUCTS -->
        <?php
        $all_products   = file_exists(BASE_DIR.'products.json') ? json_decode(file_get_contents(BASE_DIR.'products.json'), true) ?: [] : [];
        $featured_prods = array_values(array_filter($all_products, fn($p) =>
            ($p['active'] ?? true) && ($p['featured'] ?? false)
        ));
        // Limit to 4 on homepage
        $featured_prods = array_slice($featured_prods, 0, 4);
        if (!empty($featured_prods)):
        ?>
        <section class="featured-section" aria-label="Featured Products">
            <div class="container">
                <div class="section-header reveal" style="text-align:center;margin-bottom:48px">
                    <div class="eyebrow">Handpicked For You</div>
                    <h2 class="section-title">Featured <em>Products</em></h2>
                    <p class="section-sub" style="margin:0 auto">A selection of our most popular pieces — in store and ready to view.</p>
                </div>
                <div class="featured-grid">
                    <?php foreach ($featured_prods as $i => $fp):
                        $img     = $fp['image'] ?? '';
                        $cats    = $fp['categories'] ?? [];
                        $link    = 'stock-catalogue.php';
                        if ($cats) {
                            $cat = $cats[0];
                            if ($cat === 'sale')         $link = 'sale-catalogue.php';
                            elseif ($cat !== 'instock')  $link = strtok($cat,'-').'-catalogue.php';
                        }
                    ?>
                    <a href="<?= htmlspecialchars($link) ?>" class="featured-card reveal delay-<?= $i+1 ?>">
                        <div class="featured-card-img">
                            <?php if ($img): ?><img src="<?= htmlspecialchars($img) ?>" alt="<?= htmlspecialchars($fp['name']) ?>" style="width:100%;height:100%;object-fit:cover;position:absolute;inset:0"><?php endif; ?>
                            <?php if ($fp['fast_delivery'] ?? false): ?>
                            <div class="featured-badge badge-fast">Fast Delivery</div>
                            <?php elseif ($fp['clearance'] ?? false): ?>
                            <div class="featured-badge badge-clearance">Clearance</div>
                            <?php elseif ($fp['badge'] ?? ''): ?>
                            <div class="featured-badge badge-<?= htmlspecialchars($fp['badge_type']??'popular') ?>"><?= htmlspecialchars($fp['badge']) ?></div>
                            <?php endif; ?>
                        </div>
                        <div class="featured-card-body">
                            <span class="featured-card-cat"><?= htmlspecialchars($fp['category_label'] ?? '') ?></span>
                            <div class="featured-card-name"><?= htmlspecialchars($fp['name']) ?></div>
                            <?php if (prices_shown() && !($fp['enquiry_only'] ?? false) && ($fp['show_price'] ?? true) && !empty($fp['price'])): ?>
                            <div class="featured-card-price">
                                <?php if (!empty($fp['price_was'])): ?><span class="price-was"><?= htmlspecialchars($fp['price_was']) ?></span><?php endif; ?>
                                <span class="price-now"><?= htmlspecialchars($fp['price']) ?></span>
                            </div>
                            <?php elseif ($fp['enquiry_only'] ?? false): ?>
                            <div class="featured-card-price" style="font-size:13px;font-style:italic;color:var(--text-muted)">Price on enquiry</div>
                            <?php endif; ?>
                            <span class="featured-card-cta">View Product →</span>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
                <div style="text-align:center;margin-top:36px">
                    <a href="stock.php" class="btn-outline reveal">Browse All In Stock →</a>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- FLAMING JUNE BANNER -->
        <?php
        // Sale banner uses current month theme from $_st (set in header.php)
        $_sale_bg    = $_st['bg']    ?? '#c0460e';
        $_sale_emoji = $_st['emoji'] ?? '';
        $_sale_name  = $_st['name']  ?? 'Summer Sale';
        $_sale_eyebrow = $settings['june_eyebrow'] ?? 'Limited Time';
        $_sale_subtitle = $settings['june_subtitle'] ?? 'On Selected Furniture & Flooring';
        $_sale_detail = $settings['june_detail'] ?? ('Visit us in store — ' . (opening_hours_display() ?: 'see opening hours') . ', ' . main_store()['address']);
        $_sale_pct   = $settings['june_pct'] ?? '20%';
        $_sale_pct_label = $settings['june_pct_label'] ?? 'OFF';
        $_sale_items = $settings['june_items'] ?? "Sofas & Corner Suites
Recliners & Chairs
Beds & Mattresses
Flooring & Carpets";
        $_sale_btn   = $settings['june_btn_text'] ?? 'Shop the Sale';
        ?>
        <?php if (block_enabled('home','sale_banner')): ?>
        <section class="june-banner" aria-label="Sale Banner" style="background:<?= htmlspecialchars($_sale_bg) ?>">
            <div class="june-bg-text"><?= htmlspecialchars($_sale_name) ?></div>
            <div class="june-inner">
                <div class="june-left reveal-left">
                    <div class="june-eyebrow"><?= htmlspecialchars($_sale_emoji . ' ' . $_sale_eyebrow) ?></div>
                    <div class="june-title" style="color:#ffffff"><?= htmlspecialchars($_sale_name) ?></div>
                    <div class="june-subtitle"><?= htmlspecialchars($_sale_subtitle) ?></div>
                    <p class="june-detail"><?= htmlspecialchars($_sale_detail) ?></p>
                </div>
                <div class="june-center reveal delay-2">
                    <div class="june-pct-wrap" style="border-color:rgba(255,255,255,0.3)">
                        <span class="june-pct" style="color:#ffffff"><?= htmlspecialchars($_sale_pct) ?></span>
                        <span class="june-pct-off" style="color:rgba(255,255,255,0.7)"><?= htmlspecialchars($_sale_pct_label) ?></span>
                    </div>
                </div>
                <div class="june-right reveal-right delay-1">
                    <ul class="june-items">
                        <?php foreach (array_filter(explode("
", $_sale_items)) as $_item): ?>
                        <li><?= htmlspecialchars(trim($_item)) ?></li>
                        <?php endforeach; ?>
                    </ul>
                    <a href="clearance.php" class="btn-fire" style="background:rgba(255,255,255,0.15);border-color:rgba(255,255,255,0.4);color:#fff"><?= htmlspecialchars($_sale_btn) ?></a>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- TESTIMONIALS -->
        <?php
        $_testi_heading = tv('testi_heading', 'What Our Customers Say');
        $_testi_count   = (int) tv('testi_count', '4');
        $_testi_bg      = tv('testi_bg', 'dark');
        $_all_reviews   = file_exists(BASE_DIR.'reviews.json') ? (json_decode(file_get_contents(BASE_DIR.'reviews.json'), true) ?: []) : [];
        $_featured_reviews = array_values(array_filter($_all_reviews, fn($r) => !empty($r['featured_on_homepage']) && !empty($r['review_text'])));
        $_featured_reviews = array_slice($_featured_reviews, 0, $_testi_count);
        ?>
        <?php if (block_enabled('home','testimonials') && !empty($_featured_reviews)): ?>
        <section class="testimonials testimonials-<?= htmlspecialchars($_testi_bg) ?>" aria-label="Customer Testimonials">
            <div class="container">
                <div class="testi-header reveal">
                    <div class="eyebrow">Reviews</div>
                    <h2 class="section-title"><?= htmlspecialchars($_testi_heading) ?></h2>
                </div>
                <div class="testi-grid">
                    <?php foreach ($_featured_reviews as $_i => $_rev): ?>
                    <div class="testi-card reveal delay-<?= ($_i % 3) + 1 ?>">
                        <div class="testi-stars"><?= str_repeat('★', (int)($_rev['rating'] ?? 5)) . str_repeat('☆', 5 - (int)($_rev['rating'] ?? 5)) ?></div>
                        <p class="testi-text">&ldquo;<?= htmlspecialchars($_rev['review_text']) ?>&rdquo;</p>
                        <div class="testi-name"><?= htmlspecialchars($_rev['customer_name'] ?? 'Verified Customer') ?></div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
        <?php endif; ?>

        <!-- WHY US -->
        <section class="why-us" aria-label="Why Choose <?= tv('site_name') ?>">
            <div class="container">
                <div class="why-header reveal">
                    <div class="eyebrow">Why Choose Us</div>
                    <h2 class="section-title">Getting<br><em>It Right</em></h2>
                    <p class="section-sub">Furnishing specialists who genuinely care about getting it right for you.</p>
                </div>
                <div class="pillars">
                    <div class="pillar reveal delay-1">
                        <span class="pillar-num">01</span>
                        <div class="pillar-title">Price Guarantee</div>
                        <p class="pillar-text">We guarantee to beat any like-for-like local quote within 20 miles of our stores. No quibbles.</p>
                    </div>
                    <div class="pillar reveal delay-2">
                        <span class="pillar-num">02</span>
                        <div class="pillar-title">Expert Fitting</div>
                        <p class="pillar-text">Expert flooring specialists. Every carpet and floor fitted to the highest professional standard.</p>
                    </div>
                    <div class="pillar reveal delay-3">
                        <span class="pillar-num">03</span>
                        <div class="pillar-title">No Pressure</div>
                        <p class="pillar-text">Come in, browse, take your time. Our team is here to help — never to push. Your decision, your pace.</p>
                    </div>
                    <div class="pillar reveal delay-4">
                        <span class="pillar-num">04</span>
                        <div class="pillar-title">Fast Delivery</div>
                        <p class="pillar-text">Free local delivery on all orders. Need it fast? We'll pull out all the stops to make it happen.</p>
                    </div>
                </div>
            </div>
        </section>

        <?php endif; ?>

        <!-- DELIVERED TO -->
        <?php
        // ---- THE ONE THING A NATIONAL CANNOT COPY ----
        // Everybody claims nationwide delivery. Naming the villages is only
        // possible if you really did drive to Anderby Creek, and it is the
        // strongest thing on this page for a customer in one of them.
        //
        // delivery-places.php builds the list from the town line of customer
        // addresses and never surfaces anything else — no names, no streets,
        // no postcodes — and drops any town with fewer than five customers so
        // it can never point at one household in a village of forty.
        require_once BASE_DIR . 'delivery-places.php';
        $_places = delivery_places()['towns'] ?? [];
        ?>
        <?php if (count($_places) >= 8): ?>
        <section class="sf-delivered" aria-label="Where we deliver">
            <div class="container">
                <div class="sf-delivered-head">
                    <span class="section-label-text">We deliver here</span>
                </div>
            </div>
            <div class="sf-delivered-rail" aria-hidden="true">
                <div class="sf-delivered-run">
                    <?php for ($_i = 0; $_i < 2; $_i++): ?>
                        <?php foreach ($_places as $_pl): ?><span><?= htmlspecialchars($_pl) ?></span><?php endforeach; ?>
                    <?php endfor; ?>
                </div>
            </div>
            <?php
            // Under the places, not above them: it reads as a caption to the
            // drifting list rather than a heading nobody has the context for yet.
            ?>
            <div class="container">
                <p class="sf-delivered-note">Our own vans, our own drivers &mdash; and they put it where you want it.</p>
            </div>
            <?php
            // The full list as plain text is kept only for anyone who has asked
            // for less motion, where the rail does not run. On everybody else's
            // screen it was a wall of place names under a list of place names.
            ?>
            <div class="container"><p class="sf-delivered-plain"><?= htmlspecialchars(implode(' · ', $_places)) ?></p></div>
        </section>
        <?php endif; ?>

        <!-- FIND US -->
        <?php
        $_visit_heading    = tv('visit_heading', "Come & See Us\nIn Person");
        $_visit_subtext    = tv('visit_subtext', 'Nothing beats seeing furniture in real life. Come in, sit down, take your time — no appointment needed.');
        $_visit_bg         = tv('visit_bg', 'light');
        $_visit_show_hours = tv('visit_show_hours', true);
        $_visit_show_map   = tv('visit_show_map', true);
        $_visit_lines = explode("\n", $_visit_heading);
        ?>
        <?php
        // The Squires layout has its own three-showroom block, with the maps on
        // it. Running both printed the same three shops twice on one page.
        ?>
        <?php if (block_enabled('home','visit') && $_home_layout !== 'squires'): ?>
        <section id="find-us" class="find-us" aria-label="Our Locations" style="<?= $_visit_bg==='dark'?'background:var(--navy)':($_visit_bg==='white'?'background:#fff':'') ?>">
            <div class="container">
                <div class="find-grid">
                    <div class="reveal-left">
                        <div class="eyebrow">Visit Us</div>
                        <h2 class="section-title"><?php
                            if (count($_visit_lines) > 1) {
                                $_visit_last = array_pop($_visit_lines);
                                echo nl2br(htmlspecialchars(implode("\n", $_visit_lines))) . '<br><em>' . htmlspecialchars($_visit_last) . '</em>';
                            } else {
                                echo htmlspecialchars($_visit_heading);
                            }
                        ?></h2>
                        <p class="section-sub"><?= htmlspecialchars($_visit_subtext) ?></p>
                        <?php
                        // ---- PICK A SHOP, THE MAP FOLLOWS ----
                        //
                        // Three shops were listed side by side under one map that was
                        // hardcoded to the business address — so whichever shop you read
                        // about, the map showed Mablethorpe. And "Get Directions" was
                        // skipped for the first store entirely, which is the main
                        // showroom: the one place most people are actually looking for.
                        //
                        // Only shops with an address are selectable, because a shop with
                        // no address cannot be put on a map. Any others still print, they
                        // just do not offer the button.
                        $_vi_stores = [];
                        foreach (stores_list() as $_vi_s) {
                            if (!($_vi_s['name'] ?? '') && !($_vi_s['address'] ?? '')) continue;
                            $_vi_stores[] = $_vi_s;
                        }
                        $_vi_first_map = '';
                        foreach ($_vi_stores as $_vi_s) {
                            $_vi_first_map = store_map_embed_url($_vi_s);
                            if ($_vi_first_map !== '') break;
                        }
                        ?>
                        <div class="find-locations">
                            <?php foreach ($_vi_stores as $_vi_i => $_vi_store):
                                $_vi_phone = $_vi_store['phone'] ?: tv('business_phone');
                                $_vi_embed = store_map_embed_url($_vi_store);
                                $_vi_dir   = store_directions_url($_vi_store);
                                $_vi_first = $_vi_embed !== '' && $_vi_embed === $_vi_first_map;
                            ?>
                            <div class="find-location<?= $_vi_first ? ' is-active' : '' ?>"
                                 <?php if ($_vi_embed !== ''): ?>data-map="<?= htmlspecialchars($_vi_embed) ?>"<?php endif; ?>
                                 data-name="<?= htmlspecialchars($_vi_store['name']) ?>">
                                <?php if (!empty($_vi_store['label'])): ?>
                                <div class="find-location-label"><?= htmlspecialchars($_vi_store['label']) ?></div>
                                <?php endif; ?>
                                <div class="find-location-name"><?= htmlspecialchars($_vi_store['name']) ?></div>
                                <div class="find-location-detail">
                                    <?= htmlspecialchars($_vi_store['address']) ?><br>
                                    <?php if ($_visit_show_hours): $_hrs = opening_hours_display($_vi_store); if ($_hrs): ?><?= htmlspecialchars($_hrs) ?><br><?php endif; endif; ?>
                                    <?php if ($_vi_phone): ?><a href="tel:<?= preg_replace('/[^0-9+]/','',$_vi_phone) ?>"><?= htmlspecialchars($_vi_phone) ?></a><?php endif; ?>
                                    <?php if (tv('business_email')): ?>&nbsp;·&nbsp;<a href="mailto:<?= tv('business_email') ?>">Email Us</a><?php endif; ?>
                                </div>
                                <div class="find-location-actions">
                                    <?php if ($_vi_embed !== ''): ?>
                                    <button type="button" class="find-location-pick" aria-pressed="<?= $_vi_first ? 'true' : 'false' ?>">
                                        <span>Show on map</span>
                                    </button>
                                    <?php endif; ?>
                                    <?php if ($_vi_dir !== ''): ?>
                                    <a class="find-location-dir" href="<?= htmlspecialchars($_vi_dir) ?>" target="_blank" rel="noopener">Get Directions →</a>
                                    <?php endif; ?>
                                </div>
                                <?php if ($_vi_embed !== ''): ?>
                                <?php
                                // The map belongs to the shop and sits underneath it, rather
                                // than three cards pointing at one map floating off to the
                                // right that showed the wrong place for two of them at any
                                // moment.
                                //
                                // No src until it is opened: three Google embeds loading on
                                // every homepage hit is three third-party requests nobody
                                // asked for, on a page that already has a film to fetch.
                                ?>
                                <div class="find-location-map" hidden>
                                    <iframe data-src="<?= htmlspecialchars($_vi_embed) ?>"
                                        width="100%" height="300" style="border:0"
                                        allowfullscreen loading="lazy"
                                        referrerpolicy="no-referrer-when-downgrade"
                                        title="<?= htmlspecialchars($_vi_store['name']) ?> on the map"></iframe>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php if (false): // the shared map is now one per shop, above ?>
                    <div class="find-map reveal-right delay-2">
                        <?php if ($_vi_first_map !== ''): ?>
                        <iframe id="find-us-map"
                            src="<?= htmlspecialchars($_vi_first_map) ?>"
                            width="100%" height="520"
                            style="border:0;" allowfullscreen="" loading="lazy"
                            referrerpolicy="no-referrer-when-downgrade"
                            title="<?= tv('site_name') ?> Location">
                        </iframe>
                        <?php else: ?>
                        <div style="width:100%;height:520px;background:#f2f2f2;display:flex;align-items:center;justify-content:center;color:#888;text-align:center;padding:20px;box-sizing:border-box">Add your shop addresses in Business Details to show them here.</div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
        <script>
        // ---- EACH SHOP OPENS ITS OWN MAP ----
        // Progressive: with no JavaScript every card still prints its address,
        // hours and phone, and "Get Directions" is a real link that already
        // works. The map is an extra, not the way to find a shop.
        //
        // The src is set on first open and left alone after, so a shop nobody
        // clicks never loads an embed at all.
        (function () {
            var cards = document.querySelectorAll(".find-location");
            if (!cards.length) return;

            Array.prototype.forEach.call(cards, function (card) {
                var btn   = card.querySelector(".find-location-pick");
                var wrap  = card.querySelector(".find-location-map");
                if (!btn || !wrap) return;
                var frame = wrap.querySelector("iframe");
                btn.setAttribute("aria-expanded", "false");
                card.classList.remove("is-active");

                btn.addEventListener("click", function () {
                    var opening = wrap.hidden;

                    Array.prototype.forEach.call(cards, function (other) {
                        var ow = other.querySelector(".find-location-map");
                        var ob = other.querySelector(".find-location-pick");
                        if (!ow || !ob) return;
                        ow.hidden = true;
                        other.classList.remove("is-active");
                        ob.setAttribute("aria-expanded", "false");
                        var ol = ob.querySelector("span"); if (ol) ol.textContent = "Show on map";
                    });

                    if (opening) {
                        if (frame && !frame.getAttribute("src")) {
                            frame.setAttribute("src", frame.getAttribute("data-src") || "");
                        }
                        wrap.hidden = false;
                        card.classList.add("is-active");
                        btn.setAttribute("aria-expanded", "true");
                        var l = btn.querySelector("span"); if (l) l.textContent = "Hide map";
                    }
                });
            });
        })();
        </script>
        <?php endif; ?>
    </main>

    <!-- FOOTER -->
<?php require_once __DIR__ . '/footer.php'; ?>
