<?php
require_once __DIR__ . '/core/init.php';

function formatPhoneUSGeneric($phone) {
    $cleaned = preg_replace('/[^0-9]/', '', (string)$phone);
    if (strlen($cleaned) === 10) {
        return sprintf("(%s) %s-%s", substr($cleaned, 0, 3), substr($cleaned, 3, 3), substr($cleaned, 6));
    }
    if (strlen($cleaned) === 11 && substr($cleaned, 0, 1) === '1') {
         return sprintf("+1 (%s) %s-%s", substr($cleaned, 1, 3), substr($cleaned, 4, 3), substr($cleaned, 7));
    }
    return $phone;
}

$servicesList = [];
$schedData = null;
$biz = $biz ?? []; 
$reviewsData = $reviewsData ?? [];

if (isset($pdo)) {
    try {
        $stmtS = $pdo->prepare("SELECT name FROM services ORDER BY name ASC");
        $stmtS->execute();
        $servicesList = $stmtS->fetchAll(PDO::FETCH_COLUMN);

        $id_for_schedule = $biz['user_id'] ?? $biz['id'] ?? 1; 
        $stmtH = $pdo->prepare("SELECT daily_hours, blocked_dates, timezone FROM schedule_config WHERE user_id = ? LIMIT 1");
        $stmtH->execute([$id_for_schedule]);
        $schedData = $stmtH->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {}
}

$client_business_name = $biz['company_name'] ?? 'Flow Cleaning Services';
$logo_url         = $biz['logo_url'] ?? ''; 
$website_url      = $biz['website_url'] ?? '#';
$email_address    = $biz['site_email'] ?? '';
$license_number   = $biz['license_number'] ?? '';
$timezone_config  = $biz['timezone'] ?? $schedData['timezone'] ?? 'America/New_York';

$primary_phone_raw    = $biz['phone_primary'] ?? '';
$display_phone        = formatPhoneUSGeneric($primary_phone_raw);
$link_phone           = preg_replace('/[^0-9]/', '', $primary_phone_raw) ?: '#';

$whatsapp_raw         = $biz['whatsapp'] ?? '';
$link_whatsapp        = 'https://wa.me/' . preg_replace('/\D/', '', $whatsapp_raw) ?: '#';

$reviews_links = $reviewsData;
$branding = ['favicon' => '/core/img/favicon.png'];
$value_proposition_en = "For busy homeowners and businesses in New York, Renton, Seattle, and Tacoma seeking more than just a common clean. We offer impeccable, discreet service designed to make your space a sanctuary of peace and pride—effortlessly.";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome To <?php echo htmlspecialchars($client_business_name); ?></title>
    <meta name="robots" content="noindex, nofollow">
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url ?? ''); ?>">
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php if(file_exists('files/gtm-body.php')) include 'files/gtm-body.php'; ?>
<div id="wrapper" class="pt-[64px] md:pt-0">
    <header class="hidden md:block bg-white border-b border-black/5 shadow-[0_8px_30px_rgba(0,0,0,0.06)]">
        <div class="max-w-7xl mx-auto px-6 lg:px-8 py-5">
            <div class="flex items-center gap-6">
                <div class="flex-shrink-0 flex items-center">
                    <a href="<?php echo htmlspecialchars($website_url); ?>" aria-label="Home" class="inline-flex items-center">
                        <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="<?php echo htmlspecialchars($client_business_name); ?> logo" class="h-14 lg:h-16 w-auto object-contain" loading="eager" decoding="async">
                    </a>
                </div>
                <div class="ml-auto"></div>
                <nav aria-label="Primary actions" class="flex items-center gap-3 lg:gap-4">
                    <a href="tel:<?php echo $link_phone; ?>" class="group inline-flex items-center gap-3 pl-2 pr-4 py-2 rounded-2xl bg-white border border-black/10 shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all">
                        <span class="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-[var(--color-secondary)] text-[var(--color-primary)] shadow-xs group-hover:shadow-sm transition">
                            <i data-lucide="phone" class="w-5 h-5"></i>
                        </span>
                        <span class="font-extrabold text-[var(--color-primary)] tracking-wide"><?php echo htmlspecialchars($display_phone); ?></span>
                    </a>
                    <span aria-hidden="true" class="hidden xl:block w-px h-8 bg-black/10"></span>
                    <a href="mailto:<?php echo htmlspecialchars($email_address); ?>" class="group inline-flex items-center gap-3 pl-2 pr-4 py-2 rounded-2xl bg-white border border-black/10 shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all">
                        <span class="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-[var(--color-secondary)] text-[var(--color-primary)] shadow-xs group-hover:shadow-sm transition">
                            <i data-lucide="mail" class="w-5 h-5"></i>
                        </span>
                        <span class="font-extrabold text-[var(--color-primary)] tracking-wide max-w-[260px] lg:max-w-none truncate"><?php echo htmlspecialchars($email_address); ?></span>
                    </a>
                    <a href="#quote-form" class="inline-flex items-center gap-3 px-6 py-3.5 rounded-2xl font-extrabold text-[var(--color-primary)] bg-[var(--color-highlight)] shadow-[0_10px_24px_rgba(0,0,0,0.12)] hover:shadow-[0_14px_30px_rgba(0,0,0,0.16)] hover:-translate-y-0.5 active:translate-y-0 transition-all">
                        GET A QUOTE <i data-lucide="arrow-big-right-dash" class="w-5 h-5"></i>
                    </a>
                </nav>
            </div>
        </div>
        <nav class="bg-[var(--color-primary)] py-3 shadow-md hidden md:block" id="main-navbar" aria-label="Primary">
            <ul class="max-w-7xl mx-auto flex flex-wrap justify-center items-center gap-x-6 gap-y-2 text-[15px] font-extrabold uppercase tracking-wide">
                <li><a href="#wrapper" class="text-white/95 hover:text-white inline-flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-white/10 transition-colors"><i data-lucide="house" class="w-5 h-5"></i> Home</a></li>
                <li><a href="#services-list" class="text-white/95 hover:text-white inline-flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-white/10 transition-colors"><i data-lucide="briefcase" class="w-5 h-5"></i> Services</a></li>
                <li><a href="#gallery-section" class="text-white/95 hover:text-white inline-flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-white/10 transition-colors"><i data-lucide="image" class="w-5 h-5"></i> Projects</a></li>
                <li><a href="#coverage-area" class="text-white/95 hover:text-white inline-flex items-center gap-2 px-3 py-2 rounded-lg hover:bg-white/10 transition-colors"><i data-lucide="map-pin" class="w-5 h-5"></i> Coverage</a></li>
                <li><a href="#quote-form" class="border-2 border-[var(--color-secondary)] text-[var(--color-secondary)] hover:bg-[var(--color-secondary)] hover:text-[var(--color-primary)] transition-colors px-3 py-1 rounded-lg inline-flex items-center gap-2 text-sm"><i data-lucide="phone-outgoing" class="w-4 h-4"></i> Contact Us</a></li>
            </ul>
        </nav>
    </header>

    <header class="md:hidden bg-white text-[var(--color-primary)] shadow-lg py-3 px-4 flex items-center fixed top-0 left-0 w-full z-50">
        <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="w-auto h-12 object-contain mr-auto max-w-[120px]">
        <a href="tel:<?php echo $link_phone; ?>" class="mr-2 inline-flex h-10 w-10 items-center justify-center rounded-md bg-black/5 text-[var(--color-primary)]">
            <i data-lucide="phone" class="w-5 h-5"></i>
        </a>
        <button id="openAgendaModalMobile" class="mr-2 inline-flex items-center gap-2 px-3 py-2 rounded-lg font-bold bg-[var(--color-secondary)] text-white">
            <span>QUOTE</span>
            <i data-lucide="note-pen" class="w-5 h-5"></i>
        </button>
        <button id="openMobileMenu" class="ml-auto inline-flex h-10 w-10 items-center justify-center rounded-md bg-black/5 text-[var(--color-primary)]">
            <i data-lucide="menu" class="w-6 h-6"></i>
        </button>
    </header>

    <div class="mobile-menu hidden fixed inset-0 z-[60] flex flex-col h-full bg-[var(--color-primary)]" id="mobileMenu">
        <div class="w-full bg-white px-6 pt-5 pb-5 relative">
            <a href="#" id="closeMobileMenu" class="mobile-menu-link absolute top-4 right-4 flex items-center justify-center w-10 h-10 rounded-md bg-gray-100 text-gray-700 hover:bg-gray-200 hover:scale-110 transition-all">
                <i data-lucide="x" class="w-6 h-6"></i>
            </a>
            <div class="flex justify-center">
                <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="h-14 w-auto object-contain max-h-[56px]">
            </div>
        </div>
        <div class="bg-[var(--color-primary)] p-6 rounded-2xl shadow-2xl mx-4 mb-4">
            <p class="text-center text-lg font-bold tracking-wider text-[var(--color-secondary)] mb-4">Ready To Start?</p>
            <a href="<?php echo htmlspecialchars($link_whatsapp); ?>" class="group block w-full bg-[var(--color-secondary)] text-white p-4 rounded-xl shadow-lg hover:brightness-110 mb-4">
                <div class="flex items-center gap-4">
                    <div class="flex-shrink-0"><i data-lucide="phone" class="w-7 h-7"></i></div>
                    <div class="text-left">
                        <p class="font-extrabold text-2xl leading-tight"><?php echo htmlspecialchars($display_phone); ?></p>
                        <p class="text-sm font-medium opacity-80">WhatsApp Or Call</p>
                    </div>
                </div>
            </a>
        </div>
        <nav class="p-4">
            <ul class="divide-y divide-white/10 rounded-lg overflow-hidden border border-white/10">
                <li><a href="#wrapper" class="mobile-menu-link flex items-center justify-between px-4 py-3 text-white">HOME</a></li>
                <li><a href="#quote-form" class="mobile-menu-link flex items-center justify-between px-4 py-3 text-[var(--color-secondary)]">CONTACT US</a></li>
            </ul>
        </nav>
    </div>

    <main class="flex-grow">
        <section id="hero" class="relative px-6 pt-28 pb-16 md:py-28 hero-section-bg" style="background-color: #000;">
            <div class="absolute inset-0 bg-black/50"></div>
            <div class="relative max-w-7xl mx-auto md:flex md:items-center md:gap-12">
                <div class="md:w-1/2 text-center md:text-left">
                    <div class="inline-flex items-center gap-2 px-3 py-1.5 rounded-md bg-white/10 text-[var(--color-secondary)] font-semibold tracking-widest ring-1 ring-white/20">
                        <span class="inline-flex items-center gap-3 text-xl sm:text-2xl font-extrabold tracking-wider text-[var(--color-secondary)]">
                            <i data-lucide="sun" class="w-7 h-7"></i>
                            <span>Hello, Good Day!</span>
                        </span>
                    </div>
                    <h1 class="font-extrabold leading-tight mt-3">
                        <span class="block text-3xl sm:text-4xl md:text-5xl text-white">Expert Solutions For</span>
                        <span class="block text-4xl sm:text-5xl md:text-5xl text-[var(--color-secondary)]"><?php echo htmlspecialchars($client_business_name); ?></span>
                    </h1>
                    <p class="mt-4 text-base sm:text-lg text-white/90 max-w-lg mx-auto md:mx-0"><?php echo $value_proposition_en; ?></p>
                    <div class="mt-8 flex flex-col sm:flex-row sm:items-center sm:gap-6 justify-center md:justify-start">
                        <a href="#quote-form" class="bg-[var(--color-highlight)] hover:brightness-110 text-[var(--color-primary)] font-bold px-8 py-4 rounded-lg shadow-lg inline-flex items-center gap-2 transition">
                            REQUEST A FREE QUOTE <i data-lucide="arrow-big-right-dash" class="w-5 h-5"></i>
                        </a>
                        <div class="hidden md:block text-white">
                            <p class="text-sm tracking-wide opacity-90">Or Call Now For Your Free Quote</p>
                            <a href="tel:<?php echo $link_phone; ?>" class="text-2xl font-extrabold tracking-[0.08em]"><?php echo htmlspecialchars($display_phone); ?></a>
                        </div>
                        <a href="tel:<?php echo $link_phone; ?>" class="md:hidden mt-4 sm:mt-0 bg-[var(--color-secondary)] text-white font-extrabold px-6 py-4 rounded-lg shadow-lg inline-flex items-center justify-center gap-2 transition">
                            <i data-lucide="phone" class="w-5 h-5"></i> CALL FOR YOUR FREE QUOTE
                        </a>
                    </div>
                </div>
                <div class="md:w-1/2 mt-10 md:mt-0 flex justify-center md:justify-start">
                    <div class="w-full h-64 sm:h-80 md:h-96 bg-gray-800 rounded-xl flex items-center justify-center text-white/20 shadow-2xl border border-white/10">
                        <i data-lucide="image" class="w-20 h-20"></i>
                    </div>
                </div>
            </div>
        </section>

        <section class="bg-white text-[var(--color-primary)] py-12 md:py-24 px-4 border-t border-gray-100">
            <div class="max-w-7xl mx-auto grid md:grid-cols-2 items-start gap-10 md:gap-12">
                <div class="text-center md:text-left" data-aos="fade-up">
                    <p class="inline-flex items-center gap-2 px-4 py-1.5 rounded-md bg-[var(--color-primary)]/5 text-[var(--color-primary)] font-extrabold tracking-[0.15em] ring-1 ring-[var(--color-primary)]/10">Fast • Free • No Obligation</p>
                    <h2 class="font-extrabold leading-[0.95] tracking-tight mt-4">
                        <span class="block text-[var(--color-primary)] text-3xl sm:text-5xl md:text-4xl">Get Your Free, Custom Quote</span>
                    </h2>
                    <p class="text-gray-600 leading-relaxed max-w-2xl mt-5 text-base sm:text-lg md:text-xl mx-auto md:mx-0">Tell us what you need and we’ll design a plan that fits your reality. No contracts. No pressure. Just clear pricing.</p>

                    <div class="mt-10">
                        <div id="status-now-container" class="mb-4 p-4 rounded-xl border flex items-center gap-4 transition-all duration-500 shadow-sm">
                            <div id="status-dot" class="w-3 h-3 rounded-full animate-pulse"></div>
                            <div>
                                <p class="text-xs font-bold uppercase tracking-widest text-gray-500 mb-0">Current Status</p>
                                <h3 id="status-text" class="text-lg font-black text-[var(--color-primary)]">Checking...</h3>
                            </div>
                        </div>

                        <h3 class="font-extrabold text-lg mb-4 flex items-center gap-2 justify-center md:justify-start text-[var(--color-primary)]">
                            <i data-lucide="calendar-check" class="w-5 h-5 text-[var(--color-secondary)]"></i>
                            Weekly Business Hours
                        </h3>
                        <div id="weekly-schedule-grid" class="flex flex-col gap-2 max-w-md mx-auto md:mx-0 bg-gray-50 p-5 rounded-2xl border border-gray-100 shadow-inner">
                            </div>
                    </div>
                </div>

                <div id="quote-form" class="bg-[var(--color-primary)] text-white -mx-4 sm:mx-0 rounded-none sm:rounded-2xl p-5 sm:p-7 md:p-8 shadow-2xl ring-1 ring-white/10" data-aos="fade-up" data-aos-delay="80">
                    <h3 class="font-extrabold text-center leading-tight mb-2 text-xl sm:text-3xl">Request A Free Quote <span class="text-[var(--color-secondary)]">(~60 Sec)</span></h3>
                    <p class="text-center text-sm text-white/70 mb-5">No commitment. We reply fast with clear, customized pricing.</p>
                    <form id="contact-form-main" class="space-y-5 js-lead-form" action="submit_lead.php" method="post">
                        <input type="hidden" name="form_origin" value="main">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
                            <div class="min-w-0"><input type="text" name="name" class="block w-full rounded-xl border-0 bg-white/10 px-4 h-12 text-white placeholder-white/50 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-secondary)]" placeholder="Your Name" required></div>
                            <div class="min-w-0"><input type="email" name="email" class="block w-full rounded-xl border-0 bg-white/10 px-4 h-12 text-white placeholder-white/50 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-secondary)]" placeholder="YourEmail@email.com" required></div>
                            <div class="min-w-0"><input type="tel" name="phone" class="block w-full rounded-xl border-0 bg-white/10 px-4 h-12 text-white placeholder-white/50 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-secondary)]" placeholder="(XXX) XXX-XXXX" required></div>
                            <div class="min-w-0">
                                <select name="service" class="block w-full rounded-xl border-0 bg-white/10 px-4 h-12 text-white shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-secondary)]" required>
                                    <option value="" class="text-black/50">Select A Service</option>
                                    <?php foreach ($servicesList as $svc): ?>
                                        <option value="<?php echo htmlspecialchars($svc); ?>" class="text-black"><?php echo htmlspecialchars($svc); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        <div class="min-w-0"><textarea name="message" rows="4" class="block w-full rounded-xl border-0 bg-white/10 px-4 py-3 text-white placeholder-white/50 shadow-sm focus:outline-none focus:ring-2 focus:ring-[var(--color-secondary)]" placeholder="Tell Us How We Can Help You..." required></textarea></div>
                        <button type="submit" class="w-full mt-1 inline-flex items-center justify-center gap-3 px-6 py-4 rounded-xl font-extrabold text-[var(--color-primary)] bg-[var(--color-highlight)] hover:opacity-90 shadow-lg transition">
                            <span>GET YOUR FREE QUOTE NOW</span> <i data-lucide="send-horizontal" class="w-5 h-5"></i>
                        </button>
                        <div id="form-message" class="mt-3 text-center text-sm font-semibold hidden"></div>
                    </form>
                </div>
            </div>
        </section>
    </main>

    <footer class="mt-auto bg-[var(--color-primary)] text-white border-t border-white/10">
        <div class="max-w-7xl mx-auto px-6 lg:px-8 py-12">
            <div class="grid grid-cols-1 md:grid-cols-12 gap-10 items-start">
                <div class="md:col-span-4">
                    <div class="inline-flex items-center gap-3 rounded-2xl bg-white/95 ring-1 ring-black/10 shadow-md px-4 py-3">
                        <img src="<?php echo htmlspecialchars($logo_url); ?>" alt="Logo" class="h-12 w-auto object-contain">
                    </div>
                    <p class="mt-5 text-sm text-white/90">Commercial & Residential <span class="mx-2">|</span> Licensed & Insured</p>
                    <p class="mt-5 text-sm text-white"><?php if (!empty($license_number)): ?>Lic. # <span class="mx-2">|</span> <span class="mx-2 text-[var(--color-secondary)]"><?php echo htmlspecialchars($license_number); ?></span><?php endif; ?></p>
                </div>
                <div class="md:col-span-5">
                    <h3 class="text-sm font-semibold tracking-wider text-white/80 uppercase text-left">Connect with us</h3>
                    <div class="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <?php foreach ($reviews_links as $platform => $url): ?>
                            <a href="<?php echo htmlspecialchars($url); ?>" target="_blank" class="group inline-flex items-center justify-between gap-3 rounded-xl px-4 py-2 bg-white/5 hover:bg-white/10 ring-1 ring-white/10 hover:ring-white/20 transition-all">
                                <span class="inline-flex items-center gap-3"><span class="text-sm font-medium text-white/90 group-hover:text-white"><?php echo ucfirst($platform); ?></span></span>
                                <i data-lucide="arrow-up-right" class="w-4 h-4 text-white/50 group-hover:text-white/80"></i>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="md:col-span-3">
                    <h3 class="text-sm font-semibold tracking-wider text-white/80 uppercase text-left">Contact us now</h3>
                    <ul class="mt-4 space-y-3">
                        <li class="flex items-center gap-3"><i data-lucide="phone" class="w-4 h-4"></i> <a href="tel:<?php echo $link_phone; ?>" class="text-sm text-white/90 hover:text-white"><?php echo htmlspecialchars($display_phone); ?></a></li>
                        <li class="flex items-center gap-3"><i data-lucide="mail" class="w-4 h-4"></i> <a href="mailto:<?php echo htmlspecialchars($email_address); ?>" class="text-sm text-white/90 hover:text-white truncate max-w-[240px]"><?php echo htmlspecialchars($email_address); ?></a></li>
                    </ul>
                </div>
            </div>
            <div class="mt-10 pt-6 border-t border-white/10 flex flex-col items-center gap-4">
                <p class="text-xs text-white/60">© <?php echo date('Y'); ?> <?php echo htmlspecialchars($client_business_name); ?>. All Rights Reserved.</p>
            </div>
        </div>
    </footer>

    <a href="<?php echo htmlspecialchars($link_whatsapp); ?>" target="_blank" class="fixed bottom-6 right-6 z-[1000] bg-[#25D366] text-white w-14 h-14 rounded-full shadow-xl hover:scale-105 transition-all duration-300 flex items-center justify-center focus:outline-none focus:ring-4 focus:ring-[#25D366]/50">
        <i data-lucide="message-circle" class="w-8 h-8"></i>
    </a>
</div>

<script>
    AOS.init({ once: true, duration: 800 });
    lucide.createIcons();

    // Data real de la DB con corrección de lógica
    const RAW_SCHEDULE = <?php 
        $days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        $dailyHours = json_decode($schedData['daily_hours'] ?? '{}', true);
        $finalSchedule = [];
        for ($i = 0; $i <= 6; $i++) {
            // Acceso robusto a la configuración: usa la clave de string (que es lo que produce el JSON)
            // o la clave de array si json_decode lo maneja como array indexado.
            $config = $dailyHours[(string)$i] ?? $dailyHours[$i] ?? ['active' => 0, 'start' => '09:00', 'end' => '17:00'];
            $finalSchedule[] = [
                "day_name" => $days[$i],
                // El error estaba aquí, donde la coerción de tipos fallaba. Forzamos la comprobación de valor.
                "is_active" => (bool)($config['active'] ?? 0), 
                "start" => $config['start'] ?? '09:00',
                "end" => $config['end'] ?? '17:00'
            ];
        }
        echo json_encode($finalSchedule); 
    ?>;
    
    const BLOCKED_DATES = <?php echo $schedData['blocked_dates'] ?? '[]'; ?>;
    const BIZ_TIMEZONE = "<?php echo $timezone_config; ?>";

    function formatAMPM(time) {
        let [h, m] = time.split(':');
        let hours = parseInt(h);
        let minutes = parseInt(m);
        let ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12 || 12;
        return `${hours}:${minutes.toString().padStart(2, '0')} ${ampm}`;
    }

    function updateUI() {
        const grid = document.getElementById('weekly-schedule-grid');
        const statusText = document.getElementById('status-text');
        const statusDot = document.getElementById('status-dot');
        const statusContainer = document.getElementById('status-now-container');

        const now = new Date();
        const formatter = new Intl.DateTimeFormat('en-US', {
            timeZone: BIZ_TIMEZONE, hour: '2-digit', minute: '2-digit', weekday: 'long', year: 'numeric', month: '2-digit', day: '2-digit', hour12: false
        });
        
        const parts = formatter.formatToParts(now);
        const currentDayName = parts.find(p => p.type === 'weekday').value;
        const currentTime = `${parts.find(p => p.type === 'hour').value}:${parts.find(p => p.type === 'minute').value}`;
        
        // Formatear la fecha como YYYY-MM-DD para la comprobación de bloqueos
        const year = parts.find(p => p.type === 'year').value;
        const month = parts.find(p => p.type === 'month').value.padStart(2, '0');
        const day = parts.find(p => p.type === 'day').value.padStart(2, '0');
        const currentFullDate = `${year}-${month}-${day}`;
        
        // Aseguramos que BLOCKED_DATES sea un array antes de usar some
        const blockedDatesArray = Array.isArray(BLOCKED_DATES) ? BLOCKED_DATES : JSON.parse(BLOCKED_DATES);
        const isBlockedToday = blockedDatesArray.some(b => b.date === currentFullDate);
        
        let isOpenNow = false;
        grid.innerHTML = '';

        RAW_SCHEDULE.forEach(day => {
            const isToday = day.day_name === currentDayName;
            let dayIsActuallyActive = day.is_active;

            if (isToday && isBlockedToday) dayIsActuallyActive = false;

            if (isToday && dayIsActuallyActive) {
                if (currentTime >= day.start && currentTime <= day.end) isOpenNow = true;
            }

            // DISEÑO COMPACTO
            const row = document.createElement('div');
            const dayWeight = isToday ? 'font-black text-[var(--color-primary)]' : 'font-semibold text-gray-500';
            const timeColor = dayIsActuallyActive ? 'text-[var(--color-primary)]' : 'text-red-400';
            
            row.className = `flex justify-between items-center py-2 border-b border-gray-100 last:border-0 ${isToday ? 'bg-white -mx-2 px-2 rounded-lg shadow-sm' : ''}`;
            row.innerHTML = `
                <span class="${dayWeight} text-sm w-20">${day.day_name}</span>
                <span class="text-xs font-bold ${timeColor}">
                    ${dayIsActuallyActive ? `${formatAMPM(day.start)} — ${formatAMPM(day.end)}` : 'Closed'}
                </span>
            `;
            grid.appendChild(row);
        });

        // Actualización del estado "OPEN NOW"
        statusContainer.classList.remove('border-green-300', 'bg-green-50', 'border-red-300', 'bg-red-50');
        statusText.classList.remove('text-green-600', 'text-red-600');

        if (isOpenNow) {
            statusText.innerText = "WE ARE OPEN NOW";
            statusDot.className = "w-3 h-3 rounded-full bg-green-500 animate-pulse";
            statusContainer.classList.add('border-green-300', 'bg-green-50');
            statusText.classList.add('text-green-600');
        } else {
            statusText.innerText = isBlockedToday ? "CLOSED TODAY (HOLIDAY)" : "WE ARE CLOSED RIGHT NOW";
            statusDot.className = "w-3 h-3 rounded-full bg-red-500";
            statusContainer.classList.add('border-red-300', 'bg-red-50');
            statusText.classList.add('text-red-600');
        }
    }

    updateUI();

    (function() {
        const mobMenu = document.getElementById('mobileMenu');
        const openMob = document.getElementById('openMobileMenu');
        const closeMob = document.getElementById('closeMobileMenu');
        if(openMob && mobMenu) {
            openMob.addEventListener('click', ()=> mobMenu.classList.remove('hidden'));
            closeMob.addEventListener('click', ()=> mobMenu.classList.add('hidden'));
            mobMenu.querySelectorAll('a').forEach(l => l.addEventListener('click', ()=> mobMenu.classList.add('hidden')));
        }
        document.querySelectorAll('.js-lead-form').forEach(form => {
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                const msg = form.querySelector('#form-message');
                msg.classList.remove('hidden');
                msg.innerText = "Sending...";
                try {
                    const res = await fetch(form.action, { method: 'POST', body: new FormData(form) });
                    if (res.ok) {
                        msg.innerText = "Sent successfully!";
                        msg.classList.add('text-green-300');
                        form.reset();
                    } else throw new Error();
                } catch {
                    msg.innerText = "Error sending message.";
                    msg.classList.add('text-red-300');
                }
            });
        });
    })();
</script>
</body>
</html>