<?php
/**
 * Página de Cadastro - MontaLoja
 * Wizard de criação de loja com header/footer do template
 */
require_once __DIR__ . '/../../includes/config.php';

$pdo = getDB();
$baseDomain = 'duolead.com.br';

// Carregar planos ativos
$plansStmt = $pdo->query("SELECT * FROM plans WHERE is_active = 1 ORDER BY sort_order ASC");
$plans = $plansStmt->fetchAll(PDO::FETCH_ASSOC);
$selectedPlan = $_GET['plano'] ?? 'free';

// Incluir header do template
include __DIR__ . '/../../templates/landing_v1/header.php';

// RGB para gradientes (usar variáveis do header)
$r = hexdec(substr($themeColors['primary'], 1, 2));
$g = hexdec(substr($themeColors['primary'], 3, 2));
$b = hexdec(substr($themeColors['primary'], 5, 2));
?>

<style>
/* ========================================
   ESTILOS ESPECÍFICOS DA PÁGINA DE CADASTRO
   ======================================== */

/* Wizard Container */
.wizard-container {
    min-height: 100vh;
    padding-top: 33px;
}

/* Progress Bar */
.progress-container {
    background: var(--bg-darker);
    padding: 1.5rem 2rem;
    border-bottom: 1px solid var(--border);
    position: sticky;
    top: 75px;
    z-index: 1;
}

.progress-steps {
    max-width: 700px;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    position: relative;
}

.progress-line {
    position: absolute;
    top: 18px;
    left: 25px;
    right: 25px;
    height: 3px;
    background: var(--border);
    z-index: 0;
}

.progress-line::after {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: var(--progress, 0%);
    background: var(--gold);
    transition: width 0.5s ease;
}

.step-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 0.5rem;
    position: relative;
    z-index: 1;
}

.step-circle {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: var(--bg-card);
    border: 3px solid var(--border);
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 0.875rem;
    color: var(--text-muted);
    transition: all 0.3s;
}

.step-label {
    font-size: 0.75rem;
    color: var(--text-muted);
    font-weight: 500;
    transition: color 0.3s;
}

.step-item.active .step-circle {
    border-color: var(--gold);
    background: var(--gold);
    color: #000;
}

.step-item.active .step-label {
    color: var(--gold);
}

.step-item.completed .step-circle {
    border-color: var(--success);
    background: var(--success);
    color: #fff;
}

.step-item.completed .step-label {
    color: var(--success);
}

/* Wizard Main */
.wizard-main {
    max-width: 600px;
    margin: 0 auto;
    padding: 2rem 1rem 4rem;
}

.wizard-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 2rem;
}

/* Step Content */
.step-content {
    display: none;
}

.step-content.active {
    display: block;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

.step-title {
    font-size: 1.5rem;
    font-weight: 700;
    margin-bottom: 0.5rem;
    text-align: center;
}

.step-title span {
    background: var(--gradient-gold);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.step-subtitle {
    color: var(--text-muted);
    text-align: center;
    margin-bottom: 2rem;
}

/* Welcome Step */
.welcome-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto 1.5rem;
    background: rgba(<?php echo "$r, $g, $b"; ?>, 0.15);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.welcome-icon iconify-icon {
    font-size: 2.5rem;
    color: var(--gold);
}

.welcome-features {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    margin: 1.5rem 0 2rem;
}

.welcome-feature {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.75rem 1rem;
    background: rgba(<?php echo "$r, $g, $b"; ?>, 0.1);
    border-radius: 8px;
}

.welcome-feature iconify-icon {
    color: var(--success);
    font-size: 1.25rem;
}

.btn-start {
    width: 100%;
    padding: 1rem;
    font-size: 1.1rem;
}

/* Segment Grid */
.segment-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
    margin-bottom: 2rem;
}

.segment-card {
    position: relative;
    padding: 1.25rem;
    background: var(--bg-darker);
    border: 2px solid var(--border);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s;
    text-align: center;
}

.segment-card input {
    position: absolute;
    opacity: 0;
}

.segment-card:hover {
    border-color: var(--gold);
}


.segment-card.disabled { opacity: 1; pointer-events: none !important; position: relative; cursor: not-allowed !important; filter: grayscale(0.5); background: #f9fafb !important; }
.segment-card.disabled:hover { border-color: var(--border) !important; transform: none !important; }
.coming-soon-badge { position: absolute !important; top: 10px !important; right: 10px !important; left: auto !important; background: linear-gradient(135deg, #6366f1, #8b5cf6) !important; color: white !important; font-size: 0.7rem !important; padding: 4px 10px !important; border-radius: 20px !important; font-weight: 600 !important; z-index: 100 !important; text-transform: uppercase !important; letter-spacing: 0.5px !important; box-shadow: 0 2px 8px rgba(99,102,241,0.3) !important; }
.segment-card.selected {
    border-color: var(--gold);
    background: rgba(<?php echo "$r, $g, $b"; ?>, 0.1);
}

.segment-icon {
    width: 50px;
    height: 50px;
    margin: 0 auto 0.75rem;
    background: rgba(<?php echo "$r, $g, $b"; ?>, 0.15);
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.segment-icon iconify-icon {
    font-size: 1.5rem;
    color: var(--gold);
}

.segment-title {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.segment-desc {
    font-size: 0.8rem;
    color: var(--text-muted);
}

/* Form Styles */
.form-group {
    margin-bottom: 1.25rem;
}

.form-label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
    font-size: 0.9rem;
}

.form-label .required {
    color: var(--error);
}

.form-input {
    width: 100%;
    padding: 0.875rem 1rem;
    background: var(--bg-darker);
    border: 2px solid var(--border);
    border-radius: 8px;
    color: var(--text-primary);
    font-size: 1rem;
    transition: all 0.3s;
}

.form-input:focus {
    outline: none;
    border-color: var(--gold);
    box-shadow: 0 0 0 4px rgba(<?php echo "$r, $g, $b"; ?>, 0.15);
}

.form-input::placeholder {
    color: var(--text-muted);
}

/* Subdomain Input */
.subdomain-wrapper {
    display: flex;
    align-items: stretch;
    background: var(--bg-darker);
    border: 2px solid var(--border);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;
}

.subdomain-wrapper:focus-within {
    border-color: var(--gold);
    box-shadow: 0 0 0 4px rgba(<?php echo "$r, $g, $b"; ?>, 0.15);
}

.subdomain-wrapper input {
    flex: 1;
    padding: 0.875rem 1rem;
    background: transparent;
    border: none;
    color: var(--text-primary);
    font-size: 1rem;
}

.subdomain-wrapper input:focus {
    outline: none;
}

.subdomain-suffix {
    padding: 0.875rem 1rem;
    background: var(--bg-card);
    color: var(--text-muted);
    font-weight: 500;
    border-left: 1px solid var(--border);
}

.subdomain-status {
    margin-top: 0.5rem;
    font-size: 0.85rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.subdomain-status.available {
    color: var(--success);
}

.subdomain-status.unavailable {
    color: var(--error);
}

.subdomain-status.checking {
    color: var(--text-muted);
}

/* Password Strength */
.password-strength {
    height: 4px;
    background: var(--border);
    border-radius: 2px;
    margin-top: 0.5rem;
    overflow: hidden;
}

.password-strength-bar {
    height: 100%;
    width: var(--progress, 0%);
    border-radius: 2px;
    transition: all 0.3s;
}

.password-strength-bar.weak {
    width: 33%;
    background: var(--error);
}

.password-strength-bar.medium {
    width: 66%;
    background: #F59E0B;
}

.password-strength-bar.strong {
    width: 100%;
    background: var(--success);
}

/* Plan Grid */
.plan-grid {
    display: flex;
    flex-direction: column;
    gap: 1rem;
    margin-bottom: 2rem;
}

.plan-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: var(--bg-darker);
    border: 2px solid var(--border);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
}

.plan-card input {
    position: absolute;
    opacity: 0;
}

.plan-card:hover {
    border-color: var(--gold);
}

.plan-card.selected {
    border-color: var(--gold);
    background: rgba(<?php echo "$r, $g, $b"; ?>, 0.1);
}

.plan-card.recommended::before {
    content: 'Recomendado';
    position: absolute;
    top: -10px;
    right: 12px;
    background: var(--gold);
    color: #000;
    font-size: 0.7rem;
    font-weight: 700;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
}

.plan-radio {
    width: 20px;
    height: 20px;
    border: 2px solid var(--border);
    border-radius: 50%;
    position: relative;
    flex-shrink: 0;
}

.plan-card.selected .plan-radio {
    border-color: var(--gold);
}

.plan-card.selected .plan-radio::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 10px;
    height: 10px;
    background: var(--gold);
    border-radius: 50%;
}

.plan-info {
    flex: 1;
}

.plan-name {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.plan-features {
    font-size: 0.8rem;
    color: var(--text-muted);
}

.plan-price {
    text-align: right;
}

.plan-price-value {
    font-size: 1.25rem;
    font-weight: 700;
    color: var(--gold);
}

.plan-price-period {
    font-size: 0.75rem;
    color: var(--text-muted);
.plan-trial-badge {
    position: absolute;
    top: -8px;
    right: 60px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    font-size: 0.7rem;
    font-weight: 600;
    padding: 4px 10px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
}
.plan-trial-badge iconify-icon {
    font-size: 0.85rem;
}
}

/* Buttons 
.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.3s;
    cursor: pointer;
    border: none;
    font-size: 1rem;
}*/

.btn-primary {
    background: var(--gradient-gold);
    color: #000;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 40px rgba(<?php echo "$r, $g, $b"; ?>, 0.3);
}

.btn-secondary {
    background: var(--bg-darker);
    color: var(--text-primary);
    border: 1px solid var(--border);
}

.btn-secondary:hover {
    border-color: var(--gold);
}

.btn-group {
    display: flex;
    gap: 1rem;
    justify-content: space-between;
}

.btn-group .btn {
    flex: 1;
}

/* Alert */
.alert {
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-size: 0.9rem;
}

.alert-error {
    background: rgba(239, 68, 68, 0.15);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: #FCA5A5;
}

/* Success Step */
.success-icon {
    width: 100px;
    height: 100px;
    margin: 0 auto 1.5rem;
    background: rgba(34, 197, 94, 0.15);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.success-icon iconify-icon {
    font-size: 3rem;
    color: var(--success);
}

.success-url {
    background: var(--bg-darker);
    padding: 1rem;
    border-radius: 8px;
    text-align: center;
    margin-bottom: 1.5rem;
}

.success-url-label {
    font-size: 0.85rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.success-url-value {
    font-weight: 600;
    color: var(--gold);
    font-size: 1.1rem;
}

/* Mobile Responsive */
@media (max-width: 767px) {
    .wizard-container {
        padding-top: 84px;
    }
    
    .progress-container {
        padding: 1rem;
        top: 84px;
    }
    
    .step-label {
        display: none;
    }
    
    .step-circle {
        width: 32px;
        height: 32px;
        font-size: 0.75rem;
    }
    
    .wizard-card {
        padding: 1.5rem;
    }
    
    .segment-grid {
        grid-template-columns: 1fr;
    }
    
    .btn-group {
        flex-direction: column;
    }
    
    .btn-group .btn-secondary {
        order: 1;
    }
}
/* Payment Modal */
.payment-modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.6); z-index: 1000; align-items: center; justify-content: center; backdrop-filter: blur(4px); }
.payment-modal.active { display: flex; }
.payment-modal-content { background: var(--bg-white); border-radius: 16px; padding: 2rem; max-width: 420px; width: 90%; text-align: center; animation: slideUp 0.3s ease; position: relative; }
@keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
.payment-modal-close { position: absolute; top: 12px; right: 12px; background: none; border: none; font-size: 1.5rem; cursor: pointer; color: var(--text-light); }
.payment-modal-icon { width: 60px; height: 60px; background: linear-gradient(135deg, var(--gold), #d4a92a); border-radius: 12px; margin: 0 auto 1rem; display: flex; align-items: center; justify-content: center; }
.payment-modal-icon iconify-icon { font-size: 1.8rem; color: white; }
.payment-modal h3 { font-size: 1.3rem; margin-bottom: 0.25rem; color: var(--text); }
.payment-modal-subtitle { color: var(--text-light); font-size: 0.9rem; margin-bottom: 1.5rem; }
.payment-options { display: flex; flex-direction: column; gap: 0.75rem; }
.payment-option { display: flex; align-items: center; gap: 1rem; padding: 1rem; border: 2px solid var(--border); border-radius: 12px; cursor: pointer; transition: all 0.3s; background: var(--bg-darker); }
.payment-option:hover { border-color: var(--gold); background: rgba(204,164,59,0.05); }
.payment-option-icon { width: 40px; height: 40px; background: var(--bg-white); border-radius: 8px; display: flex; align-items: center; justify-content: center; }
.payment-option-icon iconify-icon { font-size: 1.3rem; color: var(--gold); }
.payment-option-info { text-align: left; flex: 1; }
.payment-option-title { font-weight: 600; color: var(--text); }
.payment-option-desc { font-size: 0.8rem; color: var(--text-light); }
</style>

<!-- WIZARD -->
<div class="wizard-container">
    <div class="progress-container">
        <div class="progress-steps">
            <div class="progress-line" id="progressLine"></div>
            <div class="step-item active" data-step="0"><div class="step-circle">1</div><span class="step-label">Início</span></div>
            <div class="step-item" data-step="1"><div class="step-circle">2</div><span class="step-label">Segmento</span></div>
            <div class="step-item" data-step="2"><div class="step-circle">3</div><span class="step-label">Sua Loja</span></div>
            <div class="step-item" data-step="3"><div class="step-circle">4</div><span class="step-label">Seus Dados</span></div>
            <div class="step-item" data-step="4"><div class="step-circle">5</div><span class="step-label">Plano</span></div>
        </div>
    </div>

    <main class="wizard-main">
        <div class="wizard-card">
            <form id="wizardForm" onsubmit="return handleFormSubmit(event)">
                <div id="alertContainer"></div>

                <!-- Step 0: Welcome -->
                <div class="step-content active" data-step="0">
                    <div class="welcome-icon"><iconify-icon icon="solar:rocket-2-bold"></iconify-icon></div>
                    <h2 class="step-title">Invista em um ambiente <span>personalizado</span> para seu negócio</h2>
                    <p class="step-subtitle">Vamos configurar sua loja em poucas etapas!</p>
                    <div class="welcome-features">
                        <div class="welcome-feature"><iconify-icon icon="solar:check-circle-bold"></iconify-icon><span>Comece agora de graça</span></div>
                        <div class="welcome-feature"><iconify-icon icon="solar:check-circle-bold"></iconify-icon><span>Sem cartão de crédito</span></div>
                        <div class="welcome-feature"><iconify-icon icon="solar:check-circle-bold"></iconify-icon><span>Suporte via WhatsApp</span></div>
                    </div>
                    <button type="button" class="btn btn-primary btn-start" onclick="nextStep()"><iconify-icon icon="solar:play-bold"></iconify-icon>Iniciar configuração</button>
                </div>

                <!-- Step 1: Segment -->
                <div class="step-content" data-step="1">
                    <h2 class="step-title">Qual é o seu <span>segmento</span>?</h2>
                    <p class="step-subtitle">Selecione o tipo do seu negócio</p>
                    <div class="segment-grid">
                        <label class="segment-card"><input type="radio" name="business_type" value="retail"><div class="segment-icon"><iconify-icon icon="solar:bag-bold"></iconify-icon></div><div class="segment-title">Loja / Varejo</div><div class="segment-desc">Roupas, acessórios</div></label>
                        <label class="segment-card disabled"><span class="coming-soon-badge" style="position:absolute;top:10px;right:10px;">Em Breve</span><input type="radio" name="business_type" value="service" disabled><div class="segment-icon"><iconify-icon icon="solar:scissors-bold"></iconify-icon></div><div class="segment-title">Barbearia / Salão</div><div class="segment-desc">Serviços e agendamentos</div></label>
                        <label class="segment-card disabled"><span class="coming-soon-badge" style="position:absolute;top:10px;right:10px;">Em Breve</span><input type="radio" name="business_type" value="food" disabled><div class="segment-icon"><iconify-icon icon="solar:cup-hot-bold"></iconify-icon></div><div class="segment-title">Alimentação</div><div class="segment-desc">Restaurante, lanchonete</div></label>
                        <label class="segment-card disabled"><span class="coming-soon-badge" style="position:absolute;top:10px;right:10px;">Em Breve</span><input type="radio" name="business_type" value="other" disabled><div class="segment-icon"><iconify-icon icon="solar:widget-bold"></iconify-icon></div><div class="segment-title">Outro</div><div class="segment-desc">Outros segmentos</div></label>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-secondary" onclick="prevStep()"><iconify-icon icon="solar:arrow-left-linear"></iconify-icon>Voltar</button>
                        <button type="button" class="btn btn-primary" onclick="nextStep()">Continuar<iconify-icon icon="solar:arrow-right-linear"></iconify-icon></button>
                    </div>
                </div>

                <!-- Step 2: Store Info -->
                <div class="step-content" data-step="2">
                    <h2 class="step-title">Sobre sua <span>loja</span></h2>
                    <p class="step-subtitle">Informe os dados do seu negócio</p>
                    <div class="form-group">
                        <label class="form-label">Nome da sua loja <span class="required">*</span></label>
                        <input type="text" name="store_name" id="storeName" class="form-input" placeholder="Ex: Loja da Maria" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Endereço da sua loja online <span class="required">*</span></label>
                        <div class="subdomain-wrapper">
                            <input type="text" name="subdomain" id="subdomain" placeholder="minhaloja" required maxlength="30">
                            <span class="subdomain-suffix">.<?= $baseDomain ?></span>
                        </div>
                        <div class="subdomain-status" id="subdomainStatus"></div>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-secondary" onclick="prevStep()"><iconify-icon icon="solar:arrow-left-linear"></iconify-icon>Voltar</button>
                        <button type="button" class="btn btn-primary" onclick="nextStep()">Continuar<iconify-icon icon="solar:arrow-right-linear"></iconify-icon></button>
                    </div>
                </div>

                <!-- Step 3: User Data -->
                <div class="step-content" data-step="3">
                    <h2 class="step-title">Seus <span>dados</span></h2>
                    <p class="step-subtitle">Crie sua conta de administrador</p>
                    <div class="form-group"><label class="form-label">Seu nome <span class="required">*</span></label><input type="text" name="owner_name" class="form-input" placeholder="Nome completo" required></div>
                    <div class="form-group"><label class="form-label">WhatsApp <span class="required">*</span></label><input type="tel" name="phone" class="form-input" placeholder="(00) 00000-0000" required></div>
                    <div class="form-group"><label class="form-label">E-mail <span class="required">*</span></label><input type="email" name="email" class="form-input" placeholder="seu@email.com" required></div>
                    <div class="form-group"><label class="form-label">Senha <span class="required">*</span></label><input type="password" name="password" id="password" class="form-input" placeholder="Mínimo 6 caracteres" required minlength="6"><div class="password-strength"><div class="password-strength-bar" id="passwordStrength"></div></div></div>
                    <div class="form-group"><label class="form-label">Confirmar senha <span class="required">*</span></label><input type="password" name="confirm_password" class="form-input" placeholder="Repita a senha" required></div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-secondary" onclick="prevStep()"><iconify-icon icon="solar:arrow-left-linear"></iconify-icon>Voltar</button>
                        <button type="button" class="btn btn-primary" onclick="nextStep()">Continuar<iconify-icon icon="solar:arrow-right-linear"></iconify-icon></button>
                    </div>
                </div>

                <!-- Step 4: Plan -->
                <div class="step-content" data-step="4">
                    <h2 class="step-title">Escolha seu <span>plano</span></h2>
                    <p class="step-subtitle">Comece com 14 dias grátis</p>
                    <div class="plan-grid">
                        <?php foreach ($plans as $i => $plan): ?>
                        <label class="plan-card <?= $plan['id'] === $selectedPlan ? 'selected' : '' ?> <?= $i === 1 ? 'recommended' : '' ?>">
                            <input type="radio" name="plan_id" value="<?= $plan['id'] ?>" <?= $plan['id'] === $selectedPlan ? 'checked' : '' ?>>
                            <div class="plan-radio"></div>
                            <div class="plan-info"><div class="plan-name"><?= htmlspecialchars($plan['name']) ?></div><div class="plan-features"><?= htmlspecialchars($plan['description'] ?? 'Recursos essenciais') ?></div></div>
                            <div class="plan-price"><div class="plan-price-value">R$ <?= number_format($plan['price_monthly'], 0, ',', '.') ?></div><div class="plan-price-period">/mês</div></div>
                        </label>
                            <?php if ($plan['has_trial'] ?? false): ?>
                            <div class="plan-trial-badge">
                                <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                                <?= $plan['trial_days'] ?> dias grátis
                            </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                    <div class="btn-group">
                        <button type="button" class="btn btn-secondary" onclick="prevStep()"><iconify-icon icon="solar:arrow-left-linear"></iconify-icon>Voltar</button>
                        <button type="submit" class="btn btn-primary" id="btnSubmit"><iconify-icon icon="solar:rocket-bold"></iconify-icon>Criar minha loja</button>
                    </div>
                </div>

                <!-- Step 5: Success -->
                <div class="step-content" data-step="5">
                    <div class="success-icon"><iconify-icon icon="solar:check-circle-bold"></iconify-icon></div>
                    <h2 class="step-title">Parabéns! Sua loja foi <span>criada</span>!</h2>
                    <p class="step-subtitle">Você já pode começar a configurar</p>
                    <div class="success-url"><div class="success-url-label">Endereço da sua loja:</div><div class="success-url-value" id="successUrl"></div></div>
                    <a href="/pages/login.php" class="btn btn-primary btn-start" id="btnAccessStore"><iconify-icon icon="solar:login-bold"></iconify-icon>Acessar minha loja</a>
                </div>
            </form>
        </div>
    </main>

<!-- Payment Modal -->
<div class="payment-modal" id="paymentModal">
    <div class="payment-modal-content">
        <button class="payment-modal-close" onclick="closePaymentModal()">&times;</button>
        <div class="payment-modal-icon"><iconify-icon icon="solar:card-bold"></iconify-icon></div>
        <h3>Escolha a forma de pagamento</h3>
        <p class="payment-modal-subtitle" id="paymentPlanInfo">Plano Starter - R$ 35,00/mês</p>
        <div class="payment-options">
            <div class="payment-option" onclick="selectPaymentMethod('credit_card')">
                <div class="payment-option-icon"><iconify-icon icon="solar:card-bold"></iconify-icon></div>
                <div class="payment-option-info"><div class="payment-option-title">Cartão de Crédito</div><div class="payment-option-desc">Pague em até 12x</div></div>
            </div>
            <div class="payment-option" onclick="selectPaymentMethod('pix')">
                <div class="payment-option-icon"><iconify-icon icon="solar:qr-code-bold"></iconify-icon></div>
                <div class="payment-option-info"><div class="payment-option-title">PIX</div><div class="payment-option-desc">Aprovação instantânea</div></div>
            </div>
        </div>
    </div>
</div>
</div>

<script>
// Wizard logic
let currentStep = 0, totalSteps = 5, subdomainValid = false;

function updateProgress() {
    const p = document.getElementById('progressLine'), s = document.querySelectorAll('.step-item');
    p.style.setProperty('--progress', (currentStep / (totalSteps - 1)) * 100 + '%');
    s.forEach((i, n) => {
        i.classList.remove('active', 'completed');
        if (n < currentStep) i.classList.add('completed');
        if (n === currentStep) i.classList.add('active');
    });
    document.querySelectorAll('.step-content').forEach((c, n) => c.classList.toggle('active', n === currentStep));
}

function nextStep() {
    if (!validateStep(currentStep)) return;
    if (currentStep < totalSteps) { currentStep++; updateProgress(); }
}

function prevStep() {
    if (currentStep > 0) { currentStep--; updateProgress(); }
}

function validateStep(step) {
    const a = document.getElementById('alertContainer');
    a.innerHTML = '';
    if (step === 1 && !document.querySelector('input[name="business_type"]:checked')) { showAlert('Selecione um segmento'); return false; }
    if (step === 2) {
        const n = document.getElementById('storeName').value.trim(), s = document.getElementById('subdomain').value.trim();
        if (!n) { showAlert('Informe o nome da loja'); return false; }
        if (s.length < 3) { showAlert('Endereço deve ter no mínimo 3 caracteres'); return false; }
        if (!subdomainValid) { showAlert('Este endereço não está disponível'); return false; }
    }
    if (step === 3) {
        const n = document.querySelector('input[name="owner_name"]').value.trim(),
              p = document.querySelector('input[name="phone"]').value.trim(),
              e = document.querySelector('input[name="email"]').value.trim(),
              pw = document.querySelector('input[name="password"]').value,
              cp = document.querySelector('input[name="confirm_password"]').value;
        if (!n || !p || !e || !pw) { showAlert('Preencha todos os campos'); return false; }
        if (pw.length < 6) { showAlert('Senha deve ter no mínimo 6 caracteres'); return false; }
        if (pw !== cp) { showAlert('As senhas não conferem'); return false; }
    }
    return true;
}

function showAlert(m) {
    document.getElementById('alertContainer').innerHTML = '<div class="alert alert-error"><iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>' + m + '</div>';
}

// Segment selection
document.querySelectorAll('.segment-card:not(.disabled)').forEach(c => c.addEventListener('click', function() {
    document.querySelectorAll('.segment-card').forEach(x => x.classList.remove('selected'));
    this.classList.add('selected');
    this.querySelector('input').checked = true;
}));

// Plan selection
document.querySelectorAll('.plan-card').forEach(c => c.addEventListener('click', function() {
    document.querySelectorAll('.plan-card').forEach(x => x.classList.remove('selected'));
    this.classList.add('selected');
    this.querySelector('input').checked = true;
}));

// Subdomain handling
const subdomainInput = document.getElementById('subdomain'), storeNameInput = document.getElementById('storeName'), statusEl = document.getElementById('subdomainStatus');
let checkTimeout;

function sanitizeSubdomain(t) {
    return t.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]/g, '').substring(0, 30);
}

function checkSubdomain(s) {
    if (s.length < 3) {
        statusEl.className = 'subdomain-status unavailable';
        statusEl.innerHTML = '<iconify-icon icon="solar:close-circle-bold"></iconify-icon> Mínimo 3 caracteres';
        subdomainValid = false;
        return;
    }
    statusEl.className = 'subdomain-status checking';
    statusEl.innerHTML = '<iconify-icon icon="solar:refresh-bold"></iconify-icon> Verificando...';
    fetch('/pages/cadastro/check-subdomain.php?subdomain=' + encodeURIComponent(s))
        .then(r => r.json())
        .then(d => {
            if (d.available) {
                statusEl.className = 'subdomain-status available';
                statusEl.innerHTML = '<iconify-icon icon="solar:check-circle-bold"></iconify-icon> ' + d.url + ' disponível!';
                subdomainValid = true;
            } else {
                statusEl.className = 'subdomain-status unavailable';
                statusEl.innerHTML = '<iconify-icon icon="solar:close-circle-bold"></iconify-icon> ' + d.message;
                subdomainValid = false;
            }
        });
}

subdomainInput.addEventListener('input', function() {
    this.value = sanitizeSubdomain(this.value);
    clearTimeout(checkTimeout);
    checkTimeout = setTimeout(() => checkSubdomain(this.value), 500);
});
storeNameInput.addEventListener('input', function() {
    if (!subdomainInput.dataset.edited) {
        const s = sanitizeSubdomain(this.value);
        if (s.length >= 3) {
            subdomainInput.value = s;
            clearTimeout(checkTimeout);
            checkTimeout = setTimeout(() => checkSubdomain(s), 500);
        }
    }
});

// Password strength
document.getElementById('password').addEventListener('input', function() {
    const b = document.getElementById('passwordStrength'), l = this.value.length;
    b.className = 'password-strength-bar';
    if (l >= 8 && /[A-Z]/.test(this.value) && /[0-9]/.test(this.value)) b.classList.add('strong');
    else if (l >= 6) b.classList.add('medium');
    else if (l > 0) b.classList.add('weak');
});

// Phone mask
document.querySelector('input[name="phone"]').addEventListener('input', function() {
    let v = this.value.replace(/\D/g, '');
    if (v.length > 11) v = v.substring(0, 11);
    if (v.length > 6) this.value = '(' + v.substring(0, 2) + ') ' + v.substring(2, 7) + '-' + v.substring(7);
    else if (v.length > 2) this.value = '(' + v.substring(0, 2) + ') ' + v.substring(2);
    else if (v.length > 0) this.value = '(' + v;
});

// Form submission
async function submitRegistration() {
    const btn = document.getElementById("btnSubmit");
    const form = document.getElementById("wizardForm");
    if (!btn || !form) return;

    btn.disabled = true;
    btn.innerHTML = '<iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon> Criando...';

    const formData = new FormData(form);

    try {
        const r = await fetch("/pages/cadastro/process.php", { method: "POST", body: formData });
        const d = await r.json();
        if (d.success) {
            document.getElementById("successUrl").textContent = d.store_url;
            document.getElementById("btnAccessStore").href = "/pages/login.php?registered=1&email=" + encodeURIComponent(formData.get("email"));
            currentStep = 5;
            updateProgress();
        } else {
            showAlert(d.message || "Erro ao criar conta");
            btn.disabled = false;
            btn.innerHTML = '<iconify-icon icon="solar:rocket-bold"></iconify-icon> Criar minha loja';
        }
    } catch (err) {
        showAlert("Erro de conexão");
        btn.disabled = false;
        btn.innerHTML = '<iconify-icon icon="solar:rocket-bold"></iconify-icon> Criar minha loja';
    }
}

// Payment Modal Functions
function openPaymentModal() {
    var selectedPlan = document.querySelector('input[name="plan_id"]:checked');
    if (!selectedPlan) { showAlert("Selecione um plano"); return; }
    var planId = selectedPlan.value;
    var planCard = selectedPlan.closest(".plan-card");
    var planName = planCard.querySelector(".plan-name").textContent;
    var planPrice = planCard.querySelector(".plan-price-value").textContent;
    document.getElementById("paymentPlanInfo").textContent = planName + " - " + planPrice + "/mês";
    document.getElementById("paymentModal").classList.add("active");
}

function closePaymentModal() {
    document.getElementById("paymentModal").classList.remove("active");
}

function selectPaymentMethod(method) {
    closePaymentModal();
    var btn = document.getElementById("btnSubmit");
    btn.disabled = true;
    btn.innerHTML = '<iconify-icon icon="solar:hourglass-bold"></iconify-icon>Redirecionando...';

    var form = document.getElementById("wizardForm");
    var formData = new FormData(form);
    formData.append("payment_method", method);

    fetch("/pages/cadastro/create-payment.php", {
        method: "POST",
        body: formData
    })
    .then(r => r.json())
    .then(d => {
        if (d.success && d.checkout_url) {
            window.location.href = d.checkout_url;
        } else {
            showAlert(d.message || "Erro ao criar pagamento");
            btn.disabled = false;
            btn.innerHTML = '<iconify-icon icon="solar:rocket-bold"></iconify-icon> Criar minha loja';
        }
    })
    .catch(err => {
        showAlert("Erro de conexão");
        btn.disabled = false;
        btn.innerHTML = '<iconify-icon icon="solar:rocket-bold"></iconify-icon> Criar minha loja';
    });
}

function handleFormSubmit(e) {
    var selectedPlan = document.querySelector('input[name="plan_id"]:checked');
    if (!selectedPlan) { e.preventDefault(); showAlert("Selecione um plano"); return false; }
    var planCard = selectedPlan.closest(".plan-card");
    var priceText = planCard.querySelector(".plan-price-value").textContent;
    var price = parseInt(priceText.replace(/\D/g, ""));
    if (price === 0) { submitRegistration(); return false; }
    e.preventDefault();
    openPaymentModal();
    return false;
}
</script>

<?php
// Incluir footer do template
include __DIR__ . '/../../templates/landing_v1/footer.php';
?>
