<style>
/* =========================================================
   APPOINTMENT CALENDAR HEADER (Light Blue, Collapsible)
   ========================================================= */
:root {
    --header-bg-blue: rgba(239, 246, 255, 0.96); /* Light Blue Glass */
    --border-light-blue: #bfdbfe;
    --brand-blue: #1d4ed8;
    --brand-blue-light: #dbeafe;
}

.cal-header-wrapper {
    position: sticky;
    top: 0;
    z-index: 80;
    width: 100%;
    background: var(--header-bg-blue);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border: 1px solid var(--border-light-blue);
    border-top: none;
    border-radius: 0 0 20px 20px;
    box-shadow: 0 8px 25px -8px rgba(37, 99, 235, 0.15);
    margin-bottom: 24px;
    transition: all 0.35s ease;
    overflow: hidden;
}

/* Accent Line */
.cal-header-wrapper::before {
    content: ''; 
    position: absolute; top: 0; left: 0; right: 0; height: 4px;
    background: linear-gradient(90deg, #1e3a8a, #3b82f6, #059669);
}

/* TOP BAR (Always Visible) */
.cal-top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid rgba(191, 219, 254, 0.5);
}

.cal-page-title { 
    font-size: 22px; 
    font-weight: 900; 
    color: var(--text-main); 
    display: flex; 
    align-items: center; 
    gap: 12px; 
    margin: 0; 
    letter-spacing: -0.5px;
}

.cal-page-title i { color: var(--brand-blue); }

.cal-top-actions {
    display: flex;
    align-items: center;
    gap: 16px;
}

/* View Toggle Switch */
.view-toggle-group {
    display: flex;
    background: #ffffff;
    border: 1px solid #cbd5e1;
    border-radius: 10px;
    overflow: hidden;
    padding: 2px;
}

.view-btn {
    background: transparent;
    border: none;
    padding: 8px 16px;
    font-size: 13px;
    font-weight: 700;
    color: var(--text-muted);
    cursor: pointer;
    border-radius: 8px;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
}

.view-btn.active {
    background: var(--brand-blue-light);
    color: var(--brand-blue);
}

/* Locked Small Book Button */
.btn-book-locked { 
    background: var(--e-blue); 
    color: #fff; 
    padding: 10px 18px !important; 
    border: none; 
    border-radius: 10px; 
    font-size: 13px !important; 
    font-weight: 800; 
    cursor: pointer; 
    transition: all 0.2s; 
    text-decoration: none; 
    display: inline-flex; 
    align-items: center; 
    gap: 8px; 
    white-space: nowrap !important;
    width: auto !important;
    flex: 0 0 auto !important;
    box-shadow: 0 4px 10px rgba(30, 58, 138, 0.15); 
}
.btn-book-locked:hover { background: #1e293b; transform: translateY(-2px); }

/* Collapse/Expand Button */
.btn-collapse {
    background: #ffffff;
    border: 1px solid var(--border-light-blue);
    color: var(--brand-blue);
    width: 36px;
    height: 36px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 2px 4px rgba(37, 99, 235, 0.1);
}
.btn-collapse:hover { background: var(--brand-blue); color: #fff; transform: scale(1.05); }

/* COLLAPSIBLE CONTENT AREA */
.cal-collapsible-content {
    padding: 20px 24px;
    max-height: 800px;
    opacity: 1;
    overflow: hidden;
    transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1), padding 0.4s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease;
}

.cal-collapsible-content.collapsed {
    max-height: 0;
    padding-top: 0;
    padding-bottom: 0;
    opacity: 0;
    margin: 0;
    pointer-events: none;
}

/* KPI Row */
.kpi-row { 
    display: grid; 
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); 
    gap: 16px; 
    margin-bottom: 24px; 
}
.kpi-card { 
    background: rgba(255, 255, 255, 0.8); 
    border-radius: 14px; 
    padding: 16px; 
    border: 1px solid rgba(191, 219, 254, 0.5); 
    display: flex; 
    align-items: center; 
    gap: 16px; 
}
.kpi-icon { 
    width: 48px; 
    height: 48px; 
    border-radius: 12px; 
    display: flex; 
    align-items: center; 
    justify-content: center; 
    font-size: 20px; 
    color: #fff; 
    flex-shrink: 0;
}
.kpi-data h4 { margin: 0; font-size: 11px; color: var(--text-muted); text-transform: uppercase; font-weight: 800; letter-spacing: 0.5px;}
.kpi-data .val { margin: 4px 0 0 0; font-size: 22px; font-weight: 900; color: var(--text-main); }
.gender-split { display: flex; align-items: center; gap: 10px; font-size: 14px; font-weight: 800; margin-top: 4px; }
.g-male { color: #3b82f6; display: flex; align-items: center; gap: 4px; }
.g-female { color: #ec4899; display: flex; align-items: center; gap: 4px; }
.g-divider { width: 2px; height: 14px; background: #cbd5e1; }

/* Filter Command Bar */
.command-bar { 
    background: rgba(255, 255, 255, 0.9); 
    border: 1px solid rgba(191, 219, 254, 0.8); 
    border-radius: 14px; 
    padding: 16px; 
    display: flex; 
    flex-wrap: wrap; 
    gap: 16px; 
    align-items: flex-end; 
}
.filter-group { display: flex; flex-direction: column; gap: 6px; flex: 1; min-width: 160px; }
.filter-group label { font-size: 11px; font-weight: 800; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px;}
.filter-group select { padding: 10px 14px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 13px; font-weight: 600; outline: none; background: #fff; width: 100%; color: var(--text-main); cursor: pointer;}
.filter-group select:focus { border-color: var(--e-blue); box-shadow: 0 0 0 3px var(--e-blue-light); }

.date-range-container { display: flex; align-items: center; border: 1px solid #cbd5e1; border-radius: 8px; background: #fff; overflow: hidden; }
.date-range-container:focus-within { border-color: var(--e-blue); box-shadow: 0 0 0 3px var(--e-blue-light); }
.date-range-container input[type="date"] { border: none; background: transparent; padding: 10px 12px; font-size: 13px; font-weight: 600; color: var(--text-main); outline: none; width: 50%; cursor: pointer;}
.date-separator { background: #f1f5f9; color: #64748b; padding: 0 10px; font-size: 11px; display: flex; align-items: center; justify-content: center; height: 100%; border-left: 1px solid #e2e8f0; border-right: 1px solid #e2e8f0; }

.btn-filter { background: var(--e-green); color: #fff; padding: 0 20px; border: none; border-radius: 8px; height: 40px; font-size: 13px; font-weight: 800; cursor: pointer; transition: all 0.2s; white-space: nowrap; display: flex; align-items: center; gap: 8px; flex: 0 0 auto;}
.btn-filter:hover { background: #047857; transform: translateY(-2px);}

@media (max-width: 768px) {
    .cal-top-bar { flex-direction: column; align-items: stretch; gap: 16px; padding: 16px; }
    .cal-top-actions { justify-content: space-between; width: 100%; flex-wrap: wrap; }
    .view-toggle-group { flex: 1; justify-content: center; }
    .view-btn { flex: 1; justify-content: center; }
    
    .command-bar { flex-direction: column; align-items: stretch; }
    .date-range-container { flex-direction: column; border-radius: 8px; }
    .date-range-container input[type="date"] { width: 100%; padding: 12px; }
    .date-separator { display: none; }
    .date-range-container input[type="date"]:first-child { border-bottom: 1px solid #cbd5e1; }
    .btn-filter { width: 100%; justify-content: center; margin-top: 8px; }
}
</style>

<div class="cal-header-wrapper">
    
    <div class="cal-top-bar">
        <h1 class="cal-page-title"><i class="fa-solid fa-stethoscope"></i> Daily Schedule</h1>
        
        <div class="cal-top-actions">
            <div class="view-toggle-group">
                <button type="button" class="view-btn active" id="btnViewTiles" onclick="switchCalendarView('tiles')">
                    <i class="fa-solid fa-grip"></i> Tiles
                </button>
                <button type="button" class="view-btn" id="btnViewDetailed" onclick="switchCalendarView('detailed')">
                    <i class="fa-solid fa-list"></i> List View
                </button>
            </div>

            <a href="../patient/search_patient.php" class="btn-book-locked">
                <i class="fa-solid fa-calendar-plus"></i> Book
            </a>

            <button type="button" class="btn-collapse" id="toggleHeaderBtn" title="Toggle Filters & Stats">
                <i class="fa-solid fa-minus"></i>
            </button>
        </div>
    </div>

    <div class="cal-collapsible-content" id="collapsibleHeaderContent">
        <div class="kpi-row">
            <div class="kpi-card">
                <div class="kpi-icon" style="background: linear-gradient(135deg, #3b82f6, #2563eb);"><i class="fa-solid fa-clipboard-list"></i></div>
                <div class="kpi-data"><h4>Total Booked</h4><div class="val"><?php echo $kpi_total ?? 0; ?></div></div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon" style="background: linear-gradient(135deg, #f59e0b, #d97706);"><i class="fa-solid fa-user-clock"></i></div>
                <div class="kpi-data"><h4>Pending / Waiting</h4><div class="val"><?php echo $kpi_pending ?? 0; ?></div></div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon" style="background: linear-gradient(135deg, #10b981, #059669);"><i class="fa-solid fa-notes-medical"></i></div>
                <div class="kpi-data"><h4>Completed</h4><div class="val"><?php echo $kpi_completed ?? 0; ?></div></div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon" style="background: linear-gradient(135deg, #8b5cf6, #7c3aed);"><i class="fa-solid fa-hospital-user"></i></div>
                <div class="kpi-data">
                    <h4>Demographics</h4>
                    <div class="gender-split">
                        <span class="g-male"><i class="fa-solid fa-mars"></i> <?php echo $kpi_male ?? 0; ?></span>
                        <div class="g-divider"></div>
                        <span class="g-female"><i class="fa-solid fa-venus"></i> <?php echo $kpi_female ?? 0; ?></span>
                    </div>
                </div>
            </div>
        </div>

        <form class="command-bar" method="get" action="">
            <div class="filter-group" style="flex: 1.5;">
                <label>Date Range</label>
                <div class="date-range-container">
                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($filter_date_from ?? date('Y-m-d')); ?>">
                    <div class="date-separator"><i class="fa-solid fa-arrow-right"></i></div>
                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($filter_date_to ?? date('Y-m-d')); ?>">
                </div>
            </div>
            <div class="filter-group">
                <label>Assigned Provider</label>
                <select name="doctor_id">
                    <option value="">All Providers</option>
                    <?php if(!empty($doctors)): foreach($doctors as $d): ?>
                        <option value="<?php echo htmlspecialchars($d['id']); ?>" <?php if(($filter_doctor ?? '') == $d['id']) echo 'selected'; ?>><?php echo htmlspecialchars($d['name']); ?></option>
                    <?php endforeach; endif; ?>
                </select>
            </div>
            <div class="filter-group">
                <label>Department</label>
                <select name="department_id">
                    <option value="">All Departments</option>
                    <?php if(!empty($departments)): foreach($departments as $dept): ?>
                        <option value="<?php echo htmlspecialchars($dept['id']); ?>" <?php if(($filter_department ?? '') == $dept['id']) echo 'selected'; ?>><?php echo htmlspecialchars($dept['name']); ?></option>
                    <?php endforeach; endif; ?>
                </select>
            </div>
            <div class="filter-group">
                <label>Status</label>
                <select name="status">
                    <option value="">All Statuses</option>
                    <option value="Pending" <?php if(($filter_status ?? '') == 'Pending') echo 'selected'; ?>>Pending / Scheduled</option>
                    <option value="Completed" <?php if(($filter_status ?? '') == 'Completed') echo 'selected'; ?>>Completed</option>
                    <option value="Cancelled" <?php if(($filter_status ?? '') == 'Cancelled') echo 'selected'; ?>>Cancelled</option>
                </select>
            </div>
            <button type="submit" class="btn-filter"><i class="fa-solid fa-filter"></i> Filter</button>
        </form>
    </div>
</div>

<script>
// =========================================================================
// ANTI-SHAKING AUTO-COLLAPSE LOGIC (BULLETPROOFED)
// =========================================================================
document.addEventListener('DOMContentLoaded', function() {
    const toggleBtn = document.getElementById('toggleHeaderBtn');
    const content = document.getElementById('collapsibleHeaderContent');
    const icon = toggleBtn.querySelector('i');
    
    let lastScrollTop = window.pageYOffset || document.documentElement.scrollTop;
    let isAnimating = false;
    let animTimeout;

    // Core Toggling Function
    function toggleHeader(forceCollapse = null) {
        let isCurrentlyCollapsed = content.classList.contains('collapsed');
        let willCollapse = forceCollapse !== null ? forceCollapse : !isCurrentlyCollapsed;

        // Abort if already in desired state
        if (isCurrentlyCollapsed === willCollapse) return;

        if (willCollapse) {
            content.classList.add('collapsed');
            icon.classList.remove('fa-minus');
            icon.classList.add('fa-plus');
        } else {
            content.classList.remove('collapsed');
            icon.classList.remove('fa-plus');
            icon.classList.add('fa-minus');
        }

        // Lock scroll detection during the transition to prevent infinite shaking
        isAnimating = true;
        clearTimeout(animTimeout);
        animTimeout = setTimeout(() => {
            isAnimating = false;
            // CRITICAL FIX: Reset the baseline scroll position AFTER the layout shift
            // so the browser's automatic scroll compensation doesn't trigger a reverse toggle.
            lastScrollTop = window.pageYOffset || document.documentElement.scrollTop;
        }, 450); 
    }

    // Manual Click
    toggleBtn.addEventListener('click', () => toggleHeader());

    // Auto Collapse/Expand on Scroll
    window.addEventListener('scroll', function() {
        // Stop listening completely if the header is currently shrinking or expanding
        if (isAnimating) return;

        let currentScroll = window.pageYOffset || document.documentElement.scrollTop;
        
        // If user scrolls back to the absolute top of the page, always expand
        if (currentScroll < 50) {
            toggleHeader(false);
            lastScrollTop = currentScroll;
            return;
        }

        // Ignore tiny accidental scroll bumps
        if (Math.abs(lastScrollTop - currentScroll) <= 20) return;

        // Scrolled Down significantly
        if (currentScroll > lastScrollTop && currentScroll > 150) {
            toggleHeader(true); 
        } 
        // Scrolled Up significantly
        else if (currentScroll < lastScrollTop) {
            toggleHeader(false); 
        }

        lastScrollTop = currentScroll <= 0 ? 0 : currentScroll; 
    }, { passive: true });
});
</script>