<?php
// ======================================
// = INÍCIO DO ARQUIVO index.php        =
// ======================================

// Configurações de Erro (Ideal para Produção)
ini_set('display_errors', 0); // Não mostrar erros ao utilizador
ini_set('log_errors', 1);     // Logar erros num arquivo
// ini_set('error_log', '/path/to/your/php-error.log'); // Definir caminho do log

// session_start(); // Descomente se precisar de sessões

// ======================================
// = Configuração Segura do Banco de Dados =
// ======================================
$hostname = 'localhost';
$username = 'u966280798_grow';
$password = '2425@Zoom';
$database = 'u966280798_grow';

// Conexão com o Banco de Dados
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
    error_log("DB Connection Error: " . $conn->connect_error);
    header('Content-Type: application/json');
    die(json_encode(['status' => 'error', 'message' => 'Não foi possível ligar ao servidor. Tente mais tarde.']));
}
$conn->set_charset("utf8mb4");

// Função para sanitizar entrada (para XSS, não SQLi)
function sanitize_input($data) {
    return htmlspecialchars(trim(preg_replace('/\s+/', ' ', $data)), ENT_QUOTES, 'UTF-8');
}

// Função para normalizar número de telemóvel (mantida)
function normalize_phone($phone) {
    $phone = preg_replace('/[^\d+]/', '', $phone);
    if (substr($phone, 0, 2) === '00') { $phone = '+' . substr($phone, 2); }
    if (strlen($phone) > 9 && substr($phone, 0, 3) === '351' && substr($phone, 0, 1) !== '+') { $phone = '+' . $phone; }
    $phone = preg_replace('/[^\d+]/', '', $phone);
    if (strpos($phone, '00351') === 0) { $phone = '+351' . substr($phone, 5); }
    if (strlen($phone) === 12 && strpos($phone, '351') === 0 && substr($phone, 0, 1) !== '+') { $phone = '+' . $phone; }
    if (strlen($phone) === 9 && substr($phone, 0, 1) !== '+' && preg_match('/^[29]\d{8}$/', $phone)) { $phone = '+351' . $phone; }
    if (substr($phone, 0, 4) !== '+351' && strlen($phone) >= 9) {
        if (substr($phone, 0, 3) === '351') { $phone = '+' . $phone; }
    }
    $phone = str_replace(' ', '', $phone);
    return $phone;
}

// Função segura para mover lead para reserva e apagar da principal
function move_and_delete_lead($conn, $criteria_col, $criteria_val, $criteria_type = "s") {
    $allowed_columns = ['temp_id', 'phonenumber', 'name_address'];
    if (!in_array($criteria_col, $allowed_columns)) {
        error_log("Tentativa de usar coluna não permitida em move_and_delete_lead: " . $criteria_col);
        return false;
    }
    $conn->begin_transaction();
    try {
        $sql_insert_reserve = ""; $sql_delete_lead = ""; $params = []; $types = "";
        if ($criteria_col === 'name_address') {
            if (!is_array($criteria_val) || count($criteria_val) !== 2) throw new Exception("Critério 'name_address' requer um array com nome e morada.");
            $sql_insert_reserve = "INSERT INTO tblleads_reserve (temp_id, name, phonenumber, address, dateadded, lead_status, product, product_color) SELECT temp_id, name, phonenumber, address, dateadded, lead_status, product, product_color FROM tblleads WHERE name = ? AND address = ?";
            $sql_delete_lead = "DELETE FROM tblleads WHERE name = ? AND address = ?";
            $params = $criteria_val; $types = "ss";
        } else {
            $sql_insert_reserve = "INSERT INTO tblleads_reserve (temp_id, name, phonenumber, address, dateadded, lead_status, product, product_color) SELECT temp_id, name, phonenumber, address, dateadded, lead_status, product, product_color FROM tblleads WHERE {$criteria_col} = ?";
            $sql_delete_lead = "DELETE FROM tblleads WHERE {$criteria_col} = ?";
            $params = [$criteria_val]; $types = $criteria_type;
        }
        $stmt_insert = $conn->prepare($sql_insert_reserve);
        if ($stmt_insert === false) throw new Exception("Prepare failed (INSERT RESERVE): " . $conn->error);
        if (!empty($types)) $stmt_insert->bind_param($types, ...$params);
        if (!$stmt_insert->execute()) throw new Exception("Execute failed (INSERT RESERVE): " . $stmt_insert->error);
        $stmt_insert->close();
        $stmt_delete = $conn->prepare($sql_delete_lead);
        if ($stmt_delete === false) throw new Exception("Prepare failed (DELETE LEAD): " . $conn->error);
        if (!empty($types)) $stmt_delete->bind_param($types, ...$params);
        if (!$stmt_delete->execute()) throw new Exception("Execute failed (DELETE LEAD): " . $stmt_delete->error);
        $stmt_delete->close();
        $conn->commit();
        return true;
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Error moving/deleting lead ({$criteria_col}): " . $e->getMessage());
        return false;
    }
}

// ======================================
// = Tratamento de Requisições POST     =
// ======================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');

    // Salvamento "EM TEMPO REAL" (incompleto)
    if (isset($_POST['realTime']) && $_POST['realTime'] === '1') {
        $temp_id = sanitize_input($_POST['tempId'] ?? '');
        if (empty($temp_id) || strlen($temp_id) < 5) $temp_id = uniqid('user_');
        $nome = sanitize_input($_POST['nome'] ?? '');
        $telemovel_raw = sanitize_input($_POST['telemovel'] ?? '');
        $morada = sanitize_input($_POST['morada'] ?? '');
        $product = sanitize_input($_POST['product'] ?? 'Relógio Telemóvel com Câmara');
        $product_color = sanitize_input($_POST['product_color'] ?? '');
        $telemovel = preg_match('/\d/', $telemovel_raw) ? normalize_phone($telemovel_raw) : '';
        $db_nome = ($nome === '') ? 'Nome pendente...' : $nome;
        $db_morada = ($morada === '') ? 'Morada pendente...' : $morada;
        $db_telemovel = $telemovel ?: '';
        $stmt_check = $conn->prepare("SELECT id FROM tblleads WHERE temp_id = ?");
        if ($stmt_check) {
            $stmt_check->bind_param("s", $temp_id); $stmt_check->execute(); $result = $stmt_check->get_result(); $stmt_check->close();
            if ($result->num_rows > 0) {
                $updateStmt = $conn->prepare("UPDATE tblleads SET name = ?, phonenumber = ?, address = ?, product = ?, product_color = ?, dateadded = NOW(), lead_status = 'incompleto' WHERE temp_id = ?");
                if($updateStmt) { $updateStmt->bind_param("ssssss", $db_nome, $db_telemovel, $db_morada, $product, $product_color, $temp_id); if (!$updateStmt->execute()) { error_log("Execute failed (Update Realtime): " . $updateStmt->error); } $updateStmt->close(); }
            } else {
                $insertStmt = $conn->prepare("INSERT INTO tblleads (temp_id, name, phonenumber, address, product, product_color, dateadded, lead_status) VALUES (?, ?, ?, ?, ?, ?, NOW(), 'incompleto')");
                if($insertStmt) { $insertStmt->bind_param("ssssss", $temp_id, $db_nome, $db_telemovel, $db_morada, $product, $product_color); if (!$insertStmt->execute()) { error_log("Execute failed (Insert Realtime): " . $insertStmt->error); } $insertStmt->close(); }
            }
        }
        echo json_encode(['status' => 'partial_saved', 'temp_id' => $temp_id]);
        $conn->close();
        exit;
    }

    // Submissão FINAL (com validação e bloqueio SEGUROS)
    if (isset($_POST['ajax']) && $_POST['ajax'] === '1') {
        $temp_id = sanitize_input($_POST['tempId'] ?? '');
        $nome = sanitize_input($_POST['nome'] ?? '');
        $telemovel_raw = sanitize_input($_POST['telemovel'] ?? '');
        $morada = sanitize_input($_POST['morada'] ?? '');
        $product = sanitize_input($_POST['product'] ?? 'Relógio Telemóvel com Câmara');
        $product_color = sanitize_input($_POST['product_color'] ?? '');
        $errors = [];
        if (empty($nome)) $errors[] = "O campo Nome é obrigatório.";
        if (empty($telemovel_raw)) $errors[] = "O campo Telemóvel é obrigatório.";
        if (empty($morada)) $errors[] = "O campo Morada é obrigatório.";
        if (empty($product_color)) $errors[] = "Por favor, escolha a cor do relógio.";
        $allowed_colors = ['Preto', 'Prata', 'Rosa', 'Branco'];
        if (!empty($product_color) && !in_array($product_color, $allowed_colors)) $errors[] = "A cor selecionada não é válida.";
        $telemovel_normalizado = '';
        if (!empty($telemovel_raw)) {
            $telemovel_normalizado = normalize_phone($telemovel_raw);
            $pattern_pt = "/^\+?351(9[1236]\d{7}|2\d{8})$/";
            if (!preg_match($pattern_pt, $telemovel_normalizado)) $errors[] = 'O número de telemóvel não parece válido. Confirme se é um número português (9 dígitos ou +351...).';
        }
        if (!empty($errors)) { echo json_encode(['status' => 'error', 'message' => implode("<br>", $errors)]); $conn->close(); exit; }

        $redirect_url = null;
        $blacklistWords = [ "gatuno", "gatunos", "gatona", "gatonas", "burla", "burlar", "vigarizado", "ladrão", "ladrões", "roubo", "fraude", "farsante", "trapaceiro", "impostor", "charlatão", "teste", "testando" ];
        $textToCheck = mb_strtolower($nome . ' ' . $morada, 'UTF-8');
        foreach ($blacklistWords as $badWord) {
            if (strpos($textToCheck, $badWord) !== false) {
                $criteria_col = !empty($temp_id) ? 'temp_id' : 'name_address'; $criteria_val = !empty($temp_id) ? $temp_id : [$nome, $morada]; $type = !empty($temp_id) ? 's' : '';
                move_and_delete_lead($conn, $criteria_col, $criteria_val, $type);
                $redirect_url = 'https://www.google.pt'; break;
            }
        }
        if ($redirect_url === null) {
            $checkPhoneStmt = $conn->prepare("SELECT id FROM tblleads WHERE phonenumber = ? AND lead_status = 'completo'");
            if ($checkPhoneStmt) {
                $checkPhoneStmt->bind_param("s", $telemovel_normalizado); $checkPhoneStmt->execute(); $phoneResult = $checkPhoneStmt->get_result(); $checkPhoneStmt->close();
                if ($phoneResult->num_rows > 0) {
                    $criteria_col = !empty($temp_id) ? 'temp_id' : 'phonenumber'; $criteria_val = !empty($temp_id) ? $temp_id : $telemovel_normalizado;
                    move_and_delete_lead($conn, $criteria_col, $criteria_val, 's');
                    $redirect_url = 'https://www.google.pt';
                }
            } else { error_log("Prepare failed (Check Phone Dupe): " . $conn->error); }
        }
        if ($redirect_url !== null) { echo json_encode(['status' => 'redirect', 'url' => $redirect_url]); $conn->close(); exit; }

        $morada_lower = mb_strtolower($morada, 'UTF-8');
        $valor_texto = "40,00€"; $purchase_value = 40.00; $local_entrega = "Portugal Continental";
        $ilhas_keywords = ['madeira', 'açores', 'acores', 'funchal', 'ponta delgada', 'horta', 'angra do heroísmo', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99'];
        $cp_match = preg_match('/(?:\s|^)(\d{4})-\d{3}(?:\s|$)/', $morada, $cp_matches); $cp_prefix = $cp_match ? substr($cp_matches[1], 0, 2) : '';
        foreach ($ilhas_keywords as $keyword) {
            if (strpos($morada_lower, $keyword) !== false || ($cp_prefix !== '' && $cp_prefix >= '90' && $cp_prefix <= '99')) {
                $valor_texto = "40,00€"; $purchase_value = 40.00; $local_entrega = "Portugal Continental"; break;
            }
        }

        $success = false;
        if (!empty($temp_id)) {
            $checkStmt = $conn->prepare("SELECT id FROM tblleads WHERE temp_id = ?"); $checkStmt->bind_param("s", $temp_id); $checkStmt->execute(); $result = $checkStmt->get_result(); $checkStmt->close();
            if ($result->num_rows > 0) {
                $updateFinal = $conn->prepare("UPDATE tblleads SET name = ?, phonenumber = ?, address = ?, dateadded = NOW(), lead_status = 'completo', product = ?, product_color = ? WHERE temp_id = ?");
                $updateFinal->bind_param("ssssss", $nome, $telemovel_normalizado, $morada, $product, $product_color, $temp_id);
                if($updateFinal->execute()){ $success = true; } else { error_log("Update final failed: " . $updateFinal->error); } $updateFinal->close();
            } else {
                $insertFinal = $conn->prepare("INSERT INTO tblleads (temp_id, name, phonenumber, address, dateadded, lead_status, product, product_color) VALUES (?, ?, ?, ?, NOW(), 'completo', ?, ?)");
                $insertFinal->bind_param("ssssss", $temp_id, $nome, $telemovel_normalizado, $morada, $product, $product_color);
                if($insertFinal->execute()){ $success = true; } else { error_log("Insert final (fallback) failed: " . $insertFinal->error); } $insertFinal->close();
            }
        } else {
            $stmt = $conn->prepare("INSERT INTO tblleads (name, phonenumber, address, dateadded, lead_status, product, product_color) VALUES (?, ?, ?, NOW(), 'completo', ?, ?)");
            if ($stmt) {
                $stmt->bind_param("sssss", $nome, $telemovel_normalizado, $morada, $product, $product_color);
                if ($stmt->execute()) { $success = true; } else { error_log("Execute Insert final failed: " . $stmt->error); }
                $stmt->close();
            }
        }

        // ==============================================================
        // =           MODIFICAÇÃO PARA REDIRECIONAMENTO WHATSAPP       =
        // ==============================================================
        if ($success) {
            $product_full_name = $product . " (Cor: " . $product_color . ")";
            $delivery_days = ($local_entrega === "Portugal Continental") ? "1 a 2 dias úteis" : "7-14 dias úteis";

            echo json_encode([
                'status' => 'success',
                'product_name' => $product_full_name,
                'customer_name' => html_entity_decode($nome),
                'customer_phone' => $telemovel_normalizado,
                'customer_address' => html_entity_decode($morada),
                'final_price' => $purchase_value,
                'final_price_formatted' => $valor_texto,
                'delivery_location' => $local_entrega,
                'delivery_days' => $delivery_days,
                'tracking_id' => $temp_id
            ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Pedimos desculpa, mas ocorreu um erro inesperado ao guardar a sua encomenda. Por favor, tente novamente dentro de momentos ou contacte o nosso apoio.']);
        }
        // ==============================================================
        // =        FIM DA MODIFICAÇÃO PARA REDIRECIONAMENTO WHATSAPP   =
        // ==============================================================
        $conn->close();
        exit;
    }

    echo json_encode(['status' => 'error', 'message' => 'Tipo de pedido inválido.']);
    $conn->close();
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-PT">
<head>
  <script>
    (function(h,o,t,j,a,r){
        h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
        h._hjSettings={hjid:6427248,hjsv:6};
        a=o.getElementsByTagName('head')[0];
        r=o.createElement('script');r.async=1;
        r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
        a.appendChild(r);
    })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-NGQ46KLXMQ"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-NGQ46KLXMQ');
</script>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Relógio Telemóvel Simples com Câmara - Pague aos CTT na Entrega</title>
  <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=Lato:wght@400;700&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
  <script async src="https://www.googletagmanager.com/gtag/js?id=G-LKPRMLMLBZ"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-LKPRMLMLBZ');
  </script>

  <script>
      !function(f,b,e,v,n,t,s)
      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
      n.queue=[];t=b.createElement(e);t.async=!0;
      t.src=v;s=b.getElementsByTagName(e)[0];
      s.parentNode.insertBefore(t,s)}(window, document,'script',
      'https://connect.facebook.net/en_US/fbevents.js');

      fbq('init', '824416797355982');
      fbq('track', 'ViewContent', { content_name: 'Relógio Telemóvel com Câmara', content_category: 'Eletrónicos > Smartwatches', value: 40.00, currency: 'EUR' });
  </script>
  <noscript>
    <img height="1" width="1" style="display:none"
         src="https://www.facebook.com/tr?id=824416797355982&ev=PageView&noscript=1"
    />
  </noscript>

  <!-- 2o bloco do Meta Pixel removido -->
  <style>
    :root { --brand-success: #27ae60; --brand-danger: #c0392b; --brand-accent: #f39c12; --whatsapp-green: #25D366; }
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html { scroll-behavior: smooth; }
    body { font-family: 'Lato', 'Roboto', sans-serif; background-color: #f4f5f7; color: #333; line-height: 1.6; font-size: 17px; padding: 10px; }
    .container { max-width: 750px; margin: 20px auto; background: #ffffff; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); padding: 20px; overflow: hidden; }
    .main-header { text-align: center; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 1px solid #eee; }
    .main-header h1 { font-size: 2.0em; color: #2c3e50; font-weight: 700; margin-bottom: 8px; font-family: 'Roboto', sans-serif; line-height: 1.3; }
    .main-header .subtitle { font-size: 1.2em; color: #e74c3c; font-weight: 700; }
    .carousel-container { position: relative; max-width: 100%; margin: 0 auto 25px auto; overflow: hidden; border-radius: 6px; border: 1px solid #ddd; }
    .carousel-slide { display: none; width: 100%; }
    .carousel-slide img { width: 100%; display: block; height: auto; }
    .active-slide { display: block; animation: fadeIn 0.8s; }
    @keyframes fadeIn { from { opacity: 0.4; } to { opacity: 1; } }
    .product-info { margin-bottom: 25px; }
    .product-info h2 { font-size: 1.7em; color: #34495e; margin-bottom: 10px; font-weight: 700; }
    .product-rating { font-size: 1em; color: #555; margin-bottom: 15px; }
    .stars { color: var(--brand-accent); margin-right: 5px; font-size: 1.1em; }
    .price-delivery-section { background-color: #fff8e1; padding: 20px; border-radius: 8px; margin-bottom: 25px; text-align: center; border: 2px solid #ffcc00; display: flex; flex-direction: column; align-items: center; gap: 15px; }
    @media (min-width: 600px) { .price-delivery-section { flex-direction: row; } }
    .price-details { flex-grow: 1; text-align: center; }
    .price-details .old-price { font-size: 1.1em; text-decoration: line-through; color: #95a5a6; margin-right: 10px; }
    .price-details .new-price { font-size: 2.3em; color: #e74c3c; font-weight: 700; margin-bottom: 5px; display: block; }
    .price-details .payment-info { font-size: 1.1em; color: #333; font-weight: 700; }
    .price-details .shipping-note { font-size: 0.9em; color: #555; margin-top: 5px;}
    .delivery-partner { text-align: center; }
    .delivery-partner img { max-width: 120px; height: auto; margin-bottom: 5px; }
    .delivery-partner p { font-size: 0.9em; color: #555; font-weight: bold; }
    .urgency-info { font-size: 1.05em; color: #c0392b; font-weight: 700; margin-bottom: 25px; text-align: center; background-color: #fceae8; padding: 10px; border-radius: 6px; }
    .urgency-info #countdown, .urgency-info #stock { margin-left: 5px; color: #e74c3c;}
    .urgency-info div { margin-bottom: 5px; }
    .urgency-info i { margin-right: 5px; }
    .benefits-section { margin-bottom: 30px;}
    .benefits-section h3 { font-size: 1.6em; color: #34495e; margin-bottom: 15px; text-align: center;}
    .benefits { list-style: none; padding-left: 0; }
    .benefits li { margin-bottom: 14px; font-size: 1.15em; display: flex; align-items: center; background-color: #f8f9fa; padding: 10px; border-radius: 4px; border-left: 4px solid var(--brand-success); }
    .benefits li i { color: var(--brand-success); font-size: 1.4em; margin-right: 15px; width: 25px; text-align: center; }
    .benefits .highlight { color: #e74c3c; font-weight: 700; border-left-color: #e74c3c;}
    .benefits .highlight i { color: #e74c3c; }
    .cta-button { width: 100%; background: linear-gradient(180deg, #ff8a50, #e74c3c); color: #fff; font-weight: 700; border: none; border-radius: 8px; padding: 20px 22px; font-size: 1.4em; margin-bottom: 30px; cursor: pointer; transition: transform 0.2s ease, box-shadow 0.2s ease; box-shadow: 0 4px 15px rgba(231, 76, 60, 0.4); text-transform: uppercase; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 5px; line-height: 1.2; }
    .cta-button i { margin-right: 8px; font-size: 0.9em;}
    .cta-button:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(231, 76, 60, 0.5); }
    .cta-button:active { transform: translateY(0); box-shadow: 0 4px 15px rgba(231, 76, 60, 0.4); }
    .cta-button small { font-size: 0.6em; text-transform: none; font-weight: normal; display: block; line-height: 1.1; }
    .reviews-section { margin-bottom: 30px; }
    .reviews-section h3 { text-align: center; font-size: 1.6em; color: #34495e; margin-bottom: 15px; }
    .reviews-container { position: relative; max-width: 100%; overflow: hidden; border-radius: 6px; background: #f8f9fa; padding: 20px; border: 1px solid #eee; }
    .review-slide { display: none; width: 100%; text-align: center; }
    .review-slide p { font-size: 1.1em; line-height: 1.5; color: #444; font-style: italic; }
    .review-slide strong { color: #2c3e50; display: block; margin-top: 8px; font-style: normal; font-size: 0.95em; }
    .active-review { display: block; animation: fadeIn 0.8s; }
    .order-form-section { background: #eaf4ff; padding: 25px; border-radius: 8px; border: 1px solid #bde0ff; margin-bottom: 30px; }
    .order-form-section h3 { text-align: center; font-size: 1.6em; color: #34495e; margin-bottom: 25px; }
    .order-form-section h3 i { margin-right: 10px; }
    .temu-form .form-group { margin-bottom: 20px; }
    .temu-form label { display: block; margin-bottom: 8px; font-weight: 700; font-size: 1.1em; color: #34495e; }
    .temu-form label span { color: #e74c3c; font-weight: bold; margin-right: 3px;}
    .temu-form input[type="text"], .temu-form input[type="tel"] { width: 100%; padding: 15px; border: 1px solid #ccc; border-radius: 6px; font-size: 1.1em; font-family: 'Lato', sans-serif; }
    .temu-form input:focus { border-color: #e74c3c; box-shadow: 0 0 5px rgba(231, 76, 60, 0.3); outline: none; }
    .temu-form .form-group small { color: #555; font-size: 0.9em; display: block; margin-top: 4px;}
    .temu-form .radio-group { display: flex; flex-wrap: wrap; gap: 15px; margin-top: 10px; }
    .temu-form .radio-group label { display: flex; align-items: center; font-weight: normal; font-size: 1.05em; cursor: pointer; padding: 10px 14px; border: 1px solid #ccc; border-radius: 6px; background-color: #fff; transition: background-color 0.2s ease, border-color 0.2s ease; }
    .temu-form .radio-group label:hover { background-color: #f8f9fa; }
    .temu-form .radio-group input[type="radio"] { margin-right: 8px; transform: scale(1.3); accent-color: #e74c3c; }
    .temu-form .radio-group input[type="radio"]:checked + span { font-weight: bold; }
    .temu-form button[type="submit"] { width: 100%; background: var(--brand-success); color: #fff; border: none; border-radius: 8px; padding: 18px 22px; font-size: 1.35em; cursor: pointer; font-weight: 700; transition: background-color 0.3s ease; margin-top: 15px; display: flex; align-items: center; justify-content: center; gap: 10px; }
    .temu-form button[type="submit"]:hover { background: #2ecc71; }
    .temu-form button[type="submit"]:disabled { background-color: #95a5a6; cursor: not-allowed; }
    .loader { border: 4px solid #f3f3f3; border-top: 4px solid #fff; border-radius: 50%; width: 25px; height: 25px; animation: spin 1s linear infinite; display: inline-block; vertical-align: middle; }
    @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    .processing-indicator { display: none; }
    .processing-indicator span { margin-right: 5px; }
    .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); padding-top: 60px; }
    .modal-content { background-color: #fefefe; margin: 5% auto; padding: 30px; border: 1px solid #888; width: 85%; max-width: 500px; border-radius: 8px; text-align: center; position: relative; font-size: 1.1em; }
    .modal-content h2 { margin-top: 0; margin-bottom: 15px; font-size: 1.4em; }
    .modal-content h2 i { margin-right: 10px;}
    .modal-content p { margin-bottom: 20px; line-height: 1.5; text-align: left; }
    .modal-close-btn { color: #aaa; position: absolute; top: 10px; right: 20px; font-size: 28px; font-weight: bold; cursor: pointer; }
    .modal-close-btn:hover, .modal-close-btn:focus { color: black; text-decoration: none; }
    #error-modal h2 { color: var(--brand-danger); }
    .purchase-popup { position: fixed; bottom: 15px; left: 15px; background: rgba(44, 62, 80, 0.9); color: #fff; padding: 12px 18px; border-radius: 6px; box-shadow: 0 3px 8px rgba(0,0,0,0.3); z-index: 999; display: none; font-size: 0.95em; max-width: 280px; animation: slideInUp 0.5s forwards; }
    @keyframes slideInUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
    @keyframes fadeOutDown { from { opacity: 1; transform: translateY(0); } to { opacity: 0; transform: translateY(20px); } }
    .purchase-popup.hide { animation: fadeOutDown 0.5s forwards; }
    .footer { text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; font-size: 0.95em; color: #777; }
    .footer p { margin-bottom: 8px; line-height: 1.5; }
    .footer p i { margin-right: 5px; color: #3498db; }

    /* ESTILOS PARA TELA DE REDIRECIONAMENTO WHATSAPP */
    
    
    
    @keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.1); } }
    
    
    .redirect-countdown { font-size: 3.5em; color: var(--whatsapp-green); font-weight: 700; margin: 20px 0; display: block; }
    
    
    
    .order-summary-box { background: #f8f9fa; border-radius: 12px; padding: 20px; margin-top: 30px; text-align: left; border: 2px solid #e0e0e0; }
    .order-summary-box h3 { margin: 0 0 15px 0; font-size: 1.3em; color: #34495e; text-align: center; }
    .order-summary-box ul { list-style: none; padding: 0; margin: 0; }
    .order-summary-box li { padding: 10px 0; border-bottom: 1px solid #e0e0e0; font-size: 1.05em; display: flex; gap: 10px; align-items: flex-start; }
    .order-summary-box li:last-child { border-bottom: none; }
    .order-summary-box li i { color: var(--brand-success); margin-top: 3px; }
    .order-summary-box strong { color: #2c3e50; min-width: 100px; display: inline-block; }

    @media (max-width: 600px) { 
        body { font-size: 16px; padding: 5px;} 
        .container { padding: 15px; margin: 10px auto;} 
        .main-header h1 { font-size: 1.7em; } 
        .product-info h2 { font-size: 1.5em; } 
        .price-delivery-section { padding: 15px;} 
        .price-details .new-price { font-size: 2.0em; } 
        .cta-button { font-size: 1.2em; padding: 18px; } 
        .temu-form button[type="submit"] { font-size: 1.2em; padding: 16px; } 
        .benefits li { font-size: 1.05em; padding: 8px; } 
        .benefits li i { font-size: 1.2em; margin-right: 10px; } 
        .modal-content { width: 90%; padding: 20px;} 
        .purchase-popup { max-width: 90%; left: 5%; bottom: 10px; }
        
        
        
        .redirect-countdown { font-size: 2.8em; }
        
        
    }
          /* Sticky CTA Mobile */
        .sticky-cta-mobile {
            display: none;
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background: #28a745;
            color: white;
            text-align: center;
            padding: 12px 20px;
            font-size: 1.1em;
            font-weight: bold;
            z-index: 9999;
            box-shadow: 0 -3px 10px rgba(0,0,0,0.2);
            cursor: pointer;
            border: none;
            text-decoration: none;
        }
        .sticky-cta-mobile:hover { background: #218838; }
        @media (max-width: 600px) {
            .sticky-cta-mobile { display: block; }
            body { padding-bottom: 55px; }
        }
  </style>
</head>
<body>
  <div class="container" id="main-container">
    <header class="main-header">
      <h1>Relógio Telemóvel com Câmara: Simples, Prático e Português!</h1>
      <p class="subtitle">Mantenha-se Ligado Sem Complicações - Encomende Já e Pague aos CTT!</p>
    </header>

    <div class="carousel-container" id="carouselContainer">
          <div class="carousel-slide active-slide"><img src="https://cdn.shopify.com/s/files/1/0457/2230/4679/files/Rel.png?v=1775209212" alt="Relógio Telemóvel - Vista frontal elegante"></div>  
    <div class="carousel-slide active-slide"><img src="https://cdn.shopify.com/s/files/1/0457/2230/4679/files/Fil.png?v=1775209211" alt="Relógio Telemóvel - Vista frontal elegante"></div>
      <div class="carousel-slide"><img src="https://cdn.shopify.com/s/files/1/0457/2230/4679/files/Rel.png?v=1775209212" alt="Relógio Telemóvel - Detalhe da câmara discreta"></div>
    </div>

    <section class="product-info">
      <h2>O Relógio Inteligente Feito a Pensar Em Si!</h2>
      <div class="product-rating">
        <span class="stars">⭐⭐⭐⭐⭐</span>
        (Mais de 250 clientes satisfeitos em Portugal!)
      </div>
      <p>Cansado de telemóveis complicados? Este relógio é a solução perfeita! Faça e receba chamadas diretamente do pulso, como um telemóvel normal, mas muito mais prático. Tire fotos com a câmara, veja os seus passos e mantenha-se em contacto com a família e amigos. <strong>Tudo isto de forma simples e intuitiva, ideal para o dia-a-dia!</strong></p>
    </section>

    <section class="price-delivery-section">
        <div class="price-details">
            <span class="old-price">Preço Normal: 79,00€</span>
            <span class="new-price">Só Hoje: 40,00€</span>
            <p class="payment-info"><i class="fa-solid fa-hand-holding-dollar"></i> Pague SÓ na Entrega ao Carteiro CTT!</p>
            <p class="shipping-note">Entrega Gratuita (Portugal Continental)<br>(Ilhas: +10€ pagos também na entrega)</p>
        </div>
        <div class="delivery-partner">
            <img src="https://cdn.shopify.com/s/files/1/0457/2230/4679/files/CTT-Logo-20080409.png?v=1745792613" alt="Entregue pelos CTT">
            <p>Entrega Rápida e Segura<br>via CTT Expresso</p>
        </div>
    </section>

    <section class="urgency-info">
        <div><i class="fa-solid fa-fire"></i> Oferta Especial Válida Apenas Hoje! Termina em: <span id="countdown">10:00</span></div>
        <div><i class="fa-solid fa-triangle-exclamation"></i> Atenção: Restam <span id="stock">4</span> unidades com este Preço de Lançamento!</div>
    </section>

    <section class="benefits-section">
        <h3>Vantagens Que Vão Facilitar o Seu Dia-a-Dia:</h3>
        <ul class="benefits">
            <li><i class="fa-solid fa-phone-volume"></i> Fale ao Telemóvel Diretamente no Pulso (sem tirar do bolso!)</li>
            <li><i class="fa-solid fa-camera"></i> Tire Fotos Simples e Rápidas com a Câmara</li>
            <li><i class="fa-solid fa-display"></i> Visor Grande e Luminoso, Fácil de Ler as Horas</li>
            <li><i class="fa-solid fa-person-walking"></i> Contador de Passos para o Ajudar a Manter-se Ativo</li>
            <li><i class="fa-solid fa-battery-full"></i> Bateria Que Dura Vários Dias, Menos Uma Preocupação</li>
            <li><i class="fa-solid fa-face-smile"></i> Super Fácil de Usar, Mesmo Para Quem Não Gosta de Tecnologia</li>
            <li class="highlight"><i class="fa-solid fa-hand-holding-dollar"></i> Pague SÓ Quando Receber em Casa, Diretamente aos CTT! 100% Seguro e Sem Riscos!</li>
            <li><i class="fa-solid fa-truck-fast"></i> Entrega Rápida e Confiável pelos CTT (Normalmente 24/48h úteis)</li>
        </ul>
    </section>

    <button class="cta-button" onclick="scrollToForm()">
        <div><i class="fa-solid fa-cart-shopping"></i> Quero Encomendar o Meu Agora!</div>
        <small>(Só paga 40,00€ aos CTT quando o carteiro entregar)</small>
    </button>

    <section class="reviews-section">
        <h3>Veja o Que Dizem Clientes Como Você:</h3>
        <div class="reviews-container" id="reviewsContainer">
            <div class="review-slide active-review">
                <p>"Muito prático, já não ando à procura do telemóvel para atender. A câmara dá jeito. Chegou rápido pelos CTT e paguei na hora. Cinco estrelas!"</p>
                <strong>Manuel P., 67 anos, Lisboa</strong>
            </div>
            <div class="review-slide">
                <p>"Comprei para a minha mãe que não se ajeita com smartphones. Adorou! Liga-nos facilmente e vê bem as horas. Foi um bom presente."</p>
                <strong>Sofia R. (filha), Porto</strong>
            </div>
            <div class="review-slide">
                <p>"Funciona bem, sem complicações. Gosto de ver os passos que dou. O pagamento na entrega é uma segurança extra. Recomendo vivamente."</p>
                <strong>Joaquim A., 72 anos, Coimbra</strong>
            </div>
            <div class="review-slide">
                <p>"Finalmente um relógio que faz chamadas e é fácil de mexer. A bateria dura bastante. Ideal para quem quer simplicidade no dia a dia."</p>
                <strong>Maria G., 65 anos, Faro</strong>
            </div>
            <div class="review-slide">
                <p>"Recebi o meu ontem, entrega impecável dos CTT. O relógio é giro e fácil de configurar. A qualidade parece boa para o preço. Satisfeito."</p>
                <strong>António M., 69 anos, Braga</strong>
            </div>
        </div>
                    <div class="review-slide">
                <p>"Comprei para o meu pai de 78 anos. Ele adora! Liga para toda a gente com facilidade. Melhor presente que podia ter dado."</p>
                <strong>Teresa L., 48 anos, Viseu</strong>
            </div>
            <div class="review-slide">
                <p>"Já é o segundo que compro. O primeiro foi para a minha mãe, agora para a sogra. As duas não largam! Entrega rápida pelos CTT."</p>
                <strong>Carlos F., 55 anos, Setúbal</strong>
            </div>
    </section>

    <section class="order-form-section" id="order-form-section">
              <h3><i class="fa-solid fa-pen-to-square"></i> Garanta o Seu Agora! Preencha e Receba em 24/48h:</h3>
      <form id="order-form" class="temu-form">
        <input type="hidden" id="tempId" name="tempId" value="">
        <input type="hidden" name="product" value="Relógio Telemóvel com Câmara 40,00€">

        <div class="form-group">
            <label for="product_color"><span>1.</span> Escolha a Cor Que Mais Gosta:</label>
            <div class="radio-group">
                <label><input type="radio" name="product_color" value="Preto" required> <span>Preto</span></label>
                <label><input type="radio" name="product_color" value="Prata" required> <span>Prata</span></label>
                <label><input type="radio" name="product_color" value="Rosa" required> <span>Rosa</span></label>
                <label><input type="radio" name="product_color" value="Branco" required> <span>Branco</span></label>
            </div>
        </div>

        <div class="form-group">
          <label for="nome"><span>2.</span> Nome Completo (Como vem na caixa do correio):</label>
          <input type="text" id="nome" name="nome" required placeholder="Ex: Maria Augusta Pereira da Silva" aria-label="Nome Completo">
        </div>

        <div class="form-group">
          <label for="telemovel"><span>3.</span> O Seu Número de Telemóvel (Para confirmarmos a entrega):</label>
          <input type="tel" id="telemovel" name="telemovel" required placeholder="Ex: 912345678 ou 351912345678" aria-label="Número de Telemóvel">
          <small>Ligamos-lhe rapidamente só para confirmar a morada antes de enviar.</small>
        </div>

        <div class="form-group">
          <label for="morada"><span>4.</span> Morada Completa (Para os CTT entregarem certinho):</label>
          <input type="text" id="morada" name="morada" required placeholder="Rua, Número, Andar (se houver), Código Postal e Localidade" aria-label="Morada Completa">
          <small>Ex: Rua da Liberdade, 123, 1º Direito, 4000-100 Porto</small>
        </div>


            <div style="background: #fff3cd; border: 1px solid #ffc107; border-radius: 8px; padding: 10px 15px; margin: 15px 0; text-align: center;">
                <p style="margin: 0; color: #856404; font-size: 0.95em;"><i class="fa-solid fa-clock"></i> <strong>Atenção:</strong> Esta oferta de 40,00€ termina hoje. Amanhã o preço volta para 79€.</p>
            </div>
            <div style="display: flex; justify-content: center; gap: 15px; margin: 10px 0; flex-wrap: wrap;">
                <span style="font-size: 0.85em; color: #28a745;"><i class="fa-solid fa-shield-halved"></i> Compra Segura</span>
                <span style="font-size: 0.85em; color: #28a745;"><i class="fa-solid fa-lock"></i> Dados Protegidos</span>
                <span style="font-size: 0.85em; color: #28a745;"><i class="fa-solid fa-truck"></i> Entrega 24/48h</span>
            </div>
        <button type="submit" id="submit-button">
            <span class="submit-text"><i class="fa-solid fa-check-double"></i> Sim, Quero Confirmar a Encomenda!</span>
            <span class="processing-indicator"><span>A registar, aguarde...</span><span class="loader"></span></span>
        </button>
                    <p style="text-align: center; margin-top: 10px; font-size: 0.85em; color: #666;"><i class="fa-solid fa-shield-halved" style="color: #28a745;"></i> Garantia de Satisfação: Se não gostar, devolvemos o seu dinheiro. Sem perguntas.</p>
            <p style="text-align: center; margin-top: 5px; font-size: 0.85em; color: #666;"><i class="fa-solid fa-users" style="color: #e74c3c;"></i> <strong>387 pessoas</strong> já encomendaram esta semana!</p>
      </form>
    </section>

    <footer class="footer">
        <p><strong><i class="fa-solid fa-shield-halved"></i> Compra 100% Segura e Sem Riscos!</strong></p>
        <p><i class="fa-solid fa-truck"></i> Entrega Rápida e Segura pelos CTT</p>
        <p><i class="fa-solid fa-money-bill-wave"></i> Pagamento Conveniente SÓ na Entrega</p>
        <p><i class="fa-solid fa-headset"></i> Apoio ao Cliente Disponível em Português</p>
        <p><i class="fa-solid fa-box-open"></i> Satisfação Garantida ou Devolução Simples</p>
        <p style="margin-top: 15px;">© <?php echo date("Y"); ?> Todos os direitos reservados.</p>
    </footer>
  </div>

  

  <div id="error-modal" class="modal">
    <div class="modal-content">
      <span class="modal-close-btn" onclick="closeModal('error-modal')">×</span>
      <h2><i class="fa-solid fa-circle-exclamation" style="color: var(--brand-danger);"></i> Ups! Algo correu mal...</h2>
      <p id="error-message-text">Ocorreu um erro.</p>
    </div>
  </div>

  <div class="purchase-popup" id="purchase-popup"></div>

  <script>
    // ===============================
    // Variáveis Globais e Estado
    // ===============================
    let tempUserId = localStorage.getItem("tempLeadId_Relogio") || "";
    let addToCartTriggered = false;
    let isSubmitting = false;
//     const WHATSAPP_NUMBER = "351936259748";

    // ===============================
    // Funções Utilitárias
    // ===============================
    function showModal(modalId, message) {
      const modal = document.getElementById(modalId);
      if (!modal) return;
      document.getElementById('error-message-text').innerHTML = message;
      modal.style.display = "block";
    }
    function closeModal(modalId) {
      const modal = document.getElementById(modalId);
      if (modal) modal.style.display = "none";
    }
    function scrollToForm() {
      const formSection = document.getElementById('order-form-section');
      if (formSection) {
        formSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
        setTimeout(() => {
          const firstInput = formSection.querySelector('input[type="radio"]:not(:checked), input[type="text"], input[type="tel"]');
          if(firstInput) firstInput.focus();
        }, 500);
      }
    }

    // ==============================================================
    // =     LÓGICA DE TELA DE REDIRECIONAMENTO PARA WHATSAPP      =
    // ==============================================================


    function renderConfirmationPage(data) {
    const WHATSAPPNUMBER = '351929364654';
    data = data || {};

    const f = document.getElementById('order-form');
    const getF = function (n) {
        if (!f) return '';
        const checked = f.querySelector('[name="' + n + '"]:checked');
        if (checked) return checked.value;
        const el = f.querySelector('[name="' + n + '"]');
        return el ? (el.value || '') : '';
    };

    const name    = (data.customer_name    || getF('nome')          || 'Cliente').toString().trim();
    const phone   = (data.customer_phone   || getF('telemovel')     || '').toString().trim();
    const address = (data.customer_address || getF('morada')        || '').toString().trim();
    const color   = (data.product_color    || getF('product_color') || '').toString().trim();
    let   product = (data.product_name     || getF('product')       || 'o produto').toString().trim();

    product = product.replace(/\s*[-–—]?\s*\d+[.,]\d{2}\s*€?/g, '').trim();
    product = product.replace(/\s*\(Cor:\s*[^)]+\)\s*/i, '').trim();
    if (color) product += ' (Cor: ' + color + ')';

    let price = (data.final_price_formatted || '').toString().trim();
    if (!price) {
        const ml = address.toLowerCase();
        price = '40,00';
    }
    if (price && price.indexOf('€') === -1) price += '€';

    const msg = 'Olá! Sou ' + name +
                '. Acabei de encomendar ' + product +
                ' no valor de ' + price +
                ' a pagar na entrega. A minha morada é: ' + address +
                '. Telemóvel: ' + phone + '.';
    const waUrl = 'https://wa.me/' + WHATSAPPNUMBER + '?text=' + encodeURIComponent(msg);

    const container = document.getElementById('whatsapp-redirect-page');
    const mainContainer = document.getElementById('main-container');
    if (mainContainer) mainContainer.style.display = 'none';
    if (container) {
        container.style.display = 'flex';
        container.innerHTML =
            '<div style="text-align:center; padding:30px; max-width:600px; margin:0 auto;">' +
                '<h1 style="font-size:1.8em; color:#2e7d32; margin-bottom:15px;">✅ Encomenda Confirmada!</h1>' +
                '<p style="font-size:1.2em; color:#555;">Obrigado, <strong>' + name + '</strong>!</p>' +
                '<p style="font-size:1.1em; color:#555;">A sua encomenda no valor de <strong>' + price + '</strong> foi registada com sucesso.</p>' +
                '<p style="font-size:1em; color:#555; margin-top:15px;">A redirecionar para o WhatsApp...</p>' +
                '<a href="' + waUrl + '" style="display:inline-block; margin-top:20px; background:#25D366; color:#fff; padding:15px 25px; border-radius:8px; text-decoration:none; font-weight:bold; font-size:1.1em;">Abrir WhatsApp Agora</a>' +
            '</div>';
    }

    setTimeout(function () { window.location.href = waUrl; }, 800);
}
    // ===============================
    // Lógica de Salvamento em Tempo Real
    // ===============================
    function saveDataRealTime() {
      if (isSubmitting) return;
      const formData = new FormData(document.getElementById('order-form'));
      if (!tempUserId && !formData.get('nome').trim() && !formData.get('telemovel').trim() && !formData.get('morada').trim() && !formData.get('product_color')) return;
      formData.append('realTime', '1');
      formData.append('tempId', tempUserId);
      fetch('', { method: 'POST', body: formData })
        .then(resp => resp.json())
        .then(data => {
          if (data.status === 'partial_saved' && data.temp_id) {
            if (tempUserId !== data.temp_id) {
                tempUserId = data.temp_id;
                document.getElementById("tempId").value = tempUserId;
                localStorage.setItem("tempLeadId_Relogio", tempUserId);
            }
          }
        })
        .catch(err => console.warn("Erro ao salvar em tempo real:", err));
      if (!addToCartTriggered && formData.get('nome').trim() && formData.get('telemovel').trim() && formData.get('morada').trim()) {
        try {
            let price = 40.00;
            const moradaLower = formData.get('morada').toLowerCase();
            price = 40.00;
            if (typeof fbq === 'function') {
                fbq('track', 'AddToCart', { content_name: formData.get('product'), value: price, currency: 'EUR' });
                addToCartTriggered = true;
            }
        } catch (e) { console.error("Erro ao disparar FB AddToCart:", e); }
      }
    }

    document.querySelectorAll('#nome, #telemovel, #morada').forEach(el => el.addEventListener('blur', saveDataRealTime));
    document.querySelectorAll('input[name="product_color"]').forEach(radio => radio.addEventListener('change', saveDataRealTime));
    if (tempUserId) document.getElementById("tempId").value = tempUserId;

    // ===============================
    // Lógica do Formulário Principal
    // ===============================
    const orderForm = document.getElementById('order-form');
    if (orderForm) {
        orderForm.addEventListener('submit', function(e) {
          e.preventDefault();
          if (isSubmitting) return;
          isSubmitting = true;
          const submitButton = document.getElementById('submit-button');
          const submitText = submitButton.querySelector('.submit-text');
          const processingIndicator = submitButton.querySelector('.processing-indicator');
          submitButton.disabled = true;
          submitText.style.display = 'none';
          processingIndicator.style.display = 'flex';
          const formData = new FormData(this);
          formData.append('ajax', '1');
          formData.append('tempId', tempUserId);

          fetch('', { method: 'POST', body: formData })
          .then(response => response.json())
          .then(data => {
            if (data.status === "success") {
                try {
                    if (typeof fbq === 'function') {
                        fbq('track', 'Purchase', { value: data.final_price, currency: 'EUR', content_name: data.product_name, content_ids: [data.tracking_id || 'N/A'], content_type: 'product' });
                    }
                    if (typeof gtag === 'function') {
                        gtag('event', 'conversion', { 'send_to': 'AW-16491374494/sOLqCJ_-iqAZEJ7P2bc9', 'value': data.final_price, 'currency': 'EUR', 'transaction_id': data.tracking_id + '_' + Date.now() });
                    }
                } catch(e) { console.error("Erro ao disparar eventos de tracking:", e); }

            // setWhatsAppCache removido - WhatsApp desativado
                renderConfirmationPage(data);
                localStorage.removeItem("tempLeadId_Relogio");

            } else if (data.status === 'redirect') {
                window.location.href = data.url;
            } else {
                showModal('error-modal', data.message || 'Ocorreu um erro desconhecido.');
                submitText.style.display = 'flex';
                processingIndicator.style.display = 'none';
                submitButton.disabled = false;
                isSubmitting = false;
            }
          })
          .catch(error => {
            console.error('Fetch Error:', error);
            showModal('error-modal', 'Não foi possível contactar o servidor. Verifique a sua ligação à internet.');
            submitText.style.display = 'flex';
            processingIndicator.style.display = 'none';
            submitButton.disabled = false;
            isSubmitting = false;
          });
        });
    }

    // ===============================
    // Lógica dos Carrosséis e Urgência
    // ===============================
    let currentSlideIndex = 0;
    const slides = document.querySelectorAll('.carousel-slide');
    function showSlide(index) { slides.forEach((s, i) => s.classList.toggle('active-slide', i === index)); }
    function nextSlide() { currentSlideIndex = (currentSlideIndex + 1) % slides.length; showSlide(currentSlideIndex); }

    let currentReviewIndex = 0;
    const reviewSlides = document.querySelectorAll('.review-slide');
    function showReview(index) { reviewSlides.forEach((r, i) => r.classList.toggle('active-review', i === index)); }
    function nextReview() { currentReviewIndex = (currentReviewIndex + 1) % reviewSlides.length; showReview(currentReviewIndex); }

    function startCountdown() {
      const el = document.getElementById('countdown'); if(!el) return;
      let timer = 10 * 60;
      setInterval(() => {
        let m = String(parseInt(timer/60,10)).padStart(2,'0');
        let s = String(parseInt(timer%60,10)).padStart(2,'0');
        el.textContent = `${m}:${s}`;
        if (--timer < 0) timer = 10*60;
      }, 1000);
    }

    function updateStock() {
      const el = document.getElementById('stock'); if(!el) return;
      let stock = parseInt(el.textContent);
      setInterval(() => { if (stock > 2) el.textContent = --stock; }, getRandomInterval(45000, 90000));
    }

    const purchaseTriggers = ["Manuel P., Lisboa: acabou de encomendar o Preto!", "Maria G., Porto: garantiu o seu em Rosa!", "Joaquim S., Faro: comprou o modelo Prata.", "Sofia A., Coimbra: acabou de pedir o Branco."];
    function showPurchasePopup() {
      const popup = document.getElementById('purchase-popup'); if (!popup) return;
      popup.textContent = purchaseTriggers[Math.floor(Math.random() * purchaseTriggers.length)];
      popup.style.display = 'block'; popup.classList.remove('hide');
      setTimeout(() => { popup.classList.add('hide'); setTimeout(() => { popup.style.display = 'none'; }, 500); }, 5000);
    }
    function getRandomInterval(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }

    // ===============================
    // Inicialização Geral
    // ===============================
    document.addEventListener('DOMContentLoaded', () => {
// CLEANED:       try {
// CLEANED:           const cachedOrder = localStorage.getItem('relogioOrderCache');
// CLEANED:           if (cachedOrder) {
// CLEANED:               const orderData = JSON.parse(cachedOrder);
// CLEANED:               if (orderData && orderData.expiry && new Date().getTime() < orderData.expiry) {
// CLEANED:                   renderConfirmationPage(orderData); 
// CLEANED:                   return;
// CLEANED:               } else {
// CLEANED:                   localStorage.removeItem('relogioOrderCache');
// CLEANED:               }
// CLEANED:           }
// CLEANED:       } catch (e) { console.error("Erro ao ler o cache da encomenda:", e); }

      showSlide(currentSlideIndex); setInterval(nextSlide, 4500);
      showReview(currentReviewIndex); setInterval(nextReview, 5500);
      startCountdown(); updateStock();
      setTimeout(() => { showPurchasePopup(); setInterval(showPurchasePopup, getRandomInterval(25000, 45000)); }, getRandomInterval(8000, 15000));

      window.onclick = function(event) {
          if (event.target == document.getElementById('error-modal')) closeModal('error-modal');
      }
    });
  </script>
<a href="#order-form-section" class="sticky-cta-mobile"><i class="fa-solid fa-shopping-cart"></i> ENCOMENDAR AGORA - 40,00€ na Entrega</a>
<div id="whatsapp-redirect-page" style="display:none;"></div>
</body>
</html>