{% extends 'layouts/company.twig' %}

{% block title %}{{ product.nome }} - {{ app_name }}{% endblock %}

{% block content %}
<div class="page-header d-flex justify-content-between align-items-center">
    <div>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{ url('products') }}">Produtos</a></li>
                <li class="breadcrumb-item active">{{ product.nome }}</li>
            </ol>
        </nav>
        <h1 class="page-title">{{ product.nome }}</h1>
    </div>
    <div class="btn-group">
        {% if product.tipo not in ['wlink', 'video_instagram', 'pesquisa_qualidade'] %}
        <a href="{{ url('batches/create?product_id=' ~ product.id) }}" class="btn btn-success">
            <i class="bi bi-plus-lg"></i> Novo Lote
        </a>
        {% endif %}
        {% if product.tipo == 'primeiro_milhao' %}
        <button type="button" class="btn btn-outline-success" data-bs-toggle="collapse" data-bs-target="#financialProductsPanel" aria-expanded="false" aria-controls="financialProductsPanel">
            <i class="bi bi-graph-up-arrow"></i> Produtos Financeiros
        </button>
        {% endif %}
        {% if product.tipo == 'atacadista' %}
        <a href="{{ url('products/' ~ product.id ~ '/atacadista') }}" class="btn" style="background:#111111;color:#fff;border-color:#111111;">
            <i class="bi bi-phone"></i> Feed Atacadista
        </a>
        {% endif %}
        {% if product.tipo == 'comunidade' %}
        <a href="{{ url('products/' ~ product.id ~ '/community') }}" class="btn btn-pink" style="background:#ec4899;color:#fff;border-color:#ec4899;">
            <i class="bi bi-people-fill"></i> Comunidade
        </a>
        {% endif %}
        {% if product.tipo == 'fit' %}
        <a href="{{ url('products/' ~ product.id ~ '/player') }}" class="btn" style="background:#8b5cf6;color:#fff;border-color:#8b5cf6;">
            <i class="bi bi-music-note-list"></i> Playlists
        </a>
        <a href="{{ url('products/' ~ product.id ~ '/fit-workouts') }}" class="btn" style="background:#14b8a6;color:#fff;border-color:#14b8a6;">
            <i class="bi bi-activity"></i> Treinos
        </a>
        {% endif %}
        {% if product.tipo == 'puzzle' %}
        <a href="{{ url('products/' ~ product.id ~ '/puzzle') }}" class="btn" style="background:#6366f1;color:#fff;border-color:#6366f1;">
            <i class="bi bi-puzzle"></i> Imagens
        </a>
        {% endif %}
        {% if product.tipo == 'album' %}
        <a href="{{ url('products/' ~ product.id ~ '/album') }}" class="btn" style="background:#f59e0b;color:#fff;border-color:#f59e0b;">
            <i class="bi bi-images"></i> Álbuns
        </a>
        {% endif %}
        {% if product.tipo == 'linkbio' %}
        <a href="{{ url('products/' ~ product.id ~ '/linkbio') }}" class="btn" style="background:#06b6d4;color:#fff;border-color:#06b6d4;">
            <i class="bi bi-link-45deg"></i> Gerir Links
        </a>
        {% endif %}
        <button type="button" class="btn" style="background:#06b6d4;color:#fff;border-color:#06b6d4;" onclick="abrirLeadsCliques()">
            <i class="bi bi-people"></i> Clientes &amp; Cliques
        </button>
        <a href="{{ url('products/' ~ product.id ~ '/edit') }}" class="btn btn-secondary">
            <i class="bi bi-pencil"></i> Editar
        </a>
    </div>
</div>

{% if product.tipo == 'primeiro_milhao' %}
<div class="collapse mb-4" id="financialProductsPanel">
    <div class="card border-success">
        <div class="card-header bg-success bg-opacity-10 border-success">
            <h6 class="mb-0 text-success">
                <i class="bi bi-graph-up-arrow me-1"></i> Produtos financeiros
            </h6>
            <small class="text-muted">No que investir para acelerar seus objetivos.</small>
        </div>
        <div class="card-body">
            <form method="POST" action="{{ url('products/' ~ product.id) }}">
                {{ csrf_field()|raw }}
                <input type="hidden" name="nome" value="{{ product.nome }}">
                <input type="hidden" name="tipo" value="{{ product.tipo }}">
                <input type="hidden" name="status" value="{{ product.status == 'ativo' ? '1' : '0' }}">
                <input type="hidden" name="redirect_url" value="{{ product.redirect_url|default('') }}">

                <div id="primeiroMilhaoProductsContainerShow">
                    {% if primeiroMilhaoProducts is defined and primeiroMilhaoProducts|length > 0 %}
                        {% for item in primeiroMilhaoProducts %}
                        <div class="border rounded-3 p-2 mb-2">
                            <div class="mb-2">
                                <label class="form-label small mb-1">Produto</label>
                                <input type="text" class="form-control" name="primeiro_milhao_produto_nome[]" value="{{ item.nome }}" placeholder="Ex: CDB a 105% do CDI">
                            </div>
                            <div class="mb-2">
                                <label class="form-label small mb-1">Descrição</label>
                                <textarea class="form-control" name="primeiro_milhao_produto_descricao[]" rows="2" placeholder="Ex: retorno líquido acima de 1% ao mês com FGC">{{ item.descricao }}</textarea>
                            </div>
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="this.parentElement.remove()">
                                <i class="bi bi-trash"></i> Remover
                            </button>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="border rounded-3 p-2 mb-2">
                            <div class="mb-2">
                                <label class="form-label small mb-1">Produto</label>
                                <input type="text" class="form-control" name="primeiro_milhao_produto_nome[]" placeholder="Ex: CDB a 105% do CDI">
                            </div>
                            <div class="mb-2">
                                <label class="form-label small mb-1">Descrição</label>
                                <textarea class="form-control" name="primeiro_milhao_produto_descricao[]" rows="2" placeholder="Ex: retorno líquido acima de 1% ao mês com FGC"></textarea>
                            </div>
                            <button type="button" class="btn btn-outline-danger btn-sm" onclick="this.parentElement.remove()">
                                <i class="bi bi-trash"></i> Remover
                            </button>
                        </div>
                    {% endif %}
                </div>

                <div class="d-flex gap-2 mt-2">
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="addPrimeiroMilhaoProdutoRowShow()">
                        <i class="bi bi-plus-lg"></i> Adicionar produto financeiro
                    </button>
                    <button type="submit" class="btn btn-success btn-sm">
                        <i class="bi bi-check-lg"></i> Salvar produtos financeiros
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
{% endif %}

<!-- Modal Clientes & Cliques -->
<div class="modal fade" id="leadsClicksModal" tabindex="-1">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-people me-2"></i>Clientes & Cliques — {{ product.nome }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                {% if product.tipo == 'fit' %}
                <form action="{{ url('products/' ~ product.id ~ '/fit-banner') }}" method="POST" enctype="multipart/form-data" class="p-3 border-bottom bg-light">
                    {{ csrf_field()|raw }}
                    <h6 class="mb-2"><i class="bi bi-phone me-1"></i>Banner diário no app FIT (9:16)</h6>
                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" id="fit_popup_banner_enabled" name="fit_popup_banner_enabled" value="1" {{ product.fit_popup_banner_enabled ? 'checked' : '' }}>
                        <label class="form-check-label" for="fit_popup_banner_enabled">Exibir 1 vez por dia para cada cliente</label>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-5">
                            <label for="fit_popup_banner_image" class="form-label mb-1">Imagem do banner</label>
                            <input type="file" class="form-control form-control-sm" id="fit_popup_banner_image" name="fit_popup_banner_image" accept="image/jpeg,image/png,image/webp" data-crop-type="fit_banner_9x16">
                            <small class="text-muted">Formato 9:16 recomendado (ex.: 1080x1920).</small>
                        </div>
                        <div class="col-md-5">
                            <label for="fit_popup_banner_link" class="form-label mb-1">Link ao clicar (opcional)</label>
                            <input type="url" class="form-control form-control-sm" id="fit_popup_banner_link" name="fit_popup_banner_link" value="{{ product.fit_popup_banner_link|default('') }}" placeholder="https://...">
                            <small class="text-muted">Se preenchido, o banner abre esse link.</small>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="submit" class="btn btn-sm btn-primary w-100">
                                <i class="bi bi-save me-1"></i>Salvar
                            </button>
                        </div>
                    </div>
                    {% if product.fit_popup_banner_image %}
                    <div class="mt-2 d-flex align-items-center gap-2">
                        <img src="{{ app_url }}/public/uploads/{{ product.fit_popup_banner_image }}" alt="Banner FIT" style="width:56px;height:100px;object-fit:cover;border-radius:8px;border:1px solid #d1d5db;">
                        <div class="small text-muted">Banner atual carregado.</div>
                        <div class="form-check ms-auto">
                            <input class="form-check-input" type="checkbox" id="fit_popup_banner_remove_image" name="fit_popup_banner_remove_image" value="1">
                            <label class="form-check-label small" for="fit_popup_banner_remove_image">Remover imagem</label>
                        </div>
                    </div>
                    {% endif %}
                </form>
                {% endif %}
                <!-- Barra de pesquisa -->
                <div class="p-3 border-bottom">
                    <input type="text" class="form-control" id="lcSearch" placeholder="Pesquisar por nome, telefone ou lote…">
                </div>
                <div id="lcLoading" class="text-center py-5">
                    <div class="spinner-border text-primary"></div>
                    <p class="mt-2 text-muted">Carregando…</p>
                </div>
                <div id="lcContent" style="display:none;">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="lcTable">
                            <thead class="table-light sticky-top">
                                <tr>
                                    <th>Cliente</th>
                                    <th>Telefone</th>
                                    <th>Lote</th>
                                    <th class="text-center">Cliques</th>
                                    <th>Primeiro Acesso</th>
                                    <th>Último Acesso</th>
                                    <th>Cadastro</th>
                                </tr>
                            </thead>
                            <tbody id="lcBody"></tbody>
                        </table>
                    </div>
                    <div class="p-3 border-top text-muted small" id="lcSummary"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-4">
        <div class="card mb-4">
            <div class="card-body">
                {% if product.status == 'ativo' %}
                    <span class="badge bg-success mb-3">Ativo</span>
                {% else %}
                    <span class="badge bg-danger mb-3">Inativo</span>
                {% endif %}

                {% if product.descricao %}
                    <p class="text-muted">{{ product.descricao }}</p>
                {% endif %}

                <hr>

                {% if product.tipo == 'comunidade' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#ec4899;"><i class="bi bi-people-fill"></i> Comunidade</span></p>
                    <a href="{{ url('products/' ~ product.id ~ '/community') }}" class="btn btn-sm w-100 mb-2" style="background:#ec4899;color:#fff;">
                        <i class="bi bi-people-fill"></i> Gerenciar Comunidade
                    </a>
                    {% if community_token %}
                    <p class="mb-2">
                        <strong>Página da Comunidade:</strong><br>
                        <a href="{{ app_url }}/community.php?token={{ community_token }}" target="_blank" class="text-break small">
                            {{ app_url }}/community.php?token={{ community_token }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </p>
                    {% else %}
                    <p class="small text-muted mb-2">
                        Crie um lote para gerar o link da página da comunidade.
                    </p>
                    {% endif %}
                {% elseif product.tipo == 'sorteio' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#8b5cf6;"><i class="bi bi-gift"></i> Sorteio</span></p>
                    {% if sorteio_token %}
                    <p class="mb-2">
                        <strong>Página do Sorteio:</strong><br>
                        <a href="{{ app_url }}/sorteio.php?token={{ sorteio_token }}" target="_blank" class="text-break small">
                            {{ app_url }}/sorteio.php?token={{ sorteio_token }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </p>
                    {% else %}
                    <p class="small text-muted mb-2">
                        Crie um lote para gerar o link da página do sorteio.
                    </p>
                    {% endif %}
                    {% if product.sorteio_data %}
                    <p class="mb-1"><strong>Data do Sorteio:</strong></p>
                    <p><span class="badge bg-purple" style="background:#8b5cf6;">{{ product.sorteio_data|date('d/m/Y') }}</span></p>
                    {% endif %}
                    {% if product.sorteio_imagem %}
                    <p class="mb-1"><strong>Imagem do Prêmio:</strong></p>
                    <img src="{{ app_url }}/public/uploads/{{ product.sorteio_imagem }}" alt="Prêmio" style="max-width:150px; border-radius:10px;" class="mb-2">
                    {% endif %}
                {% elseif product.tipo == 'puzzle' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#6366f1;"><i class="bi bi-puzzle"></i> Quebra-Cabeça</span></p>
                    {% if product.puzzle_mensagem %}
                    <p class="small text-muted mb-0">"{{ product.puzzle_mensagem|slice(0,60) }}{% if product.puzzle_mensagem|length > 60 %}...{% endif %}"</p>
                    {% endif %}
                {% elseif product.tipo == 'wlink' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#25d366;"><i class="bi bi-whatsapp"></i> Link WhatsApp</span></p>
                    
                    <div class="alert alert-success py-2 px-3 mb-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-cursor-fill me-1"></i> Cliques</span>
                            <strong class="fs-5">{{ product.wlink_clicks|default(0) }}</strong>
                        </div>
                    </div>

                    <p class="mb-2">
                        <strong>Link para compartilhar:</strong><br>
                        <a href="{{ app_url }}/wlink.php?id={{ product.id }}" target="_blank" class="text-break small" id="wlinkUrl">
                            {{ app_url }}/wlink.php?id={{ product.id }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </p>
                    <button type="button" class="btn btn-sm btn-outline-success w-100 mb-2" onclick="copyWlinkUrl()">
                        <i class="bi bi-clipboard"></i> Copiar Link
                    </button>

                    {% if product.wlink_phone %}
                    <p class="mb-1"><strong>Telefone:</strong></p>
                    <p class="text-muted">+{{ product.wlink_phone }}</p>
                    {% endif %}

                    {% if product.wlink_message %}
                    <p class="mb-1"><strong>Mensagem:</strong></p>
                    <p class="text-muted small">"{{ product.wlink_message|slice(0,100) }}{% if product.wlink_message|length > 100 %}...{% endif %}"</p>
                    {% endif %}

                    {% if product.wlink_image %}
                    <p class="mb-1"><strong>Imagem:</strong></p>
                    <img src="{{ app_url }}/public/uploads/{{ product.wlink_image }}" alt="Imagem WhatsApp" style="max-width:150px; border-radius:10px;" class="mb-2">
                    {% endif %}

                {% elseif product.tipo == 'linkbio' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#06b6d4;"><i class="bi bi-link-45deg"></i> Link Dinâmico</span></p>
                    {% if linkbio_token %}
                    <p class="mb-2">
                        <strong>Página pública:</strong><br>
                        <a href="{{ app_url }}/linkbio.php?token={{ linkbio_token }}" target="_blank" class="text-break small">
                            {{ app_url }}/linkbio.php?token={{ linkbio_token }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </p>
                    <a href="{{ url('products/' ~ product.id ~ '/linkbio') }}" class="btn btn-sm w-100 mb-2" style="background:#06b6d4;color:#fff;">
                        <i class="bi bi-link-45deg"></i> Gerir Links
                    </a>
                    {% else %}
                    <p class="small text-muted mb-2">Crie um lote para gerar o link da página.</p>
                    {% endif %}
                {% elseif product.tipo == 'fit' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#14b8a6;"><i class="bi bi-activity"></i> FIT</span></p>
                    {% if product.fit_logo %}
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <img src="{{ app_url }}/public/uploads/{{ product.fit_logo }}" style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid #14b8a6;">
                        <small class="text-muted">Logo personalizada</small>
                    </div>
                    {% endif %}
                {% elseif product.tipo == 'autenticidade' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#2563eb;"><i class="bi bi-patch-check"></i> Autenticidade</span></p>
                    {% if product.auth_logo %}
                    <div class="d-flex align-items-center gap-2 mb-2">
                        <img src="{{ app_url }}/public/uploads/{{ product.auth_logo }}" style="width:40px;height:40px;border-radius:50%;object-fit:cover;border:2px solid #2563eb;">
                        <small class="text-muted">Logo personalizada</small>
                    </div>
                    {% endif %}
                    <p class="mb-2">
                        <strong>URL final pós autenticação:</strong><br>
                        <a href="{{ product.redirect_url }}" target="_blank" class="text-break small">
                            {{ product.redirect_url }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </p>
                    {% if product.auth_whatsapp %}
                    <p class="mb-1"><strong>WhatsApp denúncias:</strong></p>
                    <p class="text-muted">+{{ product.auth_whatsapp }}</p>
                    {% endif %}
                {% elseif product.tipo == 'atacadista' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#111111;"><i class="bi bi-phone"></i> Atacadista</span></p>
                    <a href="{{ url('products/' ~ product.id ~ '/atacadista') }}" class="btn btn-sm w-100 mb-2" style="background:#111111;color:#fff;">
                        <i class="bi bi-phone"></i> Gerenciar Feed
                    </a>
                    {% if atacadista_token %}
                    <p class="mb-2">
                        <strong>Página pública:</strong><br>
                        <a href="{{ app_url }}/public/atacadista.php?token={{ atacadista_token }}" target="_blank" class="text-break small">
                            {{ app_url }}/public/atacadista.php?token={{ atacadista_token }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </p>
                    {% else %}
                    <p class="small text-muted mb-2">
                        Crie um lote para gerar o link da página Atacadista.
                    </p>
                    {% endif %}
                {% elseif product.tipo == 'video_instagram' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#e1306c;"><i class="bi bi-instagram"></i> Vídeo Instagram</span></p>
                    {% if video_instagram_token %}
                    <p class="mb-2"><strong>Página pública:</strong><br>
                        <a href="{{ app_url }}/r/{{ video_instagram_token }}" target="_blank" class="text-break small">{{ app_url }}/r/{{ video_instagram_token }} <i class="bi bi-box-arrow-up-right"></i></a>
                    </p>
                    {% else %}
                    <p class="small text-muted mb-2">Crie um lote para gerar e visualizar o link público.</p>
                    {% endif %}
                {% elseif product.tipo == 'pesquisa_qualidade' %}
                    <p class="mb-1"><strong>Tipo:</strong></p>
                    <p><span class="badge" style="background:#2563eb;"><i class="bi bi-clipboard2-check"></i> Pesquisa de Qualidade</span></p>
                    {% if pesquisa_qualidade_token %}
                    <p class="mb-2"><strong>Página pública:</strong><br>
                        <a href="{{ app_url }}/r/{{ pesquisa_qualidade_token }}" target="_blank" class="text-break small">{{ app_url }}/r/{{ pesquisa_qualidade_token }} <i class="bi bi-box-arrow-up-right"></i></a>
                    </p>
                    {% endif %}
                    <p class="mb-1"><strong>Título:</strong> {{ product.pesquisa_qualidade_titulo ?: product.nome }}</p>
                    {% if product.pesquisa_qualidade_premio_ativo and product.pesquisa_qualidade_premio_texto %}
                    <p class="mb-1"><strong>Prêmio:</strong> {{ product.pesquisa_qualidade_premio_texto }}</p>
                    {% endif %}
                    {% if product.pesquisa_qualidade_ganhador %}
                    <p class="mb-1"><strong>Ganhador:</strong> {{ product.pesquisa_qualidade_ganhador }}</p>
                    {% endif %}
                {% else %}
                    <p class="mb-1"><strong>URL de Redirecionamento:</strong></p>
                    <p class="text-break small">
                        {% if product.redirect_url %}
                        <a href="{{ product.redirect_url }}" target="_blank">
                            {{ product.redirect_url }}
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                        {% else %}
                        <span class="text-muted">Nenhuma URL configurada</span>
                        {% endif %}
                    </p>
                {% endif %}
            </div>
        </div>

        <!-- Stats -->
        <div class="card {% if product.tipo == 'fit' %}mb-4{% endif %}">
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6 mb-3">
                        <h3 class="text-primary mb-0">{{ product.stats.batches }}</h3>
                        <small class="text-muted">Lotes</small>
                    </div>
                    <div class="col-6 mb-3">
                        <h3 class="text-success mb-0">{{ product.stats.links }}</h3>
                        <small class="text-muted">Links</small>
                    </div>
                    <div class="col-6">
                        <h3 class="text-info mb-0">{{ product.stats.clicks }}</h3>
                        <small class="text-muted">Cliques</small>
                    </div>
                    <div class="col-6">
                        <h3 class="text-warning mb-0">{{ product.stats.leads }}</h3>
                        <small class="text-muted">Leads</small>
                    </div>
                </div>
            </div>
        </div>

        {% if product.tipo == 'pesquisa_qualidade' %}
        <div class="card mb-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-3">
                    <div>
                        <p class="fw-semibold mb-1" style="color:#2563eb;"><i class="bi bi-clipboard2-check me-1"></i> Pesquisa de Qualidade</p>
                        <small class="text-muted">{{ pesquisa_qualidade_response_count }} resposta(s) · {{ pesquisa_qualidade_eligible_count }} elegível(is) ao prêmio</small>
                    </div>
                    <div class="d-flex flex-wrap gap-2">
                        {% if pesquisa_qualidade_response_count > 0 %}
                        <a href="{{ url('products/' ~ product.id ~ '/pesquisa-qualidade/respostas') }}" class="btn btn-outline-primary btn-sm">
                            <i class="bi bi-eye me-1"></i> Ver todas as respostas
                        </a>
                        {% endif %}
                        {% if product.pesquisa_qualidade_premio_ativo and pesquisa_qualidade_eligible_count > 0 %}
                        <form method="post" action="{{ url('products/' ~ product.id ~ '/pesquisa-qualidade/sortear') }}" onsubmit="return confirm('Sortear um ganhador aleatório entre os participantes elegíveis?');">
                            <input type="hidden" name="_csrf_token" value="{{ csrf_token }}">
                            <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-shuffle me-1"></i> Sortear ganhador</button>
                        </form>
                        {% endif %}
                    </div>
                </div>

                {% if product.pesquisa_qualidade_ganhador %}
                <div class="alert alert-success">
                    <div class="fw-bold mb-1"><i class="bi bi-trophy-fill me-1"></i> Já houve ganhador para este prêmio</div>
                    <div>
                        <strong>E-mail do ganhador:</strong>
                        {% if product.pesquisa_qualidade_ganhador_email %}
                            {{ product.pesquisa_qualidade_ganhador_email }}
                        {% else %}
                            {{ product.pesquisa_qualidade_ganhador }}
                        {% endif %}
                    </div>
                    {% if product.pesquisa_qualidade_premio_data %}
                    <div><strong>Data do prêmio:</strong> {{ product.pesquisa_qualidade_premio_data|date('d/m/Y') }}</div>
                    {% endif %}
                </div>
                {% endif %}

                {% if product.pesquisa_qualidade_premio_ativo and product.pesquisa_qualidade_premio_texto %}
                <div class="mb-3 p-3 rounded-3" style="background:#fff7ed;color:#9a3412;font-weight:600;">
                    {{ product.pesquisa_qualidade_premio_texto }}
                </div>
                {% endif %}

                <form method="post" action="{{ url('products/' ~ product.id ~ '/pesquisa-qualidade/ganhador') }}" class="mb-3">
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}">
                    <label class="form-label">Ganhador</label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="pesquisa_qualidade_ganhador" value="{{ product.pesquisa_qualidade_ganhador }}" placeholder="Nome, e-mail ou telefone do ganhador">
                        <button type="submit" class="btn btn-outline-primary">Salvar</button>
                    </div>
                </form>

                {% if pesquisa_qualidade_questions|length > 0 %}
                <p class="small text-muted mb-2"><strong>{{ pesquisa_qualidade_questions|length }}</strong> pergunta(s) configurada(s).</p>
                {% endif %}

                {% if pesquisa_qualidade_responses|length > 0 %}
                <div class="table-responsive">
                    <table class="table table-sm align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Data</th>
                                <th>Contato</th>
                                <th>Prêmio</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for resp in pesquisa_qualidade_responses %}
                            <tr>
                                <td>{{ resp.created_at|date('d/m/Y H:i') }}</td>
                                <td>
                                    {% if resp.email %}{{ resp.email }}{% endif %}
                                    {% if resp.telefone %}<br><small>{{ resp.telefone }}</small>{% endif %}
                                    {% if not resp.email and not resp.telefone %}<span class="text-muted">—</span>{% endif %}
                                </td>
                                <td>{% if resp.elegivel_premio %}<span class="badge bg-success">Elegível</span>{% else %}<span class="badge bg-secondary">Somente pesquisa</span>{% endif %}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <a href="{{ url('products/' ~ product.id ~ '/pesquisa-qualidade/respostas') }}" class="btn btn-primary">
                        <i class="bi bi-fullscreen me-1"></i> Abrir tela completa de respostas
                    </a>
                </div>
                {% else %}
                <p class="text-muted mb-0">Nenhuma resposta recebida ainda.</p>
                {% endif %}
            </div>
        </div>
        {% endif %}

        {% if product.tipo == 'fit' %}
        {% set storage_mb = (fit_storage_bytes / 1048576) %}
        <div class="card">
            <div class="card-body">
                <p class="fw-semibold mb-3" style="color:#7c3aed;">
                    <i class="bi bi-hdd me-1"></i> Armazenamento Playlists
                </p>
                <div class="row text-center">
                    <div class="col-4">
                        <h4 class="mb-0" style="color:#7c3aed;">{{ fit_playlist_count }}</h4>
                        <small class="text-muted">Playlists</small>
                    </div>
                    <div class="col-4">
                        <h4 class="mb-0" style="color:#7c3aed;">{{ fit_track_count }}</h4>
                        <small class="text-muted">Faixas</small>
                    </div>
                    <div class="col-4">
                        <h4 class="mb-0" style="color:#7c3aed;">
                            {% if storage_mb >= 1024 %}
                                {{ (storage_mb / 1024)|round(1) }} GB
                            {% else %}
                                {{ storage_mb|round(1) }} MB
                            {% endif %}
                        </h4>
                        <small class="text-muted">Usado</small>
                    </div>
                </div>
                <div class="mt-3">
                    {% set pct_raw = ((storage_mb / 500) * 100)|round(0) %}
                    {% set pct = pct_raw > 100 ? 100 : pct_raw %}
                    <div class="d-flex justify-content-between mb-1">
                        <small class="text-muted">{{ storage_mb|round(1) }} MB de 500 MB</small>
                        <small class="text-muted">{{ pct }}%</small>
                    </div>
                    <div class="progress" style="height:8px;">
                        <div class="progress-bar" role="progressbar"
                             style="width:{{ pct }}%; background:{% if pct >= 90 %}#ef4444{% elseif pct >= 70 %}#f59e0b{% else %}#7c3aed{% endif %};"
                             aria-valuenow="{{ pct }}" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <div class="col-lg-8">

        <!-- Cliques por Mês -->
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0"><i class="bi bi-bar-chart-line me-2"></i>Cliques por Mês</h5>
                <select class="form-select form-select-sm w-auto" id="monthFilter">
                    <option value="">Todos os meses</option>
                    {% for row in clicks_by_month %}
                    <option value="{{ row.mes }}">{{ row.mes_label }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="card-body">
                {% if clicks_by_month|length == 0 %}
                    <p class="text-muted text-center py-3 mb-0">Nenhum clique registado nos últimos 12 meses.</p>
                {% else %}
                <!-- Barras -->
                <div id="chartArea" class="d-flex align-items-end gap-1" style="height:120px;">
                        {% for row in clicks_by_month %}
                    {% set pct = clicks_max > 0 ? ((row.total / clicks_max) * 100)|round : 0 %}
                    <div class="chart-bar-wrap flex-fill text-center" data-mes="{{ row.mes }}" data-total="{{ row.total }}" data-label="{{ row.mes_label }}">
                        <div class="chart-bar-val small text-muted mb-1" style="font-size:0.7rem;">{{ row.total }}</div>
                        <div class="chart-bar rounded-top" style="height:{{ pct > 0 ? pct : 2 }}%; background:#6366f1; min-height:4px; transition:opacity .2s;"></div>
                        <div class="chart-bar-lbl" style="font-size:0.65rem; color:#6b7280; margin-top:2px;">{{ row.mes_label|split('/')|first }}/{{ row.mes_label|split('/')|last|slice(2,2) }}</div>
                    </div>
                    {% endfor %}
                </div>
                <hr class="my-3">
                <!-- Resumo do mês seleccionado -->
                <div id="monthSummary" class="text-center">
                    <span class="text-muted small">Seleccione um mês ou veja o total abaixo</span>
                    <div class="mt-2">
                        <span class="display-6 fw-bold text-primary" id="summaryTotal">
                            {{ clicks_total }}
                        </span>
                        <div class="text-muted small" id="summaryLabel">cliques totais nos últimos 12 meses (cada acesso +1)</div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>

        <div class="row g-3 mb-4">
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-header"><h6 class="mb-0"><i class="bi bi-phone me-1"></i>Dispositivos</h6></div>
                    <div class="card-body">
                        {% if clicks_by_device|length == 0 %}
                            <p class="text-muted small mb-0">Os próximos cliques serão classificados automaticamente.</p>
                        {% else %}
                            {% for row in clicks_by_device %}
                            <div class="d-flex justify-content-between border-bottom py-2">
                                <span>{{ row.label }}</span><strong>{{ row.total }}</strong>
                            </div>
                            {% endfor %}
                        {% endif %}
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-header"><h6 class="mb-0"><i class="bi bi-map me-1"></i>Estados</h6></div>
                    <div class="card-body">
                        {% if clicks_by_state|length == 0 %}
                            <p class="text-muted small mb-0">Localização aproximada disponível nos próximos cliques.</p>
                        {% else %}
                            {% for row in clicks_by_state %}
                            <div class="d-flex justify-content-between border-bottom py-2">
                                <span>{{ row.label }}</span><strong>{{ row.total }}</strong>
                            </div>
                            {% endfor %}
                        {% endif %}
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card h-100">
                    <div class="card-header"><h6 class="mb-0"><i class="bi bi-geo-alt me-1"></i>Cidades</h6></div>
                    <div class="card-body">
                        {% if clicks_by_city|length == 0 %}
                            <p class="text-muted small mb-0">Localização aproximada disponível nos próximos cliques.</p>
                        {% else %}
                            {% for row in clicks_by_city %}
                            <div class="d-flex justify-content-between border-bottom py-2">
                                <span>{{ row.city }}{% if row.state %} · {{ row.state }}{% endif %}</span><strong>{{ row.total }}</strong>
                            </div>
                            {% endfor %}
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <div class="alert alert-light border d-flex justify-content-between align-items-center mb-4">
            <span><i class="bi bi-people me-1"></i>Visitantes únicos estimados por IP</span>
            <strong class="fs-5">{{ unique_click_visitors }}</strong>
        </div>

        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Lotes</h5>
                <a href="{{ url('batches?product_id=' ~ product.id) }}" class="btn btn-sm btn-outline-primary">
                    Ver todos
                </a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Código</th>
                                <th>Quantidade</th>
                                <th>Liberado</th>
                                <th class="text-end">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for batch in batches %}
                            <tr>
                                <td>{{ batch.codigo_lote }}</td>
                                <td>{{ batch.quantidade }}</td>
                                <td>
                                    {% if batch.liberado %}
                                        <span class="badge bg-success">Sim</span>
                                    {% else %}
                                        <span class="badge bg-secondary">Não</span>
                                    {% endif %}
                                </td>
                                <td class="text-end">
                                    <a href="{{ url('batches/' ~ batch.id) }}" class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            {% else %}
                            <tr>
                                <td colspan="4" class="text-center py-4 text-muted">
                                    Nenhum lote criado para este produto
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function addPrimeiroMilhaoProdutoRowShow(nome = '', descricao = '') {
    const c = document.getElementById('primeiroMilhaoProductsContainerShow');
    if (!c) return;
    const row = document.createElement('div');
    row.className = 'border rounded-3 p-2 mb-2';
    row.innerHTML = `
        <div class="mb-2">
            <label class="form-label small mb-1">Produto</label>
            <input type="text" class="form-control" name="primeiro_milhao_produto_nome[]" value="${nome}" placeholder="Ex: CDB a 105% do CDI">
        </div>
        <div class="mb-2">
            <label class="form-label small mb-1">Descrição</label>
            <textarea class="form-control" name="primeiro_milhao_produto_descricao[]" rows="2" placeholder="Ex: retorno líquido acima de 1% ao mês com FGC">${descricao}</textarea>
        </div>
        <button type="button" class="btn btn-outline-danger btn-sm" onclick="this.parentElement.remove()">
            <i class="bi bi-trash"></i> Remover
        </button>
    `;
    c.appendChild(row);
}

// ── Copiar Link WhatsApp ──────────────────────────────────────
function copyWlinkUrl() {
    const url = '{{ app_url }}/wlink.php?id={{ product.id }}';
    navigator.clipboard.writeText(url).then(() => {
        const btn = event.target.closest('button');
        const originalHtml = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check"></i> Copiado!';
        btn.classList.remove('btn-outline-success');
        btn.classList.add('btn-success');
        setTimeout(() => {
            btn.innerHTML = originalHtml;
            btn.classList.remove('btn-success');
            btn.classList.add('btn-outline-success');
        }, 2000);
    });
}

// ── Clientes & Cliques ────────────────────────────────────────
let lcAllRows = [];

async function abrirLeadsCliques() {
    const modal = new bootstrap.Modal(document.getElementById('leadsClicksModal'));
    modal.show();

    if (lcAllRows.length > 0) return; // já carregado

    document.getElementById('lcLoading').style.display = '';
    document.getElementById('lcContent').style.display = 'none';

    try {
        const resp = await fetch('{{ url("products/" ~ product.id ~ "/leads-clicks") }}');
        const json = await resp.json();
        lcAllRows = json.data || [];
        renderLC(lcAllRows);
    } catch(e) {
        document.getElementById('lcLoading').innerHTML = '<p class="text-danger py-4 text-center">Erro ao carregar dados.</p>';
    }
}

function fmtDate(dt) {
    if (!dt) return '—';
    const d = new Date(dt);
    return d.toLocaleDateString('pt-BR') + ' ' + d.toLocaleTimeString('pt-BR', {hour:'2-digit',minute:'2-digit'});
}

function renderLC(rows) {
    const tbody = document.getElementById('lcBody');
    tbody.innerHTML = rows.length === 0
        ? '<tr><td colspan="7" class="text-center py-4 text-muted">Nenhum cliente encontrado.</td></tr>'
        : rows.map(r => `
            <tr>
                <td><a href="/leads/${r.id}" target="_blank">${r.nome || '—'}</a></td>
                <td>${r.telefone || '—'}</td>
                <td><span class="badge bg-light text-dark">${r.codigo_lote || '—'}</span></td>
                <td class="text-center">
                    <span class="badge ${r.click_count > 5 ? 'bg-primary' : r.click_count > 0 ? 'bg-info text-dark' : 'bg-secondary'}">${r.click_count}</span>
                </td>
                <td class="small text-muted">${fmtDate(r.first_click_at)}</td>
                <td class="small text-muted">${fmtDate(r.last_click_at)}</td>
                <td class="small text-muted">${fmtDate(r.created_at)}</td>
            </tr>`).join('');

    const total = rows.reduce((s, r) => s + parseInt(r.click_count || 0), 0);
    document.getElementById('lcSummary').textContent =
        `${rows.length} cliente(s) • ${total} clique(s) total`;

    document.getElementById('lcLoading').style.display = 'none';
    document.getElementById('lcContent').style.display = '';
}

document.getElementById('lcSearch')?.addEventListener('input', function() {
    const q = this.value.toLowerCase();
    const filtered = lcAllRows.filter(r =>
        (r.nome || '').toLowerCase().includes(q) ||
        (r.telefone || '').toLowerCase().includes(q) ||
        (r.codigo_lote || '').toLowerCase().includes(q)
    );
    renderLC(filtered);
});

// ── Cliques por Mês ────────────────────────────────────────────
(function() {
    const select = document.getElementById('monthFilter');
    if (!select) return;

    const bars = document.querySelectorAll('.chart-bar-wrap');
    const summaryTotal = document.getElementById('summaryTotal');
    const summaryLabel = document.getElementById('summaryLabel');
    const totalAll = {{ clicks_total }};

    // Corrige alturas relativas dentro do container
    const maxBar = Math.max(...[...bars].map(b => parseInt(b.dataset.total) || 0));
    bars.forEach(b => {
        const bar = b.querySelector('.chart-bar');
        const pct = maxBar > 0 ? Math.max((parseInt(b.dataset.total) / maxBar) * 100, 3) : 3;
        bar.style.height = pct + '%';
    });

    select.addEventListener('change', function() {
        const mes = this.value;
        bars.forEach(b => {
            b.querySelector('.chart-bar').style.opacity = (!mes || b.dataset.mes === mes) ? '1' : '0.2';
        });
        if (!mes) {
            summaryTotal.textContent = totalAll;
            summaryLabel.textContent = 'cliques totais nos últimos 12 meses (cada acesso +1)';
        } else {
            const chosen = [...bars].find(b => b.dataset.mes === mes);
            summaryTotal.textContent = chosen ? chosen.dataset.total : 0;
            summaryLabel.textContent = 'cliques em ' + (chosen ? chosen.dataset.label : mes);
        }
    });
})();
</script>
{% endblock %}
