<?php
/**
 * Checkout Page - MontaLoja Storefront
 * Página de finalização de pedido
 * Template: Modern Theme com CSS Global
 */

if (!defined('BARBERFLOW')) {
    define('BARBERFLOW', true);
}

require_once __DIR__ . '/../../../../../includes/config.php';

try {
    $pdo = getDB();
} catch (Exception $e) {
    die("Erro ao conectar ao banco de dados: " . $e->getMessage());
}

// ============================================
// CARREGAR DADOS DA LOJA
// ============================================

$store = null;
$requestUri = $_SERVER['REQUEST_URI'];

// PRIMEIRO: Detectar pelo slug na URL (/loja/SLUG/checkout) - tem prioridade
if (preg_match('#/loja/([a-z0-9-]+)(?:/|$)#i', $requestUri, $matches)) {
    $storeSlug = $matches[1];
    $storeStmt = $pdo->prepare("SELECT * FROM stores WHERE slug = ? AND status = 'active' LIMIT 1");
    $storeStmt->execute([$storeSlug]);
    $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
    if ($store) $_SESSION['current_store'] = $store;
}

// Tentar carregar via constante STORE_ID (router.php define isso)
if (!$store && defined('STORE_ID')) {
    $storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ? LIMIT 1");
    $storeStmt->execute([STORE_ID]);
    $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
    if ($store) $_SESSION['current_store'] = $store;
}

// Se ainda não encontrou, tentar da sessão
if (!$store) {
    $store = $_SESSION['current_store'] ?? null;
}

// Tentar detectar pelo subdomínio (dinâmico - sem domínio hardcoded)
if (!$store) {
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $hostParts = explode('.', $host);
    // Subdomínio existe quando o host tem pelo menos 3 partes (sub.dominio.tld)
    // OU 2 partes onde a primeira não é um domínio raiz do sistema (localhost)
    if (count($hostParts) >= 2) {
        $potentialSubdomain = $hostParts[0];
        if (!in_array($potentialSubdomain, ['www', 'app', 'api', 'admin', 'localhost']) && $potentialSubdomain !== '') {
            $storeStmt = $pdo->prepare("SELECT * FROM stores WHERE (subdomain = ? OR slug = ?) AND status = 'active' LIMIT 1");
            $storeStmt->execute([$potentialSubdomain, $potentialSubdomain]);
            $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
            if ($store) $_SESSION['current_store'] = $store;
        }
    }
}

if (!$store) {
    header('Location: /');
    exit;
}

$storeId = $store['id'];
$currentStoreId = $storeId;
$storeName = $store['name'];
$storeSlug = $store['slug'] ?? $store['subdomain'] ?? '';
$whatsapp = $store['whatsapp_number'] ?? $store['whatsapp'] ?? '';
$logo = $store['logo_url'] ?? $store['logo'] ?? '';

// Payment methods configuration
$paymentMethods = json_decode($store['payment_methods'] ?? '{"whatsapp": true, "online": false}', true);
$whatsappPaymentEnabled = $paymentMethods['whatsapp'] ?? true;
$onlinePaymentEnabled = $paymentMethods['online'] ?? false;

// Check if store has MP integration for online payments
$hasMPIntegration = false;
if ($onlinePaymentEnabled) {
    $mpStmt = $pdo->prepare("SELECT is_active FROM store_payment_integrations WHERE store_id = ? AND provider = 'mercadopago' AND is_active = 1");
    $mpStmt->execute([$storeId]);
    $hasMPIntegration = $mpStmt->fetch() !== false;
}
$address = $store['address'] ?? '';
$city = $store['city'] ?? '';

// Verificar sessão do cliente
$isLoggedIn = isset($_SESSION['customer_id']);
$customerName = $_SESSION['customer_name'] ?? '';
$customerEmail = $_SESSION['customer_email'] ?? '';
$customerPhone = $_SESSION['customer_phone'] ?? '';

// Buscar endereços do cliente se logado
$customerAddresses = [];
if ($isLoggedIn && isset($_SESSION['customer_id'])) {
    try {
        $stmtAddr = $pdo->prepare("SELECT * FROM customer_addresses WHERE customer_id = ? AND store_id = ? ORDER BY is_default DESC");
        $stmtAddr->execute([$_SESSION['customer_id'], $storeId]);
        $customerAddresses = $stmtAddr->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {}
}

// ============================================
// DETERMINAR TIPO DE NEGÓCIO E TEMPLATE (igual ao storefront/home.php)
// ============================================

$businessType = $store['business_type'] ?? ($_SESSION['business_type'] ?? 'retail');
$storefrontTemplate = $store['storefront_template'] ?? null;

// Categorias de negócio -> pasta base
$businessTypeMap = [
    'retail' => 'retail',
    'service' => 'service',
    'barbershop' => 'service',
    'barber' => 'service',
    'salon' => 'service',
    'ecommerce' => 'retail',
    'store' => 'retail',
];

// Templates disponíveis por categoria
$availableTemplates = [
    'retail' => [
        'modern' => [
            'name' => 'Modern',
            'colors' => [
                'primary' => '#2563EB',
                'bg' => '#FAFBFC',
                'card' => '#FFFFFF',
                'text' => '#111827',
                'accent' => '#10B981'
            ]
        ],
    ],
    'service' => [
        'classic' => [
            'colors' => [
                'primary' => '#CCA43B',
                'bg' => '#0A0A0A',
                'card' => '#151515',
                'text' => '#FFFFFF',
                'accent' => '#D4AF37'
            ]
        ],
        'elegant' => [
            'colors' => [
                'primary' => '#D4A5A5',
                'bg' => '#FDF8F5',
                'card' => '#FFFFFF',
                'text' => '#2D2D2D',
                'accent' => '#E8C4C4'
            ]
        ]
    ]
];

// Resolver template
$templateCategory = $businessTypeMap[$businessType] ?? 'retail';
$templateName = 'modern';

if ($storefrontTemplate) {
    if ($storefrontTemplate === 'retail-light') {
        $storefrontTemplate = 'retail-modern';
    }
    if (strpos($storefrontTemplate, '-') !== false) {
        $parts = explode('-', $storefrontTemplate, 2);
        if (count($parts) === 2) {
            // Mapear a categoria do template para as categorias disponíveis
            $parsedCategory = $parts[0];
            if (isset($businessTypeMap[$parsedCategory])) {
                $templateCategory = $businessTypeMap[$parsedCategory];
            } elseif (isset($availableTemplates[$parsedCategory])) {
                $templateCategory = $parsedCategory;
            }
            $templateName = $parts[1];
        }
    } else {
        $templateName = $storefrontTemplate;
    }
}

// Garantir que a categoria existe, senão usar retail
if (!isset($availableTemplates[$templateCategory])) {
    $templateCategory = 'retail';
}

if (!isset($availableTemplates[$templateCategory][$templateName])) {
    $templateName = array_key_first($availableTemplates[$templateCategory]) ?? 'modern';
}

// ============================================
// CONFIGURAR CORES DO TEMPLATE
// ============================================

$templateConfig = $availableTemplates[$templateCategory][$templateName] ?? [];
$defaultColors = $templateConfig['colors'] ?? [];

$primaryColor = $defaultColors['primary'] ?? '#2563EB';
$bgColor = $defaultColors['bg'] ?? '#FAFBFC';
$cardColor = $defaultColors['card'] ?? '#FFFFFF';
$textColor = $defaultColors['text'] ?? '#111827';
$accentColor = $defaultColors['accent'] ?? '#10B981';

$isLightTheme = in_array($bgColor, ['#FFFFFF', '#F5F5F5', '#FAFAFA', '#FAFBFC', '#FDF8F5', '#FEF3C7', '#FFFBEB']);
$textSecondary = $isLightTheme ? '#6B7280' : '#B0B0B0';
$borderColor = $isLightTheme ? 'rgba(0,0,0,0.1)' : 'rgba(255,255,255,0.1)';
$textMuted = $isLightTheme ? '#9CA3AF' : '#707070';

// ============================================
// CARREGAR CONFIGURAÇÕES PERSONALIZADAS
// ============================================

$customSettings = [];
if (!empty($store['template_settings'])) {
    $customSettings = json_decode($store['template_settings'], true) ?? [];
}

// Aplicar cores personalizadas (sobrescrevem as do template)
if (!empty($customSettings['colors'])) {
    $primaryColor = $customSettings['colors']['primary'] ?? $primaryColor;
    $bgColor = $customSettings['colors']['bg'] ?? $bgColor;
    $cardColor = $customSettings['colors']['card'] ?? $cardColor;
    $textColor = $customSettings['colors']['text'] ?? $textColor;
    $accentColor = $customSettings['colors']['accent'] ?? $accentColor;
    $textSecondary = $customSettings['colors']['text_secondary'] ?? $textSecondary;
}

// Detectar URL base - dinâmica, sem domínio hardcoded
$currentHost = $_SERVER['HTTP_HOST'] ?? '';
$isLojaPathAccess = strpos($_SERVER['REQUEST_URI'] ?? '', '/loja/') !== false;

// Montar URL base usando get_store_url() ou detecção dinâmica
if (function_exists('get_store_url') && !empty($store)) {
    $baseUrl = get_store_url($store);
} elseif ($isLojaPathAccess) {
    $baseUrl = '/loja/' . $storeSlug;
} else {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    $baseUrl = $protocol . $currentHost;
}

// Configurações do Cabeçalho (igual ao storefront/home.php)
$headerSettings = $customSettings['header'] ?? [
    'logo_type' => 'text',
    'logo_text' => $store['name'] ?? 'Minha Loja',
    'logo_image' => $store['logo_url'] ?? '',
    'show_search' => true,
    'show_cart' => true,
    'show_wishlist' => true,
    'sticky' => true
];

$faviconUrl = $headerSettings['favicon'] ?? '';

// Menu de Navegação - Itens fixos SEMPRE aparecem primeiro
// Itens fixos que SEMPRE aparecem (Início e Produtos)
$fixedMenuItems = [
    ['id' => 1, 'name' => 'Início', 'link' => $baseUrl, 'icon' => 'solar:home-2-bold'],
    ['id' => 2, 'name' => 'Produtos', 'link' => $baseUrl . '/produtos', 'icon' => 'solar:bag-3-bold'],
];

// Itens customizáveis - filtrar Início e Produtos
$savedMenuItems = $customSettings['menu'] ?? [];
$customMenuItems = [];
if (!empty($savedMenuItems)) {
    foreach ($savedMenuItems as $item) {
        $itemName = strtolower(trim($item['name'] ?? ''));
        if (!in_array($itemName, ['início', 'inicio', 'produtos', 'home', 'products'])) {
            $customMenuItems[] = $item;
        }
    }
}
if (empty($customMenuItems)) {
    $customMenuItems = [
        ['id' => 3, 'name' => 'Categorias', 'link' => $baseUrl . '#categorias', 'icon' => 'solar:widget-4-bold'],
        ['id' => 4, 'name' => 'Contato', 'link' => $baseUrl . '#contato', 'icon' => 'solar:phone-bold']
    ];
}
$menuItems = array_merge($fixedMenuItems, $customMenuItems);

if (empty($headerSettings['logo_text'])) {
    $headerSettings['logo_text'] = $store['name'] ?? 'Minha Loja';
}

// Variáveis para header/footer
$logoType = $headerSettings['logo_type'] ?? 'text';
$logoImage = $headerSettings['logo_image'] ?? $logo;
$logoText = $headerSettings['logo_text'] ?? $storeName;
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Finalizar Pedido - <?php echo htmlspecialchars($storeName); ?></title>
    <meta name="description" content="Finalize seu pedido em <?php echo htmlspecialchars($storeName); ?>">
    
    <!-- Google Fonts -->
    <?php if (!empty($faviconUrl)): ?>
<link rel="icon" type="image/x-icon" href="<?php echo htmlspecialchars($faviconUrl); ?>">
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Icons -->
    <script src="https://cdn.jsdelivr.net/npm/iconify-icon@1.0.7/dist/iconify-icon.min.js"></script>
    
    <!-- Template Styles -->
    <link rel="stylesheet" href="/pages/storefront/templates/retail/modern/includes/styles.css?v=1.0.4">
<?php include __DIR__ . "/includes/dynamic-styles.php"; ?>
    
    <!-- Dynamic Theme Colors (igual ao home.php) -->
    <style>
    /* Dynamic Color Variables */
    :root {
        /* Cores do tema */
        --primary: <?php echo htmlspecialchars($primaryColor); ?>;
        --primary-soft: <?php echo htmlspecialchars($primaryColor); ?>14;
        --primary-hover: <?php echo htmlspecialchars($customSettings['colors']['secondary'] ?? $primaryColor); ?>;
        --primary-light: <?php echo htmlspecialchars($primaryColor); ?>20;
        --accent: <?php echo htmlspecialchars($accentColor); ?>;
        --accent-soft: <?php echo htmlspecialchars($accentColor); ?>1A;
        --bg: <?php echo htmlspecialchars($bgColor); ?>;
        --bg-white: <?php echo htmlspecialchars($cardColor); ?>;
        --surface: <?php echo htmlspecialchars($cardColor); ?>;
        --surface-secondary: #F8F9FA;
        --surface-hover: #F3F4F6;
        --text: <?php echo htmlspecialchars($textColor); ?>;
        --text-secondary: <?php echo htmlspecialchars($textSecondary); ?>;
        --text-muted: <?php echo htmlspecialchars($textMuted ?? '#9CA3AF'); ?>;
        --text-light: #9CA3AF;
        --border: <?php echo htmlspecialchars($borderColor ?? 'rgba(0,0,0,0.1)'); ?>;
        --border-dark: #D1D5DB;
        
        /* Status colors */
        --success: #10B981;
        --error: #EF4444;
        --warning: #F59E0B;
        
        /* Spacing */
        --space-1: 4px;
        --space-2: 8px;
        --space-3: 12px;
        --space-4: 16px;
        --space-5: 20px;
        --space-6: 24px;
        --space-8: 32px;
        --space-10: 40px;
        --space-12: 48px;
        
        /* Typography */
        --text-xs: 0.75rem;
        --text-sm: 0.875rem;
        --text-base: 1rem;
        --text-lg: 1.125rem;
        --text-xl: 1.25rem;
        --text-2xl: 1.5rem;
        --text-3xl: 1.875rem;
        
        /* Border radius */
        --radius: 8px;
        --radius-md: 10px;
        --radius-lg: 12px;
        --radius-xl: 16px;
        --radius-2xl: 20px;
        --radius-full: 9999px;
        
        /* Shadows */
        --shadow-sm: 0 1px 2px rgba(0,0,0,0.04);
        --shadow-md: 0 4px 12px rgba(0,0,0,0.08);
        --shadow-lg: 0 12px 40px rgba(0,0,0,0.1);
        --shadow-xl: 0 20px 50px rgba(0,0,0,0.15);
        --shadow-primary: 0 4px 14px <?php echo htmlspecialchars($primaryColor); ?>40;
        
        /* Transitions */
        --transition: 0.2s ease;
        --transition-normal: 0.3s ease;
        
        /* Z-index */
        --z-modal: 1000;
        --z-toast: 1100;
    }

        /* Login Required Styles */
        .login-required-section {
            display: flex;
            justify-content: center;
            padding: var(--space-6) 0;
        }

        .login-required-card {
            background: white;
            border-radius: var(--radius-xl);
            box-shadow: var(--shadow-lg);
            padding: var(--space-8);
            max-width: 480px;
            width: 100%;
            text-align: center;
        }

        .login-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, var(--primary), var(--primary-hover));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto var(--space-4);
        }

        .login-icon iconify-icon {
            font-size: 40px;
            color: white;
        }

        .login-required-card h2 {
            font-size: var(--text-2xl);
            color: var(--text-primary);
            margin-bottom: var(--space-2);
        }

        .login-required-card > p {
            color: var(--text-secondary);
            margin-bottom: var(--space-6);
        }

        .auth-tabs {
            display: flex;
            gap: var(--space-2);
            background: var(--bg-secondary);
            padding: 4px;
            border-radius: var(--radius-lg);
            margin-bottom: var(--space-6);
        }

        .auth-tab {
            flex: 1;
            padding: var(--space-3);
            border: none;
            background: transparent;
            border-radius: var(--radius-md);
            font-weight: 500;
            color: var(--text-secondary);
            cursor: pointer;
            transition: all 0.2s;
        }

        .auth-tab.active {
            background: white;
            color: var(--primary);
            box-shadow: var(--shadow-sm);
        }

        .auth-form {
            text-align: left;
        }

        .auth-form .form-group {
            position: relative;
            margin-bottom: var(--space-4);
        }

        .auth-form label {
            display: block;
            font-size: var(--text-sm);
            font-weight: 500;
            color: var(--text-primary);
            margin-bottom: var(--space-2);
        }

        .auth-form .form-control {
            background: #f9fafb !important;
            border: 1.5px solid #e5e7eb !important;
            border-radius: 12px !important;
            background: #f9fafb;
            border: 1.5px solid #e5e7eb;
            width: 100%;
            padding: var(--space-3) var(--space-4);
            border: 1px solid var(--border-color);
            border-radius: var(--radius-md);
            font-size: var(--text-base);
            transition: border-color 0.2s, box-shadow 0.2s;
        }

        .auth-form select.form-control {
            background: #f9fafb !important;
            border: 1.5px solid #e5e7eb !important;
            border-radius: 12px !important;
            padding: 12px 16px;
            appearance: none;
        }
        .auth-form .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
        }

        /* Input com ícone à esquerda */
        .input-icon-wrapper {
            position: relative;
        }
        .input-icon-wrapper > iconify-icon,
        .input-icon-wrapper .input-icon {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
            font-size: 1.1rem;
            pointer-events: none;
        }
        .input-icon-wrapper .form-control {
            background: #f9fafb;
            border: 1.5px solid #e5e7eb;
            border-radius: 12px;
            padding-left: 44px !important;
        }
        .input-icon-wrapper .form-control::placeholder {
            color: #9ca3af;
        }

        .password-input {
            position: relative;
        }

        .password-input input {
            padding-right: 48px !important;
        }

        .toggle-password {
            position: absolute !important;
            right: 14px !important;
            top: 50% !important;
            transform: translateY(-50%) !important;
            background: transparent !important;
            border: none !important;
            color: #9ca3af;
            cursor: pointer;
            padding: 8px;
            z-index: 20;
            pointer-events: auto !important;
        }
        .toggle-password iconify-icon {
            position: static !important;
            transform: none !important;
            color: inherit;
            font-size: 1.2rem;
            pointer-events: none;
        }

        .toggle-password:hover {
            color: var(--text-primary);
        }

        .btn-auth-submit {
            width: 100%;
            padding: var(--space-4);
            background: linear-gradient(135deg, var(--primary), var(--primary-hover));
            color: white;
            border: none;
            border-radius: var(--radius-md);
            font-size: var(--text-base);
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: var(--space-2);
            transition: transform 0.2s, box-shadow 0.2s;
            margin-top: var(--space-4);
        }

        .btn-auth-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(var(--primary-rgb), 0.4);
        }

        .btn-auth-submit iconify-icon {
            font-size: 20px;
        }

        .forgot-password {
            display: block;
            text-align: center;
            margin-top: var(--space-4);
            color: var(--text-muted);
            font-size: var(--text-sm);
            text-decoration: none;
        }

        .forgot-password:hover {
            color: var(--primary);
        }

        .divider-text {
            display: flex;
            align-items: center;
            text-align: center;
            margin: var(--space-6) 0;
        }

        .divider-text::before,
        .divider-text::after {
            content: '';
            flex: 1;
            border-bottom: 1px solid var(--border-color);
        }

        .divider-text span {
            padding: 0 var(--space-4);
            color: var(--text-secondary);
            font-size: var(--text-sm);
            font-weight: 500;
        }

        .auth-error {
            background: #fee2e2;
            color: #dc2626;
            padding: var(--space-3) var(--space-4);
            border-radius: var(--radius-md);
            margin-top: var(--space-4);
            font-size: var(--text-sm);
        }

        .form-row {
            display: flex;
            gap: var(--space-3);
        }

        .form-row .form-group {
            flex: 1;
        }

        .required {
            color: #dc2626;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        .spin { animation: spin 1s linear infinite; }

        /* Payment Method Selector */
        .payment-method-option {
            transition: all 0.3s ease;
        }
        .payment-method-option:has(input:checked) {
            border-color: var(--primary) !important;
            background: rgba(var(--primary-rgb), 0.1);
        }
        .btn-online {
            background: linear-gradient(135deg, #009ee3, #00b1ea) !important;
        }
        .btn-online:hover {
            background: linear-gradient(135deg, #0088c7, #009ee3) !important;
        }
    </style>
    
    <!-- Checkout Specific Styles -->
    <style>
        /* Checkout Layout */
        .checkout-page {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .checkout-main {
            flex: 1;
            padding: var(--space-8) 0;
        }
        
        .checkout-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 var(--space-6);
            display: grid;
            grid-template-columns: 1fr 400px;
            gap: var(--space-8);
            align-items: start;
        }
        
        .checkout-breadcrumb {
            display: flex;
            align-items: center;
            gap: var(--space-2);
            margin-bottom: var(--space-6);
            font-size: var(--text-sm);
            color: var(--text-muted);
        }
        
        .checkout-breadcrumb a {
            color: var(--text-muted);
            text-decoration: none;
            transition: color var(--transition);
        }
        
        .checkout-breadcrumb a:hover {
            color: var(--primary);
        }
        
        .checkout-breadcrumb .current {
            color: var(--text);
            font-weight: 500;
        }
        
        .checkout-title {
            font-size: var(--text-2xl);
            font-weight: 700;
            margin-bottom: var(--space-6);
            display: flex;
            align-items: center;
            gap: var(--space-3);
        }
        
        .checkout-title iconify-icon {
            color: var(--primary);
        }
        
        /* Form Section */
        .checkout-form-section {
            display: flex;
            flex-direction: column;
            gap: var(--space-6);
        }
        
        .checkout-card {
            background: var(--surface);
            border-radius: var(--radius-xl);
            border: 1px solid var(--border);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
        }
        
        .checkout-card-header {
            padding: var(--space-5) var(--space-6);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            gap: var(--space-3);
            background: var(--surface-secondary);
        }
        
        .checkout-card-header iconify-icon {
            font-size: 1.5rem;
            color: var(--primary);
        }
        
        .checkout-card-header h2 {
            font-size: var(--text-lg);
            font-weight: 600;
            margin: 0;
        }
        
        .checkout-card-body {
            padding: var(--space-6);
        }
        
        /* Form Elements */
        .form-group {
            margin-bottom: var(--space-4);
        }
        
        .form-group:last-child {
            margin-bottom: 0;
        }
        
        .form-group label {
            display: block;
            font-size: var(--text-sm);
            font-weight: 500;
            margin-bottom: var(--space-2);
            color: var(--text);
        }
        
        .form-group label .required {
            color: var(--error);
        }
        
        .form-control {
            width: 100%;
            padding: var(--space-3) var(--space-4);
            border: 1px solid var(--border);
            border-radius: var(--radius-md);
            font-size: var(--text-sm);
            font-family: inherit;
            transition: all var(--transition);
            background: var(--bg);
        }
        
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-soft);
        }
        
        .form-control::placeholder {
            color: var(--text-light);
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: var(--space-4);
        }
        
        .form-row-3 {
            display: grid;
            grid-template-columns: 120px 1fr 100px;
            gap: var(--space-4);
        }
        
        textarea.form-control {
            min-height: 100px;
            resize: vertical;
        }
        
        /* Saved Addresses */
        .saved-addresses {
            display: flex;
            flex-direction: column;
            gap: var(--space-3);
            margin-bottom: var(--space-4);
        }
        
        .address-option {
            display: flex;
            align-items: flex-start;
            gap: var(--space-3);
            padding: var(--space-4);
            border: 2px solid var(--border);
            border-radius: var(--radius-lg);
            cursor: pointer;
            transition: all var(--transition);
        }
        
        .address-option:hover {
            border-color: var(--primary-light);
            background: var(--primary-soft);
        }
        
        .address-option.selected {
            border-color: var(--primary);
            background: var(--primary-soft);
        }
        
        .address-option input[type="radio"] {
            display: none;
        }
        
        .address-radio {
            width: 20px;
            height: 20px;
            border: 2px solid var(--border-dark);
            border-radius: 50%;
            flex-shrink: 0;
            position: relative;
            transition: all var(--transition);
        }
        
        .address-option.selected .address-radio {
            border-color: var(--primary);
        }
        
        .address-option.selected .address-radio::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 10px;
            height: 10px;
            background: var(--primary);
            border-radius: 50%;
        }
        
        .address-content {
            flex: 1;
        }
        
        .address-label {
            font-weight: 600;
            margin-bottom: var(--space-1);
            display: flex;
            align-items: center;
            gap: var(--space-2);
        }
        
        .badge-default {
            font-size: var(--text-xs);
            background: var(--primary);
            color: white;
            padding: 2px 8px;
            border-radius: var(--radius-full);
            font-weight: 500;
        }
        
        .address-text {
            font-size: var(--text-sm);
            color: var(--text-muted);
            line-height: 1.5;
            margin: 0;
        }
        
        .address-option.add-new {
            flex-direction: row;
            align-items: center;
            padding: var(--space-4);
            border-style: dashed;
        }
        
        .address-option.add-new .address-content {
            display: flex;
            align-items: center;
            gap: var(--space-2);
        }
        
        .address-option.add-new iconify-icon {
            font-size: 1.3rem;
            color: var(--primary);
        }
        
        /* New Address Form */
        .new-address-form {
            padding-top: var(--space-4);
            border-top: 1px solid var(--border);
        }
        
        /* Order Summary */
        .order-summary {
            background: var(--surface);
            border-radius: var(--radius-xl);
            border: 1px solid var(--border);
            overflow: hidden;
            position: sticky;
            top: 100px;
            box-shadow: var(--shadow-md);
        }
        
        .summary-header {
            padding: var(--space-5) var(--space-6);
            background: var(--primary);
            color: white;
        }
        
        .summary-header h3 {
            font-size: var(--text-lg);
            font-weight: 600;
            margin: 0;
            display: flex;
            align-items: center;
            gap: var(--space-2);
        }
        
        .summary-items {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .summary-item {
            display: flex;
            gap: var(--space-3);
            padding: var(--space-4) var(--space-5);
            border-bottom: 1px solid var(--border);
        }
        
        .summary-item:last-child {
            border-bottom: none;
        }
        
        .summary-item-image {
            width: 60px;
            height: 60px;
            border-radius: var(--radius);
            overflow: hidden;
            background: var(--surface-secondary);
            flex-shrink: 0;
        }
        
        .summary-item-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .summary-item-info {
            flex: 1;
            min-width: 0;
        }
        
        .summary-item-name {
            font-weight: 500;
            font-size: var(--text-sm);
            margin-bottom: var(--space-1);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .summary-item-qty {
            font-size: var(--text-xs);
            color: var(--text-muted);
        }
        
        .summary-item-price {
            font-weight: 600;
            color: var(--primary);
            font-size: var(--text-sm);
        }

        .summary-item-remove {
            background: none;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            padding: 0.25rem;
            border-radius: var(--radius);
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .summary-item-remove:hover {
            color: #dc3545;
            background: rgba(220, 53, 69, 0.1);
        }
        
        .summary-totals {
            padding: var(--space-4) var(--space-5);
            background: var(--surface-secondary);
        }
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: var(--space-2) 0;
            font-size: var(--text-sm);
        }
        
        .summary-row.total {
            font-size: var(--text-lg);
            font-weight: 700;
            color: var(--primary);
            padding-top: var(--space-3);
            margin-top: var(--space-2);
            border-top: 2px solid var(--border);
        }
        
        .summary-actions {
            padding: var(--space-5);
        }
        
        .btn-checkout {
            width: 100%;
            padding: var(--space-4);
            background: linear-gradient(135deg, #25D366, #128C7E);
            color: #fff;
            border: none;
            border-radius: var(--radius-lg);
            font-size: var(--text-base);
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: var(--space-2);
            transition: all var(--transition);
            box-shadow: 0 4px 14px rgba(37, 211, 102, 0.3);
        }
        
        .btn-checkout:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(37, 211, 102, 0.4);
        }
        
        .btn-checkout:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .btn-checkout iconify-icon {
            font-size: 1.4rem;
        }
        
        .secure-badge {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: var(--space-2);
            margin-top: var(--space-4);
            font-size: var(--text-xs);
            color: var(--text-muted);
        }
        
        .secure-badge iconify-icon {
            color: var(--success);
        }
        
        /* Empty Cart */
        .empty-cart {
            text-align: center;
            padding: var(--space-12);
        }
        
        .empty-cart iconify-icon {
            font-size: 4rem;
            color: var(--text-muted);
            opacity: 0.5;
        }
        
        .empty-cart h3 {
            margin: var(--space-4) 0 var(--space-2);
            font-size: var(--text-xl);
        }
        
        .empty-cart p {
            color: var(--text-muted);
            margin-bottom: var(--space-6);
        }
        
        .btn-back-store {
            display: inline-flex;
            align-items: center;
            gap: var(--space-2);
            padding: var(--space-3) var(--space-6);
            background: var(--primary);
            color: #fff;
            text-decoration: none;
            border-radius: var(--radius-lg);
            font-weight: 600;
            transition: all var(--transition);
        }
        
        .btn-back-store:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-primary);
        }
        
        /* Success Modal */
        .success-modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            backdrop-filter: blur(4px);
            z-index: var(--z-modal);
            align-items: center;
            justify-content: center;
            padding: var(--space-4);
        }
        
        .success-modal-overlay.active {
            display: flex;
        }
        
        .success-modal {
            background: var(--surface);
            border-radius: var(--radius-2xl);
            max-width: 420px;
            width: 100%;
            text-align: center;
            padding: var(--space-10);
            animation: modalIn 0.3s ease;
        }
        
        @keyframes modalIn {
            from { opacity: 0; transform: scale(0.9); }
            to { opacity: 1; transform: scale(1); }
        }
        
        .success-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, var(--success), #16a34a);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto var(--space-6);
            box-shadow: 0 10px 30px rgba(34, 197, 94, 0.3);
        }
        
        .success-icon iconify-icon {
            font-size: 2.5rem;
            color: #fff;
        }
        
        .success-modal h2 {
            font-size: var(--text-2xl);
            margin-bottom: var(--space-2);
        }
        
        .success-modal p {
            color: var(--text-muted);
            margin-bottom: var(--space-6);
        }
        
        .order-number {
            background: var(--surface-secondary);
            padding: var(--space-4);
            border-radius: var(--radius-lg);
            font-size: var(--text-2xl);
            font-weight: 700;
            color: var(--primary);
            margin-bottom: var(--space-6);
        }
        
        .btn-whatsapp {
            width: 100%;
            padding: var(--space-4);
            background: linear-gradient(135deg, #25D366, #128C7E);
            color: #fff;
            border: none;
            border-radius: var(--radius-lg);
            font-size: var(--text-base);
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: var(--space-2);
        }
        
        .redirect-text {
            font-size: var(--text-sm);
            color: var(--text-muted);
            margin-top: var(--space-4);
        }
        
        /* Toast */
        .toast {
            position: fixed;
            bottom: var(--space-8);
            left: 50%;
            transform: translateX(-50%) translateY(100px);
            background: var(--text);
            color: #fff;
            padding: var(--space-4) var(--space-6);
            border-radius: var(--radius-lg);
            display: flex;
            align-items: center;
            gap: var(--space-2);
            z-index: var(--z-toast);
            opacity: 0;
            transition: all var(--transition-normal);
            box-shadow: var(--shadow-xl);
        }
        
        .toast.show {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }
        
        .toast.error {
            background: var(--error);
        }
        
        .toast.success {
            background: var(--success);
        }
        
        /* Responsive */
        @media (max-width: 900px) {
            .checkout-container {
                grid-template-columns: 1fr;
            }
            
            .order-summary {
                position: relative;
                top: 0;
                order: -1;
            }
        }
        
        @media (max-width: 600px) {
            .checkout-main {
                padding: var(--space-4) 0;
            }
            
            .checkout-container {
                padding: 0 var(--space-4);
            }
            
            .form-row,
            .form-row-3 {
                grid-template-columns: 1fr;
            }
            
            .checkout-card-body {
                padding: var(--space-4);
            }
        }
    </style>
</head>
<body class="checkout-page">
    <!-- Header Global -->
    <?php include __DIR__ . '/../../../includes/cart.php'; ?>

<?php include __DIR__ . '/includes/header.php'; ?>

    <!-- Main Content -->
    <main class="checkout-main">
        <div class="checkout-container">
            <!-- Form Section -->
            <div class="checkout-form-section">
                <?php if (!$isLoggedIn): ?>
                <!-- Login Required -->
                <div class="login-required-section">
                    <div class="login-required-card">
                        <div class="login-icon">
                            <iconify-icon icon="solar:user-circle-bold"></iconify-icon>
                        </div>
                        <h2>Entre ou Cadastre-se</h2>
                        <p>Para finalizar seu pedido, faça login ou crie sua conta</p>
                        
                        <!-- Login Form -->
                        <div class="auth-tabs">
                            <button class="auth-tab active" onclick="showAuthTab('login')">Entrar</button>
                            <button class="auth-tab" onclick="showAuthTab('register')">Criar Conta</button>
                            <button class="auth-tab" onclick="showAuthTab('guest')">Convidado</button>
                        </div>

                        <!-- Login Tab -->
                        <div class="auth-form" id="loginForm">
                            <form onsubmit="return handleLogin(event)">
                                <div class="form-group">
                                    <label>E-mail ou WhatsApp</label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:letter-bold"></iconify-icon><input type="text" id="login_identifier" class="form-control" autocomplete="username" placeholder="seu@email.com" required></div>
                                </div>
                                <div class="form-group">
                                    <label>Senha</label>
                                    <div class="password-input input-icon-wrapper">
                                        <iconify-icon icon="solar:lock-bold"></iconify-icon><input type="password" id="login_password" class="form-control" autocomplete="current-password" placeholder="••••••••" required>
                                        <button type="button" class="toggle-password" onclick="togglePassword('login_password')">
                                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                        </button>
                                    </div>
                                </div>
                                <button type="submit" class="btn-auth-submit">
                                    <iconify-icon icon="solar:login-2-bold"></iconify-icon>
                                    Entrar
                                </button>
                                <a href="<?php echo $baseUrl; ?>/recuperar-senha" class="forgot-password">Esqueci minha senha</a>
                            </form>
                        </div>

                        <!-- Register Tab -->
                        <div class="auth-form" id="registerForm" style="display:none;">
                            <form onsubmit="return handleRegister(event)">
                                <div class="form-group">
                                    <label>Nome Completo <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:user-bold"></iconify-icon><input type="text" id="register_name" class="form-control" placeholder="Seu nome completo" required></div>
                                </div>
                                <div class="form-group">
                                    <label>WhatsApp <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:phone-bold"></iconify-icon><input type="tel" id="register_phone" class="form-control" placeholder="(00) 00000-0000" required></div>
                                </div>
                                <div class="form-group">
                                    <label>E-mail <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:letter-bold"></iconify-icon><input type="email" id="register_email" class="form-control" autocomplete="email" placeholder="seu@email.com" required></div>
                                </div>
                                <div class="form-group">
                                    <label>Senha <span class="required">*</span></label>
                                    <div class="password-input input-icon-wrapper">
                                        <iconify-icon icon="solar:lock-bold"></iconify-icon><input type="password" id="register_password" class="form-control" style="padding-left: 44px;" autocomplete="new-password" placeholder="Mínimo 6 caracteres" required minlength="6">
                                        <button type="button" class="toggle-password" onclick="togglePassword('register_password')">
                                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                        </button>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>Confirmar Senha <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:lock-bold"></iconify-icon><input type="password" id="register_password_confirm" class="form-control" autocomplete="new-password" placeholder="Repita a senha" required></div>
                                </div>
                                
                                <div class="divider-text"><span>Endereço de Entrega</span></div>
                                
                                <div class="form-row">
                                    <div class="form-group" style="flex:1">
                                        <label>CEP <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:map-point-bold"></iconify-icon><input type="text" id="register_cep" class="form-control" placeholder="00000-000" maxlength="9" required></div>
                                    </div>
                                    <div class="form-group" style="flex:2">
                                        <label>Rua <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:home-2-bold"></iconify-icon><input type="text" id="register_street" class="form-control" placeholder="Nome da rua" required></div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group" style="flex:1">
                                        <label>Número <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:hashtag-bold"></iconify-icon><input type="text" id="register_number" class="form-control" placeholder="Nº" required></div>
                                    </div>
                                    <div class="form-group" style="flex:2">
                                        <label>Complemento</label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:buildings-2-bold"></iconify-icon><input type="text" id="register_complement" class="form-control" placeholder="Apto, Bloco"></div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group" style="flex:1">
                                        <label>Bairro <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:buildings-bold"></iconify-icon><input type="text" id="register_neighborhood" class="form-control" placeholder="Bairro" required></div>
                                    </div>
                                    <div class="form-group" style="flex:1">
                                        <label>Cidade <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:city-bold"></iconify-icon><input type="text" id="register_city" class="form-control" placeholder="Cidade" required></div>
                                    </div>
                                    <div class="form-group" style="max-width:80px">
                                        <label>UF <span class="required">*</span></label>
                                        <select id="register_state" class="form-control" required>
                                            <option value="">-</option>
                                            <option>AC</option><option>AL</option><option>AP</option><option>AM</option>
                                            <option>BA</option><option>CE</option><option>DF</option><option>ES</option>
                                            <option>GO</option><option>MA</option><option>MT</option><option>MS</option>
                                            <option>MG</option><option>PA</option><option>PB</option><option>PR</option>
                                            <option>PE</option><option>PI</option><option>RJ</option><option>RN</option>
                                            <option>RS</option><option>RO</option><option>RR</option><option>SC</option>
                                            <option>SP</option><option>SE</option><option>TO</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn-auth-submit">
                                    <iconify-icon icon="solar:user-plus-bold"></iconify-icon>
                                    Criar Conta e Continuar
                                </button>
                            </form>
                        </div>
                        
                        <!-- Guest Tab -->
                        <div class="auth-form" id="guestForm" style="display:none;">
                            <div style="text-align: center; margin-bottom: 1.5rem;">
                                <iconify-icon icon="solar:rocket-bold" style="font-size: 3rem; color: var(--primary);"></iconify-icon>
                                <h3 style="margin: 0.75rem 0 0.5rem;">Compre Rápido!</h3>
                                <p style="color: #666; font-size: 0.9rem; margin: 0;">Finalize sem criar conta. Seus dados ficam salvos apenas neste pedido.</p>
                            </div>
                            <form onsubmit="return handleGuestCheckout(event)">
                                <div class="form-group">
                                    <label>Nome Completo <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:user-bold"></iconify-icon><input type="text" id="guest_name" class="form-control" placeholder="Seu nome completo" required></div>
                                </div>
                                <div class="form-group">
                                    <label>WhatsApp <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:phone-bold"></iconify-icon><input type="tel" id="guest_phone" class="form-control" placeholder="(00) 00000-0000" required></div>
                                </div>
                                <div class="form-group">
                                    <label>E-mail <span class="required">*</span></label>
                                    <div class="input-icon-wrapper"><iconify-icon icon="solar:letter-bold"></iconify-icon><input type="email" id="guest_email" class="form-control" placeholder="seu@email.com" required></div>
                                </div>
                                
                                <div class="divider-text"><span>Endereço de Entrega</span></div>
                                
                                <div class="form-row">
                                    <div class="form-group" style="flex:1">
                                        <label>CEP <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:map-point-bold"></iconify-icon><input type="text" id="guest_cep" class="form-control" placeholder="00000-000" maxlength="9" required onblur="searchGuestCep()"></div>
                                    </div>
                                    <div class="form-group" style="flex:2">
                                        <label>Rua</label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:home-2-bold"></iconify-icon><input type="text" id="guest_street" class="form-control" placeholder="Rua, Avenida..." required></div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group" style="flex:1">
                                        <label>Número <span class="required">*</span></label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:hashtag-bold"></iconify-icon><input type="text" id="guest_number" class="form-control" placeholder="Nº" required></div>
                                    </div>
                                    <div class="form-group" style="flex:2">
                                        <label>Complemento</label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:buildings-2-bold"></iconify-icon><input type="text" id="guest_complement" class="form-control" placeholder="Apto, Bloco"></div>
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group" style="flex:2">
                                        <label>Bairro</label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:buildings-bold"></iconify-icon><input type="text" id="guest_neighborhood" class="form-control" placeholder="Bairro" required></div>
                                    </div>
                                    <div class="form-group" style="flex:2">
                                        <label>Cidade</label>
                                        <div class="input-icon-wrapper"><iconify-icon icon="solar:city-bold"></iconify-icon><input type="text" id="guest_city" class="form-control" placeholder="Cidade" required></div>
                                    </div>
                                    <div class="form-group" style="flex:1">
                                        <label>UF</label>
                                        <select id="guest_state" class="form-control" required>
                                            <option value="">UF</option>
                                            <option>AC</option><option>AL</option><option>AP</option><option>AM</option>
                                            <option>BA</option><option>CE</option><option>DF</option><option>ES</option>
                                            <option>GO</option><option>MA</option><option>MT</option><option>MS</option>
                                            <option>MG</option><option>PA</option><option>PB</option><option>PR</option>
                                            <option>PE</option><option>PI</option><option>RJ</option><option>RN</option>
                                            <option>RS</option><option>RO</option><option>RR</option><option>SC</option>
                                            <option>SP</option><option>SE</option><option>TO</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <button type="submit" class="btn-auth-submit" style="background: linear-gradient(135deg, var(--primary), var(--primary-dark, var(--primary)));">
                                    <iconify-icon icon="solar:rocket-bold"></iconify-icon>
                                    Continuar como Convidado
                                </button>
                            </form>
                        </div>

                        <div class="auth-error" id="authError" style="display:none;"></div>
                    </div>
                </div>
                <?php else: ?>
                <!-- Breadcrumb -->
                <nav class="checkout-breadcrumb">
                    <a href="<?php echo $baseUrl; ?>">
                        <iconify-icon icon="solar:home-2-bold"></iconify-icon>
                    </a>
                    <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
                    <a href="<?php echo $baseUrl; ?>">Carrinho</a>
                    <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
                    <span class="current">Finalizar Pedido</span>
                </nav>
                
                <h1 class="checkout-title">
                    <iconify-icon icon="solar:bag-check-bold"></iconify-icon>
                    Finalizar Pedido
                </h1>
                
                <!-- Dados Pessoais -->
                <div class="checkout-card">
                    <div class="checkout-card-header">
                        <iconify-icon icon="solar:user-bold"></iconify-icon>
                        <h2>Seus Dados</h2>
                    </div>
                    <div class="checkout-card-body">
                        <div class="form-group">
                            <label>Nome Completo <span class="required">*</span></label>
                            <input type="text" id="customer_name" class="form-control" placeholder="Digite seu nome completo" value="<?php echo htmlspecialchars($customerName); ?>" required>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>WhatsApp <span class="required">*</span></label>
                                <input type="tel" id="customer_phone" class="form-control" placeholder="(00) 00000-0000" value="<?php echo htmlspecialchars($customerPhone); ?>" required>
                            </div>
                            <div class="form-group">
                                <label>E-mail</label>
                                <input type="email" id="customer_email" class="form-control" placeholder="seu@email.com" value="<?php echo htmlspecialchars($customerEmail); ?>">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Endereço -->
                <div class="checkout-card">
                    <div class="checkout-card-header">
                        <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                        <h2>Endereço de Entrega</h2>
                    </div>
                    <div class="checkout-card-body">
                        <?php if ($isLoggedIn && !empty($customerAddresses)): ?>
                        <div class="saved-addresses" id="savedAddresses">
                            <?php foreach ($customerAddresses as $addr): ?>
                            <label class="address-option <?php echo $addr['is_default'] ? 'selected' : ''; ?>" onclick="selectAddress(this, <?php echo htmlspecialchars(json_encode($addr), ENT_QUOTES); ?>)">
                                <input type="radio" name="selected_address" value="<?php echo $addr['id']; ?>" <?php echo $addr['is_default'] ? 'checked' : ''; ?>>
                                <div class="address-radio"></div>
                                <div class="address-content">
                                    <div class="address-label">
                                        <?php echo htmlspecialchars($addr['label'] ?: 'Endereço'); ?>
                                        <?php if ($addr['is_default']): ?><span class="badge-default">Padrão</span><?php endif; ?>
                                    </div>
                                    <p class="address-text">
                                        <?php echo htmlspecialchars($addr['street'] . ', ' . $addr['number']); ?>
                                        <?php if ($addr['complement']): ?> - <?php echo htmlspecialchars($addr['complement']); ?><?php endif; ?><br>
                                        <?php echo htmlspecialchars($addr['neighborhood'] . ' - ' . $addr['city'] . '/' . $addr['state']); ?><br>
                                        CEP: <?php echo htmlspecialchars(substr($addr['cep'], 0, 5) . '-' . substr($addr['cep'], 5)); ?>
                                    </p>
                                </div>
                            </label>
                            <?php endforeach; ?>

                            <label class="address-option add-new" onclick="showNewAddressForm()">
                                <input type="radio" name="selected_address" value="new">
                                <div class="address-content">
                                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                                    <span>Adicionar novo endereço</span>
                                </div>
                            </label>
                        </div>
                        <?php endif; ?>

                        <div class="new-address-form" id="newAddressForm" <?php echo ($isLoggedIn && !empty($customerAddresses)) ? 'style="display:none"' : ''; ?>>
                            <div class="form-row-3">
                                <div class="form-group">
                                    <label>CEP <span class="required">*</span></label>
                                    <input type="text" id="cep" class="form-control" placeholder="00000-000" maxlength="9">
                                </div>
                                <div class="form-group">
                                    <label>Rua <span class="required">*</span></label>
                                    <input type="text" id="street" class="form-control" placeholder="Nome da rua">
                                </div>
                                <div class="form-group">
                                    <label>Número <span class="required">*</span></label>
                                    <input type="text" id="number" class="form-control" placeholder="Nº">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Complemento</label>
                                    <input type="text" id="complement" class="form-control" placeholder="Apto, bloco, etc.">
                                </div>
                                <div class="form-group">
                                    <label>Bairro <span class="required">*</span></label>
                                    <input type="text" id="neighborhood" class="form-control" placeholder="Bairro">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Cidade <span class="required">*</span></label>
                                    <input type="text" id="city" class="form-control" placeholder="Cidade">
                                </div>
                                <div class="form-group">
                                    <label>Estado <span class="required">*</span></label>
                                    <input type="text" id="state" class="form-control" placeholder="UF" maxlength="2">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Observações -->
                <div class="checkout-card">
                    <div class="checkout-card-header">
                        <iconify-icon icon="solar:notebook-bold"></iconify-icon>
                        <h2>Observações</h2>
                    </div>
                    <div class="checkout-card-body">
                        <div class="form-group">
                            <label>Alguma observação para o pedido?</label>
                            <textarea id="notes" class="form-control" placeholder="Ex: Entregar após as 18h, deixar na portaria..."></textarea>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Order Summary -->
            <aside class="order-summary">
                <div class="summary-header">
                    <h3>
                        <iconify-icon icon="solar:bag-3-bold"></iconify-icon>
                        Resumo do Pedido
                    </h3>
                </div>
                
                <div class="summary-items" id="summaryItems">
                    <!-- Items loaded via JS -->
                </div>
                
                <!-- Shipping Selection -->
                <div id="shippingSection" style="margin-bottom: 1rem; padding: 1rem; background: var(--bg-light, #f9f9f9); border-radius: 12px;">
                    <div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.75rem;">
                        <iconify-icon icon="solar:delivery-bold" style="color: var(--primary);"></iconify-icon>
                        <strong>Opções de Entrega</strong>
                    </div>
                    <div id="shippingOptionsCheckout">
                        <p style="color: var(--text-muted); font-size: 0.9rem;">Informe o CEP no endereço para calcular o frete.</p>
                    </div>
                    <input type="hidden" id="selectedShippingMethod" value="">
                    <input type="hidden" id="selectedShippingCost" value="0">
                    <input type="hidden" id="selectedShippingDays" value="">
                </div>
                <div class="summary-totals">
                    <div class="summary-row">
                        <span>Subtotal</span>
                        <span id="subtotal">R$ 0,00</span>
                    </div>
                    <div class="summary-row">
                        <span>Entrega</span>
                        <span id="shipping">A combinar</span>
                    </div>
                    <div class="summary-row total">
                        <span>Total</span>
                        <span id="total">R$ 0,00</span>
                    </div>
                </div>
                
                <div class="summary-actions">
                    <!-- Payment Method Selection -->
                    <?php $bothEnabled = $whatsappPaymentEnabled && $onlinePaymentEnabled && $hasMPIntegration; ?>
                    <?php if ($bothEnabled): ?>
                    <div class="payment-method-selector" style="margin-bottom: 1rem;">
                        <p style="margin-bottom: 0.75rem; font-weight: 600; color: var(--text);">Forma de Pagamento:</p>
                        <div style="display: flex; gap: 0.5rem;">
                            <div id="optWhatsapp" class="payment-method-option active" onclick="selectPaymentMethod('whatsapp')" style="flex: 1; padding: 0.75rem; border: 2px solid var(--primary); border-radius: 8px; cursor: pointer; text-align: center; transition: all 0.3s; background: rgba(var(--primary-rgb), 0.1);">
                                <iconify-icon icon="logos:whatsapp-icon" style="font-size: 1.5rem; display: block; margin: 0 auto 0.25rem;"></iconify-icon>
                                <span style="font-size: 0.8rem;">WhatsApp</span>
                            </div>
                            <div id="optOnline" class="payment-method-option" onclick="selectPaymentMethod('online')" style="flex: 1; padding: 0.75rem; border: 2px solid var(--border-color); border-radius: 8px; cursor: pointer; text-align: center; transition: all 0.3s;">
                                <iconify-icon icon="solar:card-bold" style="font-size: 1.5rem; display: block; margin: 0 auto 0.25rem; color: #009ee3;"></iconify-icon>
                                <span style="font-size: 0.8rem;">Pagar Online</span>
                            </div>
                        </div>
                        <input type="hidden" id="selectedPaymentMethod" value="whatsapp">
                    </div>
                    <?php endif; ?>
                    <?php if ($whatsappPaymentEnabled): ?>
                    <button type="button" id="btnFinishWhatsapp" class="btn-checkout" onclick="finishOrder('whatsapp')" style="<?= $bothEnabled ? '' : '' ?>">
                        <iconify-icon icon="logos:whatsapp-icon"></iconify-icon>
                        Enviar Pedido via WhatsApp
                    </button>
                    <?php endif; ?>
                    
                    <?php if ($onlinePaymentEnabled && $hasMPIntegration): ?>
                    <button type="button" id="btnFinishOnline" class="btn-checkout btn-online" onclick="finishOrder('online')" style="background: linear-gradient(135deg, #009ee3, #00b1ea); <?= $bothEnabled ? 'display: none;' : '' ?>">
                        <iconify-icon icon="solar:card-bold"></iconify-icon>
                        Pagar Online
                    </button>
                    <?php endif; ?>
                    
                    <div class="secure-badge">
                        <iconify-icon icon="solar:shield-check-bold"></iconify-icon>
                        Pedido seguro e criptografado
                    </div>
                </div>
            </aside>
        </div>
    </main>

    <!-- Footer Global -->
    <?php include __DIR__ . '/includes/footer.php'; ?>

    <!-- Success Modal -->
    <div class="success-modal-overlay" id="successModal">
        <div class="success-modal">
            <div class="success-icon">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
            </div>
            <h2>Pedido Criado!</h2>
            <p>Seu pedido foi registrado com sucesso.</p>
            <div class="order-number">
                Pedido #<span id="orderNumber">0000</span>
            </div>
            <div id="orderTrackingLink" style="display: none; margin-top: 1rem;">
                <div style="background: var(--bg, #f9fafb); border: 1px solid var(--border-color, #e5e7eb); border-radius: 10px; padding: 1rem;">
                    <p style="margin: 0 0 0.75rem 0; font-size: 0.9rem; color: var(--text-muted);">📋 Guarde este link para acompanhar seu pedido:</p>
                    <a id="trackingUrl" href="#" target="_blank" style="display: block; background: var(--primary); color: #fff; text-decoration: none; padding: 0.75rem 1rem; border-radius: 8px; text-align: center; font-weight: 500;">
                        <iconify-icon icon="solar:link-bold"></iconify-icon> Acompanhar Meu Pedido
                    </a>
                </div>
            </div>
            <div id="whatsappRedirect" style="display: none; text-align: center;">
                <p style="margin-bottom: 1rem; color: var(--text-muted);">Clique no botão abaixo para enviar o pedido ao lojista.</p>
                <button class="btn-whatsapp" onclick="redirectToWhatsApp()">
                    <iconify-icon icon="logos:whatsapp-icon"></iconify-icon>
                    Enviar no WhatsApp
                </button>
                <button class="btn-whatsapp" style="background: var(--primary); margin-top: 10px;" onclick="window.location.href='/loja/' + STORE_SLUG">
                    <iconify-icon icon="solar:home-2-bold"></iconify-icon>
                    Voltar à Loja
                </button>
            </div>
            <div id="notificationSent" style="display: none; text-align: center;">
                <div style="background: rgba(34, 197, 94, 0.15); border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem;">
                    <iconify-icon icon="solar:chat-round-check-bold" style="font-size: 2.5rem; color: #22C55E; display: block; margin-bottom: 0.5rem;"></iconify-icon>
                    <p style="margin: 0; color: #22C55E; font-weight: 600; font-size: 1.1rem;">Notificação enviada!</p>
                    <p style="margin: 0.5rem 0 0 0; color: var(--text-muted); font-size: 0.9rem;">Você receberá os detalhes no seu WhatsApp</p>
                </div>
                <button class="btn-whatsapp" style="background: var(--primary);" onclick="window.location.href='/loja/' + STORE_SLUG">
                    <iconify-icon icon="solar:home-2-bold"></iconify-icon>
                    Voltar à Loja
                </button>
            </div>
        </div>
    </div>

    <!-- Toast -->
    <div class="toast" id="toast"></div>

    <!-- Cart Component -->
    <script>
        // Store and API configuration
        // Payment method toggle
        // Seleção de método de pagamento
        function selectPaymentMethod(method) {
            // Atualizar hidden input
            const hiddenInput = document.getElementById('selectedPaymentMethod');
            if (hiddenInput) hiddenInput.value = method;
            
            // Atualizar estilos dos seletores
            const optWhatsapp = document.getElementById('optWhatsapp');
            const optOnline = document.getElementById('optOnline');
            
            if (method === 'whatsapp') {
                if (optWhatsapp) {
                    optWhatsapp.style.borderColor = 'var(--primary)';
                    optWhatsapp.style.background = 'rgba(var(--primary-rgb), 0.1)';
                }
                if (optOnline) {
                    optOnline.style.borderColor = 'var(--border-color)';
                    optOnline.style.background = 'transparent';
                }
            } else {
                if (optWhatsapp) {
                    optWhatsapp.style.borderColor = 'var(--border-color)';
                    optWhatsapp.style.background = 'transparent';
                }
                if (optOnline) {
                    optOnline.style.borderColor = '#009ee3';
                    optOnline.style.background = 'rgba(0, 158, 227, 0.1)';
                }
            }
            
            // Mostrar/ocultar botões
            const btnWhatsapp = document.getElementById('btnFinishWhatsapp');
            const btnOnline = document.getElementById('btnFinishOnline');
            
            if (btnWhatsapp && btnOnline) {
                if (method === 'whatsapp') {
                    btnWhatsapp.style.display = 'flex';
                    btnOnline.style.display = 'none';
                } else {
                    btnWhatsapp.style.display = 'none';
                    btnOnline.style.display = 'flex';
                }
            }
        }
        const STORE_SLUG = "<?= htmlspecialchars($store['slug'] ?? '') ?>";
        const STORE_ID = <?= (int)($store['id'] ?? 0) ?>;
        const API_URL = "/api/orders.php";
        const CART_KEY = CART_STORAGE_KEY;
        const IS_LOGGED_IN = <?php echo json_encode($isLoggedIn); ?>;
        // Load cart from localStorage
        // Use cart already loaded by cart.php
        function renderSummaryFromCart() {
            if (cart.length === 0) {
                showEmptyCart();
                return;
            }
            renderSummary();
            // Calcular frete automaticamente se já houver endereço selecionado
            setTimeout(() => {
                if (typeof selectedAddress !== "undefined" && selectedAddress && selectedAddress.cep) {
                    calculateCheckoutShipping(selectedAddress.cep);
                }
            }, 500);
        }

        // Render order summary
        function renderSummary() {
            const container = document.getElementById('summaryItems');
            
            if (cart.length === 0) {
                showEmptyCart();
                return;
            }

            let html = '';
            let subtotal = 0;

            cart.forEach(item => {
                const itemTotal = item.price * item.quantity;
                subtotal += itemTotal;
                
                html += `
                    <div class="summary-item">
                        <div class="summary-item-image">
                            ${item.image ? `<img src="${item.image}" alt="${item.name}">` : '<iconify-icon icon="solar:box-bold" style="font-size:2rem;color:var(--text-muted);margin:auto;"></iconify-icon>'}
                        </div>
                        <div class="summary-item-info">
                            <div class="summary-item-name">${item.name}</div>
                            <div class="summary-item-qty">Qtd: ${item.quantity}</div>
                        </div>
                        <div class="summary-item-price">R$ ${itemTotal.toFixed(2).replace('.', ',')}</div>
                        <button class="summary-item-remove" onclick="removeFromCheckout('${item.id}')" title="Remover item">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>
                    </div>
                `;
            });

            container.innerHTML = html;
            document.getElementById('subtotal').textContent = 'R$ ' + subtotal.toFixed(2).replace('.', ',');
            document.getElementById('total').textContent = 'R$ ' + subtotal.toFixed(2).replace('.', ',');
        }

        // Remove item from checkout
        function removeFromCheckout(id) {
            id = String(id);
            cart = cart.filter(item => String(item.id) !== id);
            saveCart();
            renderSummary();
            // Calcular frete automaticamente se já houver endereço selecionado
            setTimeout(() => {
                if (typeof selectedAddress !== "undefined" && selectedAddress && selectedAddress.cep) {
                    calculateCheckoutShipping(selectedAddress.cep);
                }
            }, 500);
            
            // Se o carrinho ficou vazio, redirecionar
            if (cart.length === 0) {
                showEmptyCart();
            }
        }

        // Show empty cart message
        function showEmptyCart() {
            const container = document.getElementById('summaryItems');
            container.innerHTML = `
                <div class="empty-cart">
                    <iconify-icon icon="solar:bag-cross-bold"></iconify-icon>
                    <h3>Carrinho vazio</h3>
                    <p>Adicione produtos para continuar</p>
                    <a href="<?php echo $baseUrl; ?>" class="btn-back-store">
                        <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                        Voltar à loja
                    </a>
                </div>
            `;
            const finBtn = document.getElementById('btnFinishWhatsapp') || document.getElementById('btnFinishOnline'); if(finBtn) finBtn.disabled = true;
        }

        // Select saved address
        function selectAddress(element, addr) {
            document.querySelectorAll('.address-option').forEach(el => el.classList.remove('selected'));
            element.classList.add('selected');
            selectedAddress = addr;
            // Calcular frete automaticamente quando endereço é selecionado
            if (addr && addr.cep) {
                calculateCheckoutShipping(addr.cep);
            }
            document.getElementById('newAddressForm').style.display = 'none';
        }

        // Show new address form
        function showNewAddressForm() {
            document.querySelectorAll('.address-option').forEach(el => el.classList.remove('selected'));
            const addNew = document.querySelector('.address-option.add-new');
            if (addNew) addNew.classList.add('selected');
            document.getElementById('newAddressForm').style.display = 'block';
            selectedAddress = null;
        }

        // Search CEP
        async function searchCep(cep) {
            cep = cep.replace(/\D/g, '');
            if (cep.length !== 8) return;

            try {
                const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
                const data = await response.json();
                if (!data.erro) {
                    document.getElementById('street').value = data.logradouro || '';
                    document.getElementById('neighborhood').value = data.bairro || '';
                    document.getElementById('city').value = data.localidade || '';
                    document.getElementById('state').value = data.uf || '';
                    document.getElementById('number').focus();
                }
            } catch (e) {
                console.error('Erro CEP:', e);
            }
        }

        // Get formatted address from form
        function getFormattedAddress() {
            if (selectedAddress) {
                let addr = selectedAddress.street + ', ' + selectedAddress.number;
                if (selectedAddress.complement) addr += ' - ' + selectedAddress.complement;
                addr += ' - ' + selectedAddress.neighborhood + ', ' + selectedAddress.city + '/' + selectedAddress.state;
                addr += ' - CEP: ' + selectedAddress.cep.substring(0,5) + '-' + selectedAddress.cep.substring(5);
                return addr;
            }

            const street = document.getElementById('street').value;
            const number = document.getElementById('number').value;
            const complement = document.getElementById('complement').value;
            const neighborhood = document.getElementById('neighborhood').value;
            const city = document.getElementById('city').value;
            const state = document.getElementById('state').value;
            const cep = document.getElementById('cep').value;

            if (!street || !number) return '';

            let addr = street + ', ' + number;
            if (complement) addr += ' - ' + complement;
            addr += ' - ' + neighborhood + ', ' + city + '/' + state;
            if (cep) addr += ' - CEP: ' + cep;
            return addr;
        }

        // Show toast
        function showToast(message, type = 'info') {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.className = 'toast ' + type + ' show';
            setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }

        // Finish order
        async function finishOrder(paymentMethod = 'whatsapp') {
            const nameEl = document.getElementById('customer_name');
            const phoneEl = document.getElementById('customer_phone');
            const emailEl = document.getElementById('customer_email');
            const notesEl = document.getElementById('notes');
            
            const name = nameEl ? nameEl.value.trim() : '';
            const phone = phoneEl ? phoneEl.value.trim() : '';
            const email = emailEl ? emailEl.value.trim() : '';
            const address = getFormattedAddress();
            const notes = notesEl ? notesEl.value.trim() : '';

            // Validations
            if (!name) {
                showToast('Por favor, informe seu nome.', 'error');
                if(nameEl) nameEl.focus();
                return;
            }

            if (!phone || phone.replace(/\D/g, '').length < 10) {
                showToast('Por favor, informe um telefone válido.', 'error');
                if(phoneEl) phoneEl.focus();
                return;
            }

            if (!address) {
                showToast('Por favor, preencha o endereço de entrega.', 'error');
                return;
            }

            const btn = document.getElementById(paymentMethod === 'online' ? 'btnFinishOnline' : 'btnFinishWhatsapp') || document.getElementById('btnFinishWhatsapp');
            btn.disabled = true;
            btn.innerHTML = '<iconify-icon icon="svg-spinners:ring-resize"></iconify-icon> Processando...';

            try {
                const response = await fetch(API_URL + '?action=create&store_id=' + STORE_ID, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        items: cart,
                        customer_name: name,
                        customer_phone: phone.replace(/\D/g, ''),
                        customer_email: email,
                        delivery_address: address,
                        notes: notes,
                        store_id: STORE_ID,
                        payment_method: paymentMethod
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // Notificação enviada? Não redirecionar.
                    if (data.notification_sent) {
                        document.getElementById('orderNumber').textContent = data.order_id;
                        document.getElementById('successModal').classList.add('active');
                        cart = [];
                        localStorage.removeItem(CART_KEY);
                        if (document.getElementById('whatsappRedirect')) {
                            document.getElementById('whatsappRedirect').style.display = 'none';
                        }
                        if (document.getElementById('notificationSent')) {
                            document.getElementById('notificationSent').style.display = 'block';
                        showTrackingLink(data.tracking_token);
                        }
                        return;
                    }
                    
                    // Se pagamento online, criar checkout Mercado Pago
                    if (paymentMethod === 'online') {
                        btn.innerHTML = '<iconify-icon icon="svg-spinners:ring-resize"></iconify-icon> Redirecionando para pagamento...';
                        
                        // Chamar API para criar checkout MP
                        const checkoutResponse = await fetch('/api/store-checkout.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({
                                store_id: STORE_ID,
                                order_id: data.order_id,
                                items: cart,
                                total: cart.reduce((sum, item) => sum + (item.price * item.quantity), 0),
                                customer: {
                                    name: name,
                                    email: email,
                                    phone: phone
                                }
                            })
                        });
                        
                        const checkoutData = await checkoutResponse.json();
                        
                        if (checkoutData.success && checkoutData.checkout_url) {
                            document.getElementById('orderNumber').textContent = data.order_id;
                            cart = [];
                            localStorage.removeItem(CART_KEY);
                            // Redirecionar para Mercado Pago
                            window.location.href = checkoutData.checkout_url;
                            return;
                        } else {
                            showToast(checkoutData.error || 'Erro ao criar pagamento', 'error');
                            return;
                        }
                    }
                    // Se Notificação não foi enviada (Modo API Send ou falha)
                    // Montar URL do WhatsApp client-side para preservar emojis/Unicode
                    const waPhone = data.whatsapp_phone || '';
                    const waMessage = data.whatsapp_message || '';
                    const waUrl = 'https://api.whatsapp.com/send?phone=' + waPhone + '&text=' + encodeURIComponent(waMessage);
                    
                    console.log('WA MESSAGE RAW:', waMessage);
                    console.log('WA URL:', waUrl);

                    pendingWhatsAppUrl = waUrl;
                    
                    document.getElementById('orderNumber').textContent = data.order_id;
                    document.getElementById('successModal').classList.add('active');
                    cart = [];
                    localStorage.removeItem(CART_KEY);
                    if (document.getElementById('whatsappRedirect')) {
                        document.getElementById('whatsappRedirect').style.display = 'block';
                    }
                    if (document.getElementById('notificationSent')) {
                        document.getElementById('notificationSent').style.display = 'none';
                    }
                    showTrackingLink(data.tracking_token);
                    
                    // Abrir WhatsApp Web/App em nova aba automaticamente
                    setTimeout(() => {
                        window.open(waUrl, '_blank');
                    }, 500);
                } else {
                    showToast(data.error || 'Erro ao criar pedido', 'error');
                }
            } catch (error) {
                console.error('Erro:', error);
                showToast('Erro de conexão. Tente novamente.', 'error');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<iconify-icon icon="logos:whatsapp-icon"></iconify-icon> Enviar Pedido via WhatsApp';
            }
        }

        // Redirect to WhatsApp
        // Função para exibir link de acompanhamento do pedido (guests)
        function showTrackingLink(token) {
            if (token && document.getElementById('orderTrackingLink') && document.getElementById('trackingUrl')) {
                const baseUrl = window.location.origin;
                const trackingUrl = baseUrl + '/meu-pedido/' + token;
                document.getElementById('trackingUrl').href = trackingUrl;
                document.getElementById('orderTrackingLink').style.display = 'block';
            }
        }

        function redirectToWhatsApp() {
            if (pendingWhatsAppUrl) {
                window.location.href = pendingWhatsAppUrl;
            }
        }

        // Masks and events
        document.addEventListener('DOMContentLoaded', function() {
            renderSummary();
            // Calcular frete automaticamente se já houver endereço selecionado
            setTimeout(() => {
                if (typeof selectedAddress !== "undefined" && selectedAddress && selectedAddress.cep) {
                    calculateCheckoutShipping(selectedAddress.cep);
                }
            }, 500);

            // Phone mask
            const phoneInput = document.getElementById('customer_phone');
            if (phoneInput) {
            phoneInput.addEventListener('input', function(e) {
                let v = e.target.value.replace(/\D/g, '');
                if (v.length > 11) v = v.substring(0, 11);
                if (v.length > 6) {
                    v = '(' + v.substring(0,2) + ') ' + v.substring(2,7) + '-' + v.substring(7);
                } else if (v.length > 2) {
                    v = '(' + v.substring(0,2) + ') ' + v.substring(2);
                } else if (v.length > 0) {
                    v = '(' + v;
                }
                e.target.value = v;
            });

            }
            // CEP mask and search
            const cepInput = document.getElementById('cep');
            if (cepInput) {
                cepInput.addEventListener('input', function(e) {
                    let v = e.target.value.replace(/\D/g, '');
                    if (v.length > 5) v = v.substring(0,5) + '-' + v.substring(5,8);
                    e.target.value = v;
                });
                cepInput.addEventListener('blur', function(e) {
                    searchCep(e.target.value);
                });
            }

            // Initialize selected address
            <?php if ($isLoggedIn && !empty($customerAddresses)): ?>
            const defaultAddr = document.querySelector('.address-option.selected');
            if (defaultAddr) {
                const addr = <?php echo json_encode($customerAddresses[0]); ?>;
                selectedAddress = addr;
            // Calcular frete automaticamente quando endereço é selecionado
            if (addr && addr.cep) {
                calculateCheckoutShipping(addr.cep);
            }
            }
            <?php endif; ?>
        });

        // Auth functions
        function showAuthTab(tab) {
            const tabs = document.querySelectorAll(".auth-tab");
            document.querySelectorAll(".auth-form").forEach(f => f.style.display = "none");
            tabs.forEach(t => t.classList.remove("active"));
            
            if (tab === "login") {
                if(tabs[0]) tabs[0].classList.add("active");
                const lf = document.getElementById("loginForm"); if(lf) lf.style.display = "block";
            } else if (tab === "register") {
                if(tabs[1]) tabs[1].classList.add("active");
                const rf = document.getElementById("registerForm"); if(rf) rf.style.display = "block";
            } else if (tab === "guest") {
                if(tabs[2]) tabs[2].classList.add("active");
                const gf = document.getElementById("guestForm"); if(gf) gf.style.display = "block";
            }
            const ae = document.getElementById("authError"); if(ae) ae.style.display = "none";
            return; // early return
        }
        function showAuthTab_OLD(tab_OLD) {
            document.querySelectorAll('.auth-tab').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.auth-form').forEach(f => f.style.display = 'none');
            
            if (tab === 'login') {
                document.querySelector('.auth-tab:first-child').classList.add('active');
                document.getElementById('loginForm').style.display = 'block';
            } else {
                document.querySelector('.auth-tab:last-child').classList.add('active');
                document.getElementById('registerForm').style.display = 'block';
            }
            document.getElementById('authError').style.display = 'none';
        }


        // Buscar CEP para convidado
        async function searchGuestCep() {
            const cepInput = document.getElementById("guest_cep");
            if (!cepInput) return;
            const cep = cepInput.value.replace(/\D/g, "");
            if (cep.length !== 8) return;
            
            try {
                const resp = await fetch("https://viacep.com.br/ws/" + cep + "/json/");
                const data = await resp.json();
                if (!data.erro) {
                    const street = document.getElementById("guest_street");
                    const neighborhood = document.getElementById("guest_neighborhood");
                    const city = document.getElementById("guest_city");
                    const state = document.getElementById("guest_state");
                    if (street) street.value = data.logradouro || "";
                    if (neighborhood) neighborhood.value = data.bairro || "";
                    if (city) city.value = data.localidade || "";
                    if (state) state.value = data.uf || "";
                }
            } catch(e) { console.log("Erro ao buscar CEP:", e); }
        }

        // Processar checkout como convidado
        let isGuestCheckout = false;
        let guestData = null;
        
        async function handleGuestCheckout(e) {
            e.preventDefault();
            
            // Coletar dados do formulário
            guestData = {
                name: document.getElementById("guest_name")?.value?.trim() || "",
                phone: document.getElementById("guest_phone")?.value?.trim() || "",
                email: document.getElementById("guest_email")?.value?.trim() || "",
                address: {
                    cep: document.getElementById("guest_cep")?.value?.replace(/\D/g, "") || "",
                    street: document.getElementById("guest_street")?.value?.trim() || "",
                    number: document.getElementById("guest_number")?.value?.trim() || "",
                    complement: document.getElementById("guest_complement")?.value?.trim() || "",
                    neighborhood: document.getElementById("guest_neighborhood")?.value?.trim() || "",
                    city: document.getElementById("guest_city")?.value?.trim() || "",
                    state: document.getElementById("guest_state")?.value || ""
                }
            };
            
            // Validar campos obrigatórios
            if (!guestData.name || !guestData.phone || !guestData.address.cep || !guestData.address.number) {
                showToast("Preencha todos os campos obrigatórios", "error");
                return false;
            }
            
            // Marcar como guest checkout
            isGuestCheckout = true;
            
            // Definir selectedAddress para cálculo de frete
            selectedAddress = guestData.address;
            
            // Ocultar seção de login e mostrar checkout
            const loginSection = document.querySelector(".login-required-section");
            if (loginSection) loginSection.style.display = "none";
            
            // Criar e mostrar seção de checkout para guest
            showGuestCheckoutForm();
            
            // Calcular frete
            if (guestData.address.cep) {
                calculateCheckoutShipping(guestData.address.cep);
            }
            
            return false;
        }
        
        function showGuestCheckoutForm() {
            // Criar breadcrumb e formulário para guest
            const loginSection = document.querySelector(".login-required-section");
            if (!loginSection) return;
            
            loginSection.outerHTML = `
                <nav class="checkout-breadcrumb">
                    <a href="${typeof baseUrl !== "undefined" ? baseUrl : ""}">
                        <iconify-icon icon="solar:home-2-bold"></iconify-icon>
                    </a>
                    <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
                    <span>Carrinho</span>
                    <iconify-icon icon="solar:alt-arrow-right-linear"></iconify-icon>
                    <span class="current">Finalizar Pedido</span>
                </nav>
                
                <h1 class="checkout-title">
                    <iconify-icon icon="solar:bag-check-bold"></iconify-icon>
                    Finalizar Pedido
                </h1>
                
                <div class="checkout-card">
                    <div class="checkout-card-header">
                        <iconify-icon icon="solar:user-bold"></iconify-icon>
                        <h2>Seus Dados</h2>
                    </div>
                    <div class="checkout-card-body">
                        <div class="form-group">
                            <label>Nome Completo *</label>
                            <input type="text" id="customer_name" class="form-control" value="${guestData.name}" readonly style="background: #f5f5f5;">
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label>WhatsApp *</label>
                                <input type="tel" id="customer_phone" class="form-control" value="${guestData.phone}" readonly style="background: #f5f5f5;">
                            </div>
                            <div class="form-group">
                                <label>E-mail</label>
                                <input type="email" id="customer_email" class="form-control" value="${guestData.email || ""}" readonly style="background: #f5f5f5;">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="checkout-card">
                    <div class="checkout-card-header">
                        <iconify-icon icon="solar:map-point-bold"></iconify-icon>
                        <h2>Endereço de Entrega</h2>
                    </div>
                    <div class="checkout-card-body">
                        <div class="address-display" style="background: var(--bg, #f9fafb); padding: 1rem; border-radius: 10px; border: 1px solid var(--border-color, #e5e7eb);">
                            <strong>${guestData.address.street}, ${guestData.address.number}</strong>
                            ${guestData.address.complement ? " - " + guestData.address.complement : ""}<br>
                            ${guestData.address.neighborhood}, ${guestData.address.city}/${guestData.address.state}<br>
                            CEP: ${guestData.address.cep.substring(0,5)}-${guestData.address.cep.substring(5)}
                        </div>
                    </div>
                </div>
            `;
            
            // Renderizar resumo do carrinho
            renderSummary();
        }

        function togglePassword(inputId) {
            const input = document.getElementById(inputId);
            const icon = input.nextElementSibling.querySelector('iconify-icon');
            if (input.type === 'password') {
                input.type = 'text';
                icon.setAttribute('icon', 'solar:eye-closed-bold');
            } else {
                input.type = 'password';
                icon.setAttribute('icon', 'solar:eye-bold');
            }
        }

        function showAuthError(message) {
            const errorDiv = document.getElementById('authError');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        async function handleLogin(event) {
            event.preventDefault();
            const identifier = document.getElementById('login_identifier').value;
            const password = document.getElementById('login_password').value;
            const btn = event.target.querySelector('button[type="submit"]');
            const originalText = btn.innerHTML;
            
            btn.innerHTML = '<iconify-icon icon="solar:spinner-bold" class="spin"></iconify-icon> Entrando...';
            btn.disabled = true;

            try {
                const response = await fetch('/api/customer/login.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        identifier: identifier,
                        password: password,
                        store_id: STORE_ID
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showToast('Login realizado com sucesso!', 'success');
                    setTimeout(() => location.reload(), 500);
                } else {
                    showAuthError(data.message || 'E-mail/WhatsApp ou senha incorretos');
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            } catch (error) {
                showAuthError('Erro ao conectar. Tente novamente.');
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
            return false;
        }

        async function handleRegister(event) {
            event.preventDefault();
            
            const password = document.getElementById('register_password').value;
            const passwordConfirm = document.getElementById('register_password_confirm').value;
            
            if (password !== passwordConfirm) {
                showAuthError('As senhas não conferem');
                return false;
            }

            const btn = event.target.querySelector('button[type="submit"]');
            const originalText = btn.innerHTML;
            
            btn.innerHTML = '<iconify-icon icon="solar:spinner-bold" class="spin"></iconify-icon> Criando conta...';
            btn.disabled = true;

            const formData = {
                name: document.getElementById('register_name').value,
                phone: document.getElementById('register_phone').value.replace(/\D/g, ''),
                email: document.getElementById('register_email').value,
                password: password,
                store_id: STORE_ID,
                address: {
                    cep: document.getElementById('register_cep').value.replace(/\D/g, ''),
                    street: document.getElementById('register_street').value,
                    number: document.getElementById('register_number').value,
                    complement: document.getElementById('register_complement').value,
                    neighborhood: document.getElementById('register_neighborhood').value,
                    city: document.getElementById('register_city').value,
                    state: document.getElementById('register_state').value
                }
            };

            try {
                const response = await fetch('/api/customer/register.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showToast('Conta criada com sucesso!', 'success');
                    setTimeout(() => location.reload(), 500);
                } else {
                    showAuthError(data.message || 'Erro ao criar conta. Tente novamente.');
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                }
            } catch (error) {
                showAuthError('Erro ao conectar. Tente novamente.');
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
            return false;
        }

        // CEP search for register form
        document.getElementById('register_cep')?.addEventListener('blur', async function() {
            const cep = this.value.replace(/\D/g, '');
            if (cep.length !== 8) return;

            try {
                const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`);
                const data = await response.json();
                
                if (!data.erro) {
                    document.getElementById('register_street').value = data.logradouro || '';
                    document.getElementById('register_neighborhood').value = data.bairro || '';
                    document.getElementById('register_city').value = data.localidade || '';
                    document.getElementById('register_state').value = data.uf || '';
                    document.getElementById('register_number').focus();
                }
            } catch (e) {}
        });

        // Phone mask for register
        document.getElementById('register_phone')?.addEventListener('input', function(e) {
            let v = e.target.value.replace(/\D/g, '');
            if (v.length > 11) v = v.substring(0, 11);
            if (v.length > 6) {
                v = '(' + v.substring(0,2) + ') ' + v.substring(2,7) + '-' + v.substring(7);
            } else if (v.length > 2) {
                v = '(' + v.substring(0,2) + ') ' + v.substring(2);
            } else if (v.length > 0) {
                v = '(' + v;
            }
            e.target.value = v;
        });

        // CEP mask for register
        document.getElementById('register_cep')?.addEventListener('input', function(e) {
            let v = e.target.value.replace(/\D/g, '');
            if (v.length > 5) {
                v = v.substring(0,5) + '-' + v.substring(5,8);
            }
            e.target.value = v;
        });

// ========== SISTEMA DE FRETE CHECKOUT ==========
let shippingOptions = [];

// Função para obter itens do carrinho (usa variável global cart)
function getCartItems() {
    if (typeof cart !== 'undefined' && Array.isArray(cart)) {
        return cart;
    }
    // Fallback: tentar ler do localStorage
    try {
        const stored = localStorage.getItem(CART_KEY || 'cart');
        return stored ? JSON.parse(stored) : [];
    } catch(e) {
        return [];
    }
}

function calculateCheckoutShipping(zipcode) {
    if (!zipcode || zipcode.replace(/\D/g, "").length !== 8) return;
    
    const cleanZip = zipcode.replace(/\D/g, "");
    const cartItems = getCartItems();
    if (cartItems.length === 0) return;
    
    const optionsDiv = document.getElementById("shippingOptionsCheckout");
    optionsDiv.innerHTML = '<div style="text-align: center; padding: 0.5rem;"><iconify-icon icon="svg-spinners:ring-resize"></iconify-icon> Calculando frete...</div>';
    
    fetch("/api/shipping/calculate.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            store_id: STORE_ID,
            items: cartItems.map(i => ({ product_id: i.id, quantity: i.quantity })),
            zipcode: cleanZip,
            cart_total: parseFloat(document.getElementById("subtotal")?.textContent.replace(/[^\d,]/g, "").replace(",", ".") || 0)
        })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success && data.options && data.options.length > 0) {
            shippingOptions = data.options;
            optionsDiv.innerHTML = data.options.map((opt, idx) => `
                <label style="display: flex; align-items: center; gap: 0.75rem; padding: 0.75rem; margin-bottom: 0.5rem; background: #fff; border: 2px solid ${idx === 0 ? "var(--primary)" : "var(--border-color, #ddd)"}; border-radius: 10px; cursor: pointer; transition: all 0.2s;">
                    <input type="radio" name="shippingOption" value="${idx}" ${idx === 0 ? "checked" : ""} onchange="selectShipping(${idx})" style="width: 18px; height: 18px;">
                    <div style="flex: 1;">
                        <strong>${opt.carrier}${opt.service ? " - " + opt.service : ""}</strong>
                        <div style="font-size: 0.85rem; color: #666;">${opt.delivery_time || opt.min_days + " a " + opt.max_days + " dias"}</div>
                    </div>
                    <div style="font-weight: 600; color: ${opt.price === 0 ? "#10b981" : "var(--primary)"};">
                        ${opt.price === 0 ? "Grátis" : "R$ " + opt.price.toFixed(2).replace(".", ",")}
                    </div>
                </label>
            `).join("");
            selectShipping(0);
        } else {
            optionsDiv.innerHTML = '<p style="color: #666; font-size: 0.9rem; margin: 0;">Nenhuma opção disponível para este CEP.</p>';
            document.getElementById("shipping").textContent = "Indisponível";
        }
    })
    .catch(err => {
        console.error("Shipping error:", err);
        optionsDiv.innerHTML = '<p style="color: #ef4444;">Erro ao calcular frete.</p>';
    });
}

function selectShipping(idx) {
    const opt = shippingOptions[idx];
    if (!opt) return;
    document.getElementById("selectedShippingMethod").value = opt.carrier + (opt.service ? " - " + opt.service : "");
    document.getElementById("selectedShippingCost").value = opt.price;
    document.getElementById("selectedShippingDays").value = opt.delivery_time || opt.min_days + " a " + opt.max_days + " dias";
    document.getElementById("shipping").textContent = opt.price === 0 ? "Grátis" : "R$ " + opt.price.toFixed(2).replace(".", ",");
    document.querySelectorAll("#shippingOptionsCheckout label").forEach((lbl, i) => {
        lbl.style.borderColor = i === idx ? "var(--primary)" : "var(--border-color, #ddd)";
    });
    updateTotal();
}

function updateTotal() {
    const subtotalEl = document.getElementById("subtotal");
    const shippingCost = parseFloat(document.getElementById("selectedShippingCost")?.value || 0);
    const subtotal = parseFloat(subtotalEl?.textContent.replace(/[^\d,]/g, "").replace(",", ".") || 0);
    const total = subtotal + shippingCost;
    document.getElementById("total").textContent = "R$ " + total.toFixed(2).replace(".", ",");
}

// Hook: quando CEP muda, calcular frete
["register_cep", "cep"].forEach(id => {
    const el = document.getElementById(id);
    if (el) {
        el.addEventListener("blur", function() {
            calculateCheckoutShipping(this.value);
        });
        // Se já tiver valor, calcular
        if (el.value && el.value.replace(/\D/g, "").length === 8) {
            setTimeout(() => calculateCheckoutShipping(el.value), 500);
        }
    }
});
    </script>
</body>
</html>
