<?php
/**
 * P├ígina de Templates - BarberFlow SaaS
 * Permite ao usu├írio selecionar o tema da sua loja
 * Suporta tanto Barbearia/Sal├úo quanto Loja/Varejo
 */
require_once __DIR__ . '/../includes/config.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

// Buscar dados do usu├írio e loja
$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Detectar tipo de neg├│cio
$businessType = $store['business_type'] ?? ($_SESSION['business_type'] ?? 'service');
$isRetail = ($businessType === 'retail');

// Buscar plano da loja
$planStmt = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
$planStmt->execute([$store['plan_id'] ?? 1]);
$plan = $planStmt->fetch(PDO::FETCH_ASSOC);
$isPremiumPlan = in_array($plan['slug'] ?? '', ['professional', 'enterprise', 'unlimited']);

// Processar altera├º├úo de template
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['template_id'])) {
    $templateId = $_POST['template_id'];
    
    // Se for template de sistema (retail-light, barber-classic, salon-beauty, etc)
    if (strpos($templateId, 'retail-') === 0 || strpos($templateId, 'barber-') === 0 || strpos($templateId, 'salon-') === 0) {
        // Salvar como configura├º├úo especial
        $updateStmt = $pdo->prepare("UPDATE stores SET storefront_template = ?, updated_at = NOW() WHERE id = ?");
        $updateStmt->execute([$templateId, $storeId]);
        $message = 'Template atualizado com sucesso! As altera├º├Áes j├í est├úo vis├¡veis na sua loja.';
        $messageType = 'success';
        $store['storefront_template'] = $templateId;
    } else {
        // Template do banco de dados
        $templateId = (int)$templateId;
        $templateStmt = $pdo->prepare("SELECT * FROM store_templates WHERE id = ? AND is_active = 1");
        $templateStmt->execute([$templateId]);
        $template = $templateStmt->fetch(PDO::FETCH_ASSOC);

        if ($template) {
            if ($template['is_premium'] && !$isPremiumPlan) {
                $message = 'Este template ├® exclusivo para planos Premium. Fa├ºa upgrade do seu plano para us├í-lo.';
                $messageType = 'error';
            } else {
                $updateStmt = $pdo->prepare("UPDATE stores SET template_id = ?, updated_at = NOW() WHERE id = ?");
                $updateStmt->execute([$templateId, $storeId]);
                $message = 'Template atualizado com sucesso! As altera├º├Áes j├í est├úo vis├¡veis na sua loja.';
                $messageType = 'success';
                $store['template_id'] = $templateId;
            }
        } else {
            $message = 'Template n├úo encontrado.';
            $messageType = 'error';
        }
    }
}

// Buscar templates do banco de dados (mantido para compatibilidade)
try {
    $templatesStmt = $pdo->query("SELECT * FROM store_templates WHERE is_active = 1 ORDER BY is_premium ASC, category, name");
    $dbTemplates = $templatesStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $dbTemplates = [];
}

// Templates de sistema para Barbearia/Sal├úo - 2 templates distintos
$serviceSystemTemplates = [
    [
        'id' => 'barber-classic',
        'name' => 'Barbearia Cl├íssica',
        'description' => 'Design masculino e elegante com visual cl├íssico. Perfeito para barbearias tradicionais com estilo vintage e sofisticado.',
        'category' => 'barbearia',
        'is_premium' => false,
        'features' => ['Estilo masculino', 'Visual vintage', '├ìcones de barbearia', 'Cores escuras'],
        'preview' => [
            'bg' => '#0A0A0A',
            'primary' => '#CCA43B',
            'secondary' => '#8B7355',
            'card' => '#151515',
            'text' => '#FFFFFF',
            'accent' => '#D4AF37',
            'icon' => 'solar:scissors-bold'
        ]
    ],
    [
        'id' => 'salon-beauty',
        'name' => 'Sal├úo de Beleza',
        'description' => 'Design feminino e moderno com visual clean e suave. Ideal para sal├Áes de beleza, est├®tica e cabeleireiros unissex.',
        'category' => 'salao',
        'is_premium' => false,
        'features' => ['Estilo feminino', 'Visual moderno', 'Cores suaves', 'Layout elegante'],
        'preview' => [
            'bg' => '#FDF8F5',
            'primary' => '#D4A5A5',
            'secondary' => '#B8860B',
            'card' => '#FFFFFF',
            'text' => '#2D2D2D',
            'accent' => '#E8C4C4',
            'icon' => 'mdi:hair-dryer'
        ]
    ]
];

// Templates de sistema para Loja/Varejo
// Apenas templates com arquivo existente em templates/retail/{nome}/home.php
$retailSystemTemplates = [
    [
        'id' => 'retail-modern',
        'name' => 'Modern',
        'description' => 'Design moderno e elegante com tons claros. Perfeito para lojas de moda, acessórios e lifestyle.',
        'category' => 'modern',
        'is_premium' => false,
        'is_system' => true,
        'exists' => true,
        'preview' => [
            'bg' => '#FAFBFC',
            'primary' => '#2563EB',
            'accent' => '#10B981',
            'card' => '#FFFFFF',
            'text' => '#111827'
        ]
    ]
    // Templates futuros (ainda não implementados):
    // - retail-dark: Tema escuro premium
];

$currentTemplateId = $store['template_id'] ?? 1;
$currentStorefrontTemplate = $store['storefront_template'] ?? ($isRetail ? 'retail-modern' : 'barber-classic');

// Compatibilidade: converter retail-light para retail-modern
if ($currentStorefrontTemplate === 'retail-light') {
    $currentStorefrontTemplate = 'retail-modern';
}

$pageTitle = 'Templates da Loja';
include __DIR__ . '/../includes/dashboard-header.php';
include __DIR__ . '/../includes/responsive-styles.php';
?>

<style>
/* ========================================
   ESTILOS RESPONSIVOS PARA TEMPLATES
   ======================================== */

/* Templates Grid */
.templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 1.5rem;
}

@media (max-width: 768px) {
    .templates-grid {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
        gap: 1.25rem;
    }
}

@media (max-width: 480px) {
    .templates-grid {
        grid-template-columns: 1fr;
        gap: 1rem;
    }
}

/* Template Card */
.template-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
    transition: all 0.3s ease;
}

.template-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 40px rgba(0,0,0,0.15);
}

.template-card.active {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(204, 164, 59, 0.2);
}

/* Template Preview */
.template-preview {
    height: 180px;
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

@media (max-width: 480px) {
    .template-preview {
        height: 160px;
    }
}

.template-preview-header {
    padding: 12px 16px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.8rem;
    font-weight: 600;
}

.template-preview-content {
    flex: 1;
    padding: 16px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
}

.template-preview-item {
    border-radius: 8px;
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* Badge styles */
.template-badge {
    position: absolute;
    top: 12px;
    right: 12px;
    padding: 6px 12px;
    border-radius: 50px;
    font-size: 0.7rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;
}

.template-badge.active {
    background: var(--primary);
    color: #000;
}

.template-badge.premium {
    background: linear-gradient(135deg, #F59E0B, #D97706);
    color: #000;
}

.template-badge.locked {
    background: rgba(255, 255, 255, 0.1);
    color: var(--text-muted);
}

/* Template Info */
.template-info {
    padding: 20px;
}

@media (max-width: 480px) {
    .template-info {
        padding: 16px;
    }
}

.template-category {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    margin-bottom: 6px;
}

.template-name {
    font-size: 1.15rem;
    font-weight: 600;
    margin-bottom: 8px;
}

@media (max-width: 480px) {
    .template-name {
        font-size: 1.05rem;
    }
}

.template-description {
    font-size: 0.9rem;
    color: var(--text-secondary);
    line-height: 1.5;
    margin-bottom: 16px;
}

@media (max-width: 480px) {
    .template-description {
        font-size: 0.85rem;
        margin-bottom: 12px;
    }
}

/* Section Title */
.section-title {
    font-size: 1.2rem;
    font-weight: 600;
    margin-bottom: 1.25rem;
    display: flex;
    align-items: center;
    gap: 10px;
}

@media (max-width: 480px) {
    .section-title {
        font-size: 1.05rem;
        margin-bottom: 1rem;
    }
}

/* Current Template Card */
.current-template-card {
    background: var(--bg-card);
    border: 1px solid var(--primary);
    border-radius: 16px;
    padding: 24px;
    margin-bottom: 2rem;
    display: flex;
    align-items: center;
    gap: 24px;
}

@media (max-width: 768px) {
    .current-template-card {
        flex-direction: column;
        text-align: center;
        padding: 20px;
        gap: 16px;
    }
}

@media (max-width: 480px) {
    .current-template-card {
        padding: 16px;
        gap: 12px;
    }
}

.current-template-preview {
    width: 140px;
    height: 100px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2.5rem;
    flex-shrink: 0;
}

@media (max-width: 480px) {
    .current-template-preview {
        width: 100px;
        height: 80px;
        font-size: 2rem;
    }
}

.current-template-info {
    flex: 1;
}

.current-template-info h2 {
    font-size: 1.35rem;
    margin-bottom: 6px;
}

@media (max-width: 480px) {
    .current-template-info h2 {
        font-size: 1.15rem;
    }
}

.current-template-info p {
    color: var(--text-secondary);
    font-size: 0.95rem;
}

@media (max-width: 480px) {
    .current-template-info p {
        font-size: 0.85rem;
    }
    
    .current-template-card .btn {
        width: 100%;
        justify-content: center;
    }
}

/* Retail preview mockup */
.retail-preview-mockup {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.retail-preview-nav {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 0.7rem;
    font-weight: 600;
}

.retail-preview-hero {
    flex: 0 0 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.65rem;
    font-weight: 500;
}

.retail-preview-products {
    flex: 1;
    padding: 8px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 6px;
}

.retail-preview-product {
    border-radius: 4px;
    aspect-ratio: 1;
}

/* Page Header Responsivo */
.page-header h1 {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

@media (max-width: 480px) {
    .page-header h1 {
        font-size: 1.25rem;
    }
    
    .page-header p {
        font-size: 0.85rem;
    }
}

/* ========================================
   PREVIEW TEMPLATES BARBEARIA/SAL├âO
   ======================================== */

/* Preview Barbearia Cl├íssica */
.barber-preview-mockup {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.barber-preview-header {
    padding: 10px 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 0.75rem;
    font-weight: 600;
    border-bottom: 2px solid;
}

.barber-preview-hero {
    flex: 0 0 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 0.6rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.barber-preview-services {
    flex: 1;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.barber-service-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 10px;
    border-radius: 6px;
    font-size: 0.65rem;
}

.barber-service-item iconify-icon {
    font-size: 1rem;
}

/* Preview Sal├úo de Beleza */
.salon-preview-mockup {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.salon-preview-header {
    padding: 10px 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    font-size: 0.8rem;
    font-weight: 500;
}

.salon-preview-banner {
    flex: 0 0 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.6rem;
    font-weight: 500;
}

.salon-preview-grid {
    flex: 1;
    padding: 10px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
}

.salon-service-card {
    border-radius: 10px;
    padding: 10px 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 4px;
    text-align: center;
}

.salon-service-card iconify-icon {
    font-size: 1.1rem;
}

.salon-service-card span {
    font-size: 0.55rem;
    font-weight: 500;
}

/* Features List */
.template-features {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 12px;
}

.template-feature-tag {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 500;
}
</style>

<main class="main-content">
    <div class="page-header">
        <h1>
            <iconify-icon icon="solar:palette-bold"></iconify-icon> 
            Templates da Loja
        </h1>
        <p>
            <?php if ($isRetail): ?>
                Personalize a aparência da sua loja online
            <?php else: ?>
                Personalize a aparência da página de agendamentos da sua barbearia
            <?php endif; ?>
        </p>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <?php if ($isRetail): ?>
    <!-- ========================================= -->
    <!-- TEMPLATES PARA LOJA/VAREJO               -->
    <!-- ========================================= -->
    
    <!-- Template Atual -->
    <?php 
    $activeRetailTemplate = null;
    foreach ($retailSystemTemplates as $t) {
        if ($t['id'] === $currentStorefrontTemplate) {
            $activeRetailTemplate = $t;
            break;
        }
    }
    if (!$activeRetailTemplate) {
        $activeRetailTemplate = $retailSystemTemplates[0]; // Default: Elegante Claro
    }
    ?>
    <div class="current-template-card">
        <div class="current-template-preview" style="background: <?php echo $activeRetailTemplate['preview']['bg']; ?>; border: 1px solid <?php echo $activeRetailTemplate['preview']['primary']; ?>;">
            <iconify-icon icon="solar:bag-3-bold" style="color: <?php echo $activeRetailTemplate['preview']['primary']; ?>;"></iconify-icon>
        </div>
        <div class="current-template-info" style="flex: 1;">
            <h2><?php echo htmlspecialchars($activeRetailTemplate['name']); ?></h2>
            <p><?php echo htmlspecialchars($activeRetailTemplate['description']); ?></p>
        </div>
        <div class="current-template-actions" style="display: flex; gap: 0.75rem; flex-wrap: wrap;">
            <a href="/pages/template-editor.php" class="btn btn-primary">
                <iconify-icon icon="solar:palette-2-bold"></iconify-icon>
                Editar Template
            </a>
            <a href="/pages/storefront/home.php" target="_blank" class="btn btn-secondary">
                <iconify-icon icon="solar:eye-bold"></iconify-icon>
                Ver Loja
            </a>
        </div>
    </div>

    <!-- Templates Gratuitos -->
    <div style="margin-bottom: 2.5rem;">
        <h3 class="section-title">
            <iconify-icon icon="solar:star-bold" style="color: var(--primary);"></iconify-icon>
            Templates Gratuitos
        </h3>
        <div class="templates-grid">
            <?php foreach ($retailSystemTemplates as $template):
                if ($template['is_premium']) continue;
                $preview = $template['preview'];
                $isActive = $template['id'] === $currentStorefrontTemplate;
                $categoryLabels = ['classic' => 'Cl├íssico', 'modern' => 'Moderno', 'minimal' => 'Minimalista', 'bold' => 'Ousado'];
            ?>
            <div class="template-card <?php echo $isActive ? 'active' : ''; ?>">
                <div class="template-preview" style="background: <?php echo $preview['bg']; ?>;">
                    <?php if ($isActive): ?>
                    <div class="template-badge active">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                    </div>
                    <?php endif; ?>
                    
                    <!-- Retail Mockup Preview -->
                    <div class="retail-preview-mockup">
                        <div class="retail-preview-nav" style="background: <?php echo $preview['card']; ?>; color: <?php echo $preview['primary']; ?>;">
                            <iconify-icon icon="solar:bag-3-bold"></iconify-icon>
                            <span style="color: <?php echo $preview['text']; ?>;">Loja</span>
                            <iconify-icon icon="solar:cart-large-2-bold"></iconify-icon>
                        </div>
                        <div class="retail-preview-hero" style="background: linear-gradient(135deg, <?php echo $preview['primary']; ?>, <?php echo $preview['accent']; ?>); color: #fff;">
                            Banner Destaque
                        </div>
                        <div class="retail-preview-products">
                            <?php for ($i = 0; $i < 4; $i++): ?>
                            <div class="retail-preview-product" style="background: <?php echo $preview['card']; ?>; border: 1px solid <?php echo $preview['bg'] === '#FFFFFF' || $preview['bg'] === '#FAFBFC' ? '#E5E7EB' : 'rgba(255,255,255,0.1)'; ?>;"></div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
                <div class="template-info">
                    <div class="template-category" style="color: <?php echo $preview['primary']; ?>;">
                        <?php echo $categoryLabels[$template['category']] ?? 'Moderno'; ?>
                    </div>
                    <div class="template-name"><?php echo htmlspecialchars($template['name']); ?></div>
                    <div class="template-description"><?php echo htmlspecialchars($template['description']); ?></div>
                    
                    <?php if ($isActive): ?>
                    <button class="btn btn-secondary" style="width: 100%;" disabled>
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                    </button>
                    <?php else: ?>
                    <form method="POST">
                        <input type="hidden" name="template_id" value="<?php echo $template['id']; ?>">
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <iconify-icon icon="solar:palette-bold"></iconify-icon> Usar Template
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Templates Premium -->
    <div style="margin-bottom: 2rem;">
        <h3 class="section-title">
            <iconify-icon icon="solar:crown-bold" style="color: #F59E0B;"></iconify-icon>
            Templates Premium
        </h3>
        <div class="templates-grid">
            <?php foreach ($retailSystemTemplates as $template):
                if (!$template['is_premium']) continue;
                $preview = $template['preview'];
                $isActive = $template['id'] === $currentStorefrontTemplate;
                $canUse = $isPremiumPlan;
                $categoryLabels = ['classic' => 'Cl├íssico', 'modern' => 'Moderno', 'minimal' => 'Minimalista', 'bold' => 'Ousado'];
            ?>
            <div class="template-card <?php echo $isActive ? 'active' : ''; ?>" style="border-color: rgba(245, 158, 11, 0.3);">
                <div class="template-preview" style="background: <?php echo $preview['bg']; ?>;">
                    <?php if ($isActive): ?>
                    <div class="template-badge active">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                    </div>
                    <?php elseif (!$canUse): ?>
                    <div class="template-badge locked">
                        <iconify-icon icon="solar:lock-bold"></iconify-icon> Premium
                    </div>
                    <?php else: ?>
                    <div class="template-badge premium">
                        <iconify-icon icon="solar:crown-bold"></iconify-icon> Premium
                    </div>
                    <?php endif; ?>
                    
                    <!-- Retail Mockup Preview -->
                    <div class="retail-preview-mockup">
                        <div class="retail-preview-nav" style="background: <?php echo $preview['card']; ?>; color: <?php echo $preview['primary']; ?>;">
                            <iconify-icon icon="solar:bag-3-bold"></iconify-icon>
                            <span style="color: <?php echo $preview['text']; ?>;">Loja</span>
                            <iconify-icon icon="solar:cart-large-2-bold"></iconify-icon>
                        </div>
                        <div class="retail-preview-hero" style="background: linear-gradient(135deg, <?php echo $preview['primary']; ?>, <?php echo $preview['accent']; ?>); color: #fff;">
                            Banner Destaque
                        </div>
                        <div class="retail-preview-products">
                            <?php for ($i = 0; $i < 4; $i++): ?>
                            <div class="retail-preview-product" style="background: <?php echo $preview['card']; ?>; border: 1px solid <?php echo $preview['bg'] === '#FFFFFF' || $preview['bg'] === '#FAFBFC' || $preview['bg'] === '#FEF3C7' ? '#E5E7EB' : 'rgba(255,255,255,0.1)'; ?>;"></div>
                            <?php endfor; ?>
                        </div>
                    </div>
                </div>
                <div class="template-info">
                    <div class="template-category" style="color: #F59E0B;">
                        <?php echo $categoryLabels[$template['category']] ?? 'Moderno'; ?>
                    </div>
                    <div class="template-name"><?php echo htmlspecialchars($template['name']); ?></div>
                    <div class="template-description"><?php echo htmlspecialchars($template['description']); ?></div>
                    
                    <?php if ($isActive): ?>
                    <button class="btn btn-secondary" style="width: 100%;" disabled>
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                    </button>
                    <?php elseif (!$canUse): ?>
                    <a href="/pages/assinatura.php" class="btn btn-primary" style="width: 100%;">
                        <iconify-icon icon="solar:crown-bold"></iconify-icon> Fazer Upgrade
                    </a>
                    <?php else: ?>
                    <form method="POST">
                        <input type="hidden" name="template_id" value="<?php echo $template['id']; ?>">
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <iconify-icon icon="solar:palette-bold"></iconify-icon> Usar Template
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <?php else: ?>
    <!-- ========================================= -->
    <!-- TEMPLATES PARA BARBEARIA/SAL├âO           -->
    <!-- ========================================= -->
    
    <?php
    // Buscar template ativo dos templates de sistema
    $activeServiceTemplate = null;
    foreach ($serviceSystemTemplates as $t) {
        if ($t['id'] === $currentStorefrontTemplate) {
            $activeServiceTemplate = $t;
            break;
        }
    }
    if (!$activeServiceTemplate) {
        $activeServiceTemplate = $serviceSystemTemplates[0]; // Default: Barbearia Cl├íssica
    }
    ?>
    
    <!-- Template Atual -->
    <div class="current-template-card">
        <div class="current-template-preview" style="background: <?php echo $activeServiceTemplate['preview']['bg']; ?>; border: 1px solid <?php echo $activeServiceTemplate['preview']['primary']; ?>;">
            <iconify-icon icon="<?php echo $activeServiceTemplate['preview']['icon']; ?>" style="color: <?php echo $activeServiceTemplate['preview']['primary']; ?>;"></iconify-icon>
        </div>
        <div class="current-template-info" style="flex: 1;">
            <h2><?php echo htmlspecialchars($activeServiceTemplate['name']); ?></h2>
            <p><?php echo htmlspecialchars($activeServiceTemplate['description']); ?></p>
        </div>
        <div class="current-template-actions" style="display: flex; gap: 0.75rem; flex-wrap: wrap;">
            <a href="/pages/template-editor.php" class="btn btn-primary">
                <iconify-icon icon="solar:palette-2-bold"></iconify-icon>
                Editar Template
            </a>
            <a href="<?php echo get_store_url($store); ?>" target="_blank" class="btn btn-secondary">
                <iconify-icon icon="solar:eye-bold"></iconify-icon>
                Ver P├ígina
            </a>
        </div>
    </div>

    <!-- Escolha seu Template -->
    <div style="margin-bottom: 2.5rem;">
        <h3 class="section-title">
            <iconify-icon icon="solar:palette-bold" style="color: var(--primary);"></iconify-icon>
            Escolha o Estilo do seu Neg├│cio
        </h3>
        <p style="color: var(--text-muted); margin-bottom: 1.5rem;">
            Selecione o template que melhor representa seu estabelecimento. Ambos s├úo gratuitos!
        </p>
        
        <div class="templates-grid">
            <?php foreach ($serviceSystemTemplates as $template):
                $preview = $template['preview'];
                $isActive = $template['id'] === $currentStorefrontTemplate;
                $isBarber = $template['id'] === 'barber-classic';
            ?>
            <div class="template-card <?php echo $isActive ? 'active' : ''; ?>">
                <div class="template-preview" style="background: <?php echo $preview['bg']; ?>;">
                    <?php if ($isActive): ?>
                    <div class="template-badge active">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Ativo
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($isBarber): ?>
                    <!-- Preview Barbearia Cl├íssica -->
                    <div class="barber-preview-mockup">
                        <div class="barber-preview-header" style="background: <?php echo $preview['card']; ?>; color: <?php echo $preview['primary']; ?>; border-color: <?php echo $preview['primary']; ?>;">
                            <iconify-icon icon="solar:scissors-bold"></iconify-icon>
                            <span style="color: <?php echo $preview['text']; ?>; font-size: 0.7rem;">BARBEARIA</span>
                            <iconify-icon icon="solar:menu-dots-bold"></iconify-icon>
                        </div>
                        <div class="barber-preview-hero" style="background: linear-gradient(135deg, <?php echo $preview['primary']; ?>, <?php echo $preview['secondary']; ?>); color: #000;">
                            <iconify-icon icon="solar:scissors-bold"></iconify-icon>
                            AGENDE AGORA
                        </div>
                        <div class="barber-preview-services" style="background: <?php echo $preview['bg']; ?>;">
                            <div class="barber-service-item" style="background: <?php echo $preview['card']; ?>; color: <?php echo $preview['text']; ?>;">
                                <iconify-icon icon="mdi:content-cut" style="color: <?php echo $preview['primary']; ?>;"></iconify-icon>
                                Corte Degrad├¬
                            </div>
                            <div class="barber-service-item" style="background: <?php echo $preview['card']; ?>; color: <?php echo $preview['text']; ?>;">
                                <iconify-icon icon="mdi:face-man-shimmer" style="color: <?php echo $preview['primary']; ?>;"></iconify-icon>
                                Barba Completa
                            </div>
                        </div>
                    </div>
                    <?php else: ?>
                    <!-- Preview Sal├úo de Beleza -->
                    <div class="salon-preview-mockup">
                        <div class="salon-preview-header" style="background: <?php echo $preview['card']; ?>; color: <?php echo $preview['primary']; ?>;">
                            <iconify-icon icon="mdi:flower-tulip"></iconify-icon>
                            <span style="color: <?php echo $preview['text']; ?>;">Sal├úo de Beleza</span>
                        </div>
                        <div class="salon-preview-banner" style="background: linear-gradient(135deg, <?php echo $preview['primary']; ?>, <?php echo $preview['accent']; ?>); color: #fff;">
                            Ô£¿ Agende seu hor├írio Ô£¿
                        </div>
                        <div class="salon-preview-grid" style="background: <?php echo $preview['bg']; ?>;">
                            <div class="salon-service-card" style="background: <?php echo $preview['card']; ?>; border: 1px solid <?php echo $preview['accent']; ?>;">
                                <iconify-icon icon="mdi:hair-dryer" style="color: <?php echo $preview['primary']; ?>;"></iconify-icon>
                                <span style="color: <?php echo $preview['text']; ?>;">Cabelo</span>
                            </div>
                            <div class="salon-service-card" style="background: <?php echo $preview['card']; ?>; border: 1px solid <?php echo $preview['accent']; ?>;">
                                <iconify-icon icon="mdi:hand-extended" style="color: <?php echo $preview['primary']; ?>;"></iconify-icon>
                                <span style="color: <?php echo $preview['text']; ?>;">Unhas</span>
                            </div>
                            <div class="salon-service-card" style="background: <?php echo $preview['card']; ?>; border: 1px solid <?php echo $preview['accent']; ?>;">
                                <iconify-icon icon="mdi:spa" style="color: <?php echo $preview['primary']; ?>;"></iconify-icon>
                                <span style="color: <?php echo $preview['text']; ?>;">Est├®tica</span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="template-info">
                    <div class="template-category" style="color: <?php echo $preview['primary']; ?>;">
                        <?php echo strtoupper($template['category']); ?>
                    </div>
                    <div class="template-name"><?php echo htmlspecialchars($template['name']); ?></div>
                    <div class="template-description"><?php echo htmlspecialchars($template['description']); ?></div>
                    
                    <!-- Features -->
                    <div class="template-features">
                        <?php foreach ($template['features'] as $feature): ?>
                        <span class="template-feature-tag" style="background: <?php echo $preview['primary']; ?>20; color: <?php echo $preview['primary']; ?>;">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            <?php echo $feature; ?>
                        </span>
                        <?php endforeach; ?>
                    </div>
                    
                    <?php if ($isActive): ?>
                    <button class="btn btn-secondary" style="width: 100%;" disabled>
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Template Ativo
                    </button>
                    <?php else: ?>
                    <form method="POST">
                        <input type="hidden" name="template_id" value="<?php echo $template['id']; ?>">
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <iconify-icon icon="solar:palette-bold"></iconify-icon> Usar Este Template
                        </button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <!-- Dica -->
    <div class="card" style="background: linear-gradient(135deg, var(--primary-alpha) 0%, var(--card-bg) 100%); border: 1px solid var(--primary); padding: 1.5rem;">
        <div style="display: flex; align-items: flex-start; gap: 1rem;">
            <iconify-icon icon="solar:lightbulb-bold" style="font-size: 2rem; color: var(--primary); flex-shrink: 0;"></iconify-icon>
            <div>
                <h3 style="font-size: 1.1rem; margin-bottom: 0.5rem;">Dica</h3>
                <p style="color: var(--text-muted); margin: 0; font-size: 0.9rem;">
                    O template escolhido define o visual da sua p├ígina de agendamentos que seus clientes ir├úo ver. 
                    Voc├¬ pode trocar de template a qualquer momento sem perder seus dados.
                </p>
            </div>
        </div>
    </div>
    <?php endif; ?>
</main>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
