<?php $totalItems = count($items); ?>

<!-- Category pills — client-side filter, no page reload -->
<div class="cat-strip" style="padding-top:14px;">
    <button class="cat-pill active" data-cat="0" onclick="filterCat(0)">
        <i class="bi bi-grid-fill"></i> All
    </button>
    <?php foreach ($categories as $cat): ?>
    <button class="cat-pill" data-cat="<?= $cat['id'] ?>" onclick="filterCat(<?= $cat['id'] ?>)">
        <?php if (!empty($cat['icon_image'])): ?>
        <img class="cat-pill-img" src="<?= e(upload_url($cat['icon_image'])) ?>" alt="">
        <?php else: ?>
        <i class="bi bi-cup-hot-fill"></i>
        <?php endif; ?>
        <?= e($cat['name']) ?>
    </button>
    <?php endforeach; ?>
</div>

<?php if (empty($items)): ?>
<div class="empty-state">
    <div class="empty-state-icon">🍽</div>
    <h4>No items available</h4>
    <p>Check back soon!</p>
</div>
<?php else: ?>

<!-- View toggle -->
<div class="view-toggle-bar">
    <span class="view-count" id="itemCount"><?= $totalItems ?> item<?= $totalItems !== 1 ? 's' : '' ?></span>
    <div class="view-btns">
        <button class="view-btn active" id="btnGrid" onclick="setView('grid')" title="Grid view">
            <i class="bi bi-grid"></i>
        </button>
        <button class="view-btn" id="btnList" onclick="setView('list')" title="List view">
            <i class="bi bi-list-ul"></i>
        </button>
    </div>
</div>

<!-- Grid view (default) -->
<div class="item-grid" id="viewGrid">
    <?php foreach ($items as $item): ?>
    <div class="grid-card" data-cat="<?= (int)$item['category_id'] ?>"
         data-name="<?= e(strtolower($item['name'])) ?>"
         data-desc="<?= e(strtolower($item['description'] ?? '')) ?>"
         onclick="openItemModal(<?= (int)$item['id'] ?>)">
        <div class="gc-img-wrap">
            <?php if (!empty($item['item_image'])): ?>
            <img src="<?= e(upload_url($item['item_image'])) ?>" alt="<?= e($item['name']) ?>" loading="lazy" class="gc-img">
            <?php else: ?>
            <div class="gc-img-ph">🍽</div>
            <?php endif; ?>
        </div>
        <div class="gc-body">
            <div class="gc-name"><?= e($item['name']) ?></div>
            <?php if (!empty($item['description'])): ?>
            <div class="gc-desc"><?= e($item['description']) ?></div>
            <?php endif; ?>
            <div class="gc-footer">
                <div class="gc-price"><?= money((float)$item['base_price']) ?></div>
                <button class="gc-add" onclick="event.stopPropagation(); openItemModal(<?= (int)$item['id'] ?>)">
                    <i class="bi bi-plus-lg"></i>
                </button>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- List view -->
<div class="item-group" id="viewList" style="display:none;margin:0 14px;">
    <?php foreach ($items as $item): ?>
    <div class="item-card" data-cat="<?= (int)$item['category_id'] ?>"
         data-name="<?= e(strtolower($item['name'])) ?>"
         data-desc="<?= e(strtolower($item['description'] ?? '')) ?>"
         onclick="openItemModal(<?= (int)$item['id'] ?>)">
        <div class="item-card-body">
            <div class="item-veg-badge"><span></span></div>
            <div class="item-name"><?= e($item['name']) ?></div>
            <?php if (!empty($item['description'])): ?>
            <div class="item-desc"><?= e($item['description']) ?></div>
            <?php endif; ?>
            <div class="item-price"><?= money((float)$item['base_price']) ?></div>
        </div>
        <div class="item-card-right">
            <?php if (!empty($item['item_image'])): ?>
            <img class="item-card-img" src="<?= e(upload_url($item['item_image'])) ?>" alt="<?= e($item['name']) ?>" loading="lazy">
            <?php else: ?>
            <div class="item-card-img-placeholder">🍽</div>
            <?php endif; ?>
            <button class="item-add-btn" onclick="event.stopPropagation(); openItemModal(<?= (int)$item['id'] ?>)">+ ADD</button>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- No results placeholder -->
<div id="noResults" class="empty-state" style="display:none;margin:16px 14px;">
    <div class="empty-state-icon">🔍</div>
    <h4 id="noResultsMsg">No results found</h4>
    <p>Try a different keyword or category.</p>
</div>

<script>
let activeCat = <?= (int)($activeCat ?? 0) ?>;
let searchTerm = '';

function allCards() {
    const view = document.getElementById('viewGrid').style.display === 'none' ? 'viewList' : 'viewGrid';
    return [...document.getElementById(view).children];
}

function applyFilters() {
    // When user is searching, ignore active category — search all items
    ['viewGrid','viewList'].forEach(viewId => {
        const container = document.getElementById(viewId);
        [...container.children].forEach(card => {
            let show;
            if (searchTerm) {
                // Search mode: category ignored, match name/desc only
                show = card.dataset.name.includes(searchTerm) ||
                       card.dataset.desc.includes(searchTerm);
            } else {
                // Browse mode: category filter only
                show = activeCat === 0 || parseInt(card.dataset.cat) === activeCat;
            }
            card.style.display = show ? '' : 'none';
        });
    });

    // Update count badge
    const visible = [...document.getElementById('viewGrid').children]
        .filter(c => c.style.display !== 'none').length;
    document.getElementById('itemCount').textContent =
        visible + (visible === 1 ? ' item' : ' items');

    // No results message
    document.getElementById('noResults').style.display = visible === 0 ? '' : 'none';
    if (visible === 0 && searchTerm) {
        document.getElementById('noResultsMsg').textContent = `No results for "${searchTerm}"`;
    }
}

function filterCat(catId) {
    activeCat = catId;
    document.querySelectorAll('.cat-pill').forEach(p =>
        p.classList.toggle('active', parseInt(p.dataset.cat) === catId)
    );
    applyFilters();
}

// Override live-search to call applyFilters instead
window._menuFilterHook = function(term) {
    searchTerm = term.toLowerCase().trim();
    // While searching, visually deactivate all category pills
    document.querySelectorAll('.cat-pill').forEach(p =>
        p.classList.toggle('active', !searchTerm && parseInt(p.dataset.cat) === activeCat)
    );
    applyFilters();
};

function setView(v) {
    const isGrid = v === 'grid';
    document.getElementById('viewGrid').style.display = isGrid ? '' : 'none';
    document.getElementById('viewList').style.display = isGrid ? 'none' : '';
    document.getElementById('btnGrid').classList.toggle('active', isGrid);
    document.getElementById('btnList').classList.toggle('active', !isGrid);
    localStorage.setItem('menuView', v);
    applyFilters();
}

// Restore view preference
const _saved = localStorage.getItem('menuView');
if (_saved === 'list') setView('list'); else setView('grid');

// Apply initial category from URL
if (activeCat) filterCat(activeCat);
</script>
<?php endif; ?>

<?php include __DIR__ . '/_item_modal.php'; ?>

<?php if (!\Core\Session::get('customer_id')): ?>
<!-- ── Guest login prompt (dismissible bottom banner) ── -->
<div id="guestPrompt" style="
    position:fixed;bottom:0;left:0;right:0;z-index:1100;
    background:#fff;border-top:2px solid var(--accent);
    padding:14px 16px 20px;box-shadow:0 -4px 24px rgba(0,0,0,.15);
    display:flex;align-items:center;gap:12px;
    transform:translateY(100%);transition:transform .35s cubic-bezier(.22,1,.36,1);">
    <?php
    $_logoUrl = !empty($shopSettings['restaurant_logo']) ? upload_url($shopSettings['restaurant_logo']) : null;
    ?>
    <?php if ($_logoUrl): ?>
    <img src="<?= e($_logoUrl) ?>" alt="Logo" style="width:36px;height:36px;border-radius:50%;object-fit:cover;flex-shrink:0;">
    <?php else: ?>
    <div style="font-size:1.6rem;flex-shrink:0;">🍕</div>
    <?php endif; ?>
    <div style="flex:1;min-width:0;">
        <div style="font-size:.88rem;font-weight:700;color:#1c1c1e;">Sign in for a better experience</div>
        <div style="font-size:.75rem;color:#6b7280;margin-top:1px;">Track orders, save address &amp; earn loyalty rewards</div>
    </div>
    <a href="<?= url('shop/login') ?>" style="
        flex-shrink:0;padding:9px 16px;background:var(--accent);color:#fff;
        border-radius:10px;font-size:.82rem;font-weight:700;text-decoration:none;white-space:nowrap;">
        Sign In
    </a>
    <button onclick="dismissGuestPrompt()" style="
        flex-shrink:0;background:none;border:none;font-size:1.1rem;color:#9ca3af;
        cursor:pointer;padding:4px;line-height:1;">✕</button>
</div>
<script>
(function () {
    const el  = document.getElementById('guestPrompt');
    const key = 'guestPromptDismissed';
    if (sessionStorage.getItem(key)) return;     // dismissed this session
    // Show after 3 s delay so it doesn't interrupt browsing
    setTimeout(() => { el.style.transform = 'translateY(0)'; }, 3000);
})();
function dismissGuestPrompt() {
    const el = document.getElementById('guestPrompt');
    el.style.transform = 'translateY(100%)';
    sessionStorage.setItem('guestPromptDismissed', '1');
}
</script>
<?php endif; ?>
