{% extends '@MauticCore/Default/content.html.twig' %}

{% block headerTitle 'Deal Dashboard' %}

{% block actions %}
    {% if securityIsGranted('dealflow:deals:create') %}
        {% set actionReturnUrl = path('mautic_dealflow_reports', {'pipelineId': selectedPipeline.getId()}) %}
        <a
            class="btn btn-primary"
            href="{{ path('mautic_dealflow_new', {'pipelineId': selectedPipeline.getId(), 'returnUrl': actionReturnUrl}) }}"
            data-toggle="ajaxmodal"
            data-target="#MauticSharedModal"
            data-header="New Deal"
            data-href="{{ path('mautic_dealflow_new', {'pipelineId': selectedPipeline.getId(), 'modal': 1, 'contentOnly': 1, 'returnUrl': actionReturnUrl}) }}"
        >
            <i class="ri-add-line"></i>
            New Deal
        </a>
    {% endif %}
{% endblock %}

{% block content %}
    {{ include('@DealFlow/_styles.html.twig') }}
    {{ include('@DealFlow/Deal/_nav.html.twig') }}

    {% set totalClosedDeals = wonLostCounts.won + wonLostCounts.lost %}

    <style>
        .dealflow-report {
            color: var(--text-primary);
        }

        .dealflow-report__filter {
            align-items: center;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            justify-content: space-between;
            margin-bottom: 18px;
        }

        .dealflow-report__filter .form-group {
            margin-bottom: 0;
        }

        .dealflow-report__hero {
            background: linear-gradient(135deg, var(--layer-01) 0%, var(--layer-02) 100%);
            border: 1px solid var(--border-subtle-01);
            border-radius: 18px;
            margin-bottom: 22px;
            overflow: hidden;
            padding: 24px;
        }

        .dealflow-report__hero-grid {
            align-items: end;
            display: grid;
            gap: 20px;
            grid-template-columns: minmax(0, 1.2fr) minmax(260px, .8fr);
        }

        .dealflow-report__eyebrow {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 700;
            letter-spacing: .08em;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .dealflow-report__title {
            color: var(--text-primary);
            font-size: 30px;
            font-weight: 700;
            letter-spacing: -.02em;
            line-height: 1.1;
            margin: 0 0 10px;
        }

        .dealflow-report__intro {
            color: var(--text-secondary);
            font-size: 15px;
            line-height: 1.65;
            margin: 0;
            max-width: 720px;
        }

        .dealflow-report__hero-meta {
            display: grid;
            gap: 12px;
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }

        .dealflow-report__hero-card {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: 14px;
            padding: 16px 18px;
        }

        .dealflow-report__hero-label {
            color: var(--text-secondary);
            display: block;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .dealflow-report__hero-value {
            color: var(--text-primary);
            display: block;
            font-size: 22px;
            font-weight: 700;
            letter-spacing: -.02em;
            line-height: 1.1;
        }

        .dealflow-report__hero-note {
            color: var(--text-secondary);
            display: block;
            font-size: 12px;
            margin-top: 8px;
        }

        .dealflow-report__stats {
            display: grid;
            gap: 14px;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            margin-bottom: 22px;
        }

        .dealflow-report__stat {
            background: var(--layer-02);
            border: 1px solid var(--border-subtle-01);
            border-radius: 16px;
            min-height: 132px;
            padding: 18px;
        }

        .dealflow-report__stat-label {
            color: var(--text-secondary);
            display: block;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 12px;
            text-transform: uppercase;
        }

        .dealflow-report__stat-value {
            color: var(--text-primary);
            display: block;
            font-size: 26px;
            font-weight: 700;
            letter-spacing: -.03em;
            line-height: 1.05;
        }

        .dealflow-report__stat-note {
            color: var(--text-secondary);
            display: block;
            font-size: 12px;
            line-height: 1.5;
            margin-top: 12px;
        }

        .dealflow-report__grid {
            display: grid;
            gap: 18px;
            grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
            margin-bottom: 18px;
        }

        .dealflow-report__panel {
            background: var(--layer-02);
            border: 1px solid var(--border-subtle-01);
            border-radius: 18px;
            overflow: hidden;
        }

        .dealflow-report__panel-head {
            align-items: flex-start;
            border-bottom: 1px solid var(--border-subtle-01);
            display: flex;
            gap: 14px;
            justify-content: space-between;
            padding: 18px 20px;
        }

        .dealflow-report__panel-title {
            color: var(--text-primary);
            font-size: 16px;
            font-weight: 700;
            margin: 0 0 4px;
        }

        .dealflow-report__panel-copy {
            color: var(--text-secondary);
            font-size: 13px;
            line-height: 1.55;
            margin: 0;
        }

        .dealflow-report__panel-body {
            padding: 0;
        }

        .dealflow-report__table {
            margin: 0;
            width: 100%;
        }

        .dealflow-report__table th,
        .dealflow-report__table td {
            padding: 14px 20px;
            vertical-align: top;
        }

        .dealflow-report__table thead th {
            border-bottom: 1px solid var(--border-subtle-01);
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
        }

        .dealflow-report__table tbody tr + tr td {
            border-top: 1px solid var(--border-subtle-01);
        }

        .dealflow-report__chip {
            background: var(--layer-accent-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: 999px;
            color: var(--text-primary);
            display: inline-flex;
            font-size: 11px;
            font-weight: 700;
            line-height: 1;
            padding: 6px 9px;
            text-transform: uppercase;
        }

        .dealflow-report__chip--won {
            background: var(--label-background-green);
            border-color: var(--label-border-green);
            color: var(--label-color-green);
        }

        .dealflow-report__chip--lost {
            background: var(--label-background-red);
            border-color: var(--label-border-red);
            color: var(--label-color-red);
        }

        .dealflow-report__list {
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .dealflow-report__item {
            border-top: 1px solid var(--border-subtle-01);
            padding: 18px 20px;
        }

        .dealflow-report__item:first-child {
            border-top: 0;
        }

        .dealflow-report__item-title {
            color: var(--text-primary);
            display: inline-block;
            font-size: 15px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .dealflow-report__item-meta {
            color: var(--text-secondary);
            display: flex;
            flex-wrap: wrap;
            font-size: 12px;
            gap: 8px 12px;
            line-height: 1.5;
        }

        .dealflow-report__signal-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 12px;
        }

        .dealflow-report__signal {
            background: var(--label-background-red);
            border: 1px solid var(--label-border-red);
            border-radius: 999px;
            color: var(--label-color-red);
            display: inline-flex;
            font-size: 12px;
            font-weight: 600;
            padding: 6px 10px;
        }

        .dealflow-report__empty {
            color: var(--text-secondary);
            padding: 20px;
        }

        @media (max-width: 1199px) {
            .dealflow-report__stats {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }

            .dealflow-report__grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 767px) {
            .dealflow-report__hero-grid,
            .dealflow-report__hero-meta,
            .dealflow-report__stats {
                grid-template-columns: 1fr;
            }

            .dealflow-report__table th,
            .dealflow-report__table td,
            .dealflow-report__panel-head,
            .dealflow-report__item {
                padding-left: 16px;
                padding-right: 16px;
            }
        }
    </style>

    <div class="dealflow-report">
        <div class="dealflow-report__filter">
            <form class="form-inline" method="get">
                {% if pipelines|length > 1 %}
                    <div class="form-group">
                        <label class="mr-sm" for="dealflow_report_pipeline">Pipeline</label>
                        <select class="form-control" id="dealflow_report_pipeline" name="pipelineId" onchange="this.form.submit()">
                            {% for pipeline in pipelines %}
                                <option value="{{ pipeline.getId() }}" {% if selectedPipeline and pipeline.getId() == selectedPipeline.getId() %}selected{% endif %}>
                                    {{ pipeline.getName() }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                {% endif %}
                <div class="form-group">
                    <label class="mr-sm" for="dealflow_report_from">From</label>
                    <input class="form-control" type="date" id="dealflow_report_from" name="dateFrom" value="{{ dateFrom|default('') }}" onchange="this.form.submit()">
                </div>
                <div class="form-group">
                    <label class="mr-sm" for="dealflow_report_to">To</label>
                    <input class="form-control" type="date" id="dealflow_report_to" name="dateTo" value="{{ dateTo|default('') }}" onchange="this.form.submit()">
                </div>
            </form>
        </div>

        <section class="dealflow-report__hero">
            <div class="dealflow-report__hero-grid">
                <div>
                    <div class="dealflow-report__eyebrow">Revenue Workspace</div>
                    <h2 class="dealflow-report__title">{{ selectedPipeline.getName() }} pipeline health</h2>
                    <p class="dealflow-report__intro">Pipeline health overview for {{ selectedPipeline.getName() }}.</p>
                </div>
                <div class="dealflow-report__hero-meta">
                    <div class="dealflow-report__hero-card">
                        <span class="dealflow-report__hero-label">Open Pipeline</span>
                        <span class="dealflow-report__hero-value">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: pipelineValue, currency: reportCurrency|default('USD')}, false) }}</span>
                        <span class="dealflow-report__hero-note">{{ openDealCount }} open deal{{ openDealCount == 1 ? '' : 's' }}</span>
                    </div>
                    <div class="dealflow-report__hero-card">
                        <span class="dealflow-report__hero-label">Weighted Forecast</span>
                        <span class="dealflow-report__hero-value">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: weightedForecast, currency: reportCurrency|default('USD')}, false) }}</span>
                        <span class="dealflow-report__hero-note">Based on stage probability across open deals</span>
                    </div>
                </div>
            </div>
        </section>

        <section class="dealflow-report__stats">
            <article class="dealflow-report__stat">
                <span class="dealflow-report__stat-label">Open Deals</span>
                <span class="dealflow-report__stat-value">{{ openDealCount }}</span>
            </article>
            <article class="dealflow-report__stat">
                <span class="dealflow-report__stat-label">Win Rate</span>
                <span class="dealflow-report__stat-value">{{ winRate }}%</span>
                <span class="dealflow-report__stat-note">{{ wonLostCounts.won }} won, {{ wonLostCounts.lost }} lost{% if totalClosedDeals == 0 %}. No closed deals yet.{% endif %}</span>
            </article>
            <article class="dealflow-report__stat">
                <span class="dealflow-report__stat-label">Average Deal Size</span>
                <span class="dealflow-report__stat-value">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: averageDealSize, currency: reportCurrency|default('USD')}, false) }}</span>
            </article>
            <article class="dealflow-report__stat">
                <span class="dealflow-report__stat-label">At-Risk Deals</span>
                <span class="dealflow-report__stat-value">{{ atRiskCount }}</span>
                <span class="dealflow-report__stat-note">Overdue close dates, overdue tasks, or stale deal activity.</span>
            </article>
        </section>

        <section class="dealflow-report__grid" style="grid-template-columns: repeat(3, minmax(0, 1fr)); margin-bottom: 22px;">
            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Avg. Days to Close</h3>
                        <p class="dealflow-report__panel-copy">Mean time from deal creation to won.</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body" style="padding: 20px;">
                    <span class="dealflow-report__stat-value">
                        {{ velocityMetrics.avgDaysToClose is not null ? velocityMetrics.avgDaysToClose ~ ' days' : 'No data' }}
                    </span>
                </div>
            </article>
            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Avg. Cycle Time</h3>
                        <p class="dealflow-report__panel-copy">Mean time for all closed deals (won + lost).</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body" style="padding: 20px;">
                    <span class="dealflow-report__stat-value">
                        {{ velocityMetrics.avgCycleTime is not null ? velocityMetrics.avgCycleTime ~ ' days' : 'No data' }}
                    </span>
                </div>
            </article>
            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Monthly Close Rate</h3>
                        <p class="dealflow-report__panel-copy">Deals closed per month (last 6 months).</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body">
                    <table class="dealflow-report__table">
                        <thead>
                        <tr>
                            <th>Month</th>
                            <th>Won</th>
                            <th>Lost</th>
                            <th>Total</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for row in velocityMetrics.monthlyCloseRate %}
                            <tr>
                                <td>{{ row.month }}</td>
                                <td><span class="dealflow-report__chip dealflow-report__chip--won">{{ row.wonCount }}</span></td>
                                <td><span class="dealflow-report__chip dealflow-report__chip--lost">{{ row.lostCount }}</span></td>
                                <td>{{ row.totalClosed }}</td>
                            </tr>
                        {% else %}
                            <tr>
                                <td colspan="4" class="dealflow-report__empty">No closed deals yet.</td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </article>
        </section>

        {% if stageBreakdown is not empty %}
            <section class="dealflow-report__panel" style="margin-bottom: 22px;">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Stage Funnel</h3>
                        <p class="dealflow-report__panel-copy">Visual deal count by stage.</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body" style="padding: 20px;">
                    {% set maxCount = 1 %}
                    {% for row in stageBreakdown %}
                        {% if row.count > maxCount %}
                            {% set maxCount = row.count %}
                        {% endif %}
                    {% endfor %}
                    {% for row in stageBreakdown %}
                        <div style="margin-bottom: 10px;">
                            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:4px;">
                                <span style="font-size:13px;font-weight:600;color:var(--text-primary);">{{ row.name }}</span>
                                <span style="font-size:12px;color:var(--text-secondary);">{{ row.count }} deal{{ row.count == 1 ? '' : 's' }}</span>
                            </div>
                            <div style="background:var(--border-subtle-01);border-radius:6px;height:24px;overflow:hidden;">
                                <div style="background:var(--link-primary, #4a90d9);height:100%;border-radius:6px;width:{{ (row.count / maxCount * 100)|round }}%;transition:width .3s ease;"></div>
                            </div>
                        </div>
                    {% endfor %}
                </div>
            </section>
        {% endif %}

        <section class="dealflow-report__grid">
            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Stage Coverage</h3>
                        <p class="dealflow-report__panel-copy">Deal count and value by stage.</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body">
                    <table class="dealflow-report__table">
                        <thead>
                        <tr>
                            <th>Stage</th>
                            <th>Type</th>
                            <th>Probability</th>
                            <th>Deals</th>
                            <th>Total Amount</th>
                            <th>Weighted Amount</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for row in stageBreakdown %}
                            <tr>
                                <td><a href="{{ path('mautic_dealflow_index', {'page': 1, 'pipelineId': selectedPipeline.getId(), 'stageId': row.stageId}) }}">{{ row.name }}</a></td>
                                <td>
                                    <span class="dealflow-report__chip{% if row.stageType in ['won', 'lost'] %} dealflow-report__chip--{{ row.stageType }}{% endif %}">
                                        {{ row.stageType }}
                                    </span>
                                </td>
                                <td>{{ row.probability }}%</td>
                                <td>{{ row.count }}</td>
                                <td>{{ include('@DealFlow/Deal/_amount.html.twig', {amount: row.totalAmount, currency: reportCurrency|default('USD')}, false) }}</td>
                                <td>{{ include('@DealFlow/Deal/_amount.html.twig', {amount: row.weightedAmount, currency: reportCurrency|default('USD')}, false) }}</td>
                            </tr>
                        {% else %}
                            <tr>
                                <td colspan="6" class="dealflow-report__empty">No stage activity yet.</td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </article>

            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Owner Leaderboard</h3>
                        <p class="dealflow-report__panel-copy">Deal volume by owner.</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body">
                    <table class="dealflow-report__table">
                        <thead>
                        <tr>
                            <th>Owner</th>
                            <th>Deals</th>
                            <th>Total Amount</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for row in ownerLeaderboard %}
                            <tr>
                                <td>{{ row.ownerId is not null ? (owners[row.ownerId] ?? ('User #' ~ row.ownerId)) : 'Unassigned' }}</td>
                                <td>{{ row.dealsCount }}</td>
                                <td>{{ include('@DealFlow/Deal/_amount.html.twig', {amount: row.totalAmount, currency: reportCurrency|default('USD')}, false) }}</td>
                            </tr>
                        {% else %}
                            <tr>
                                <td colspan="3" class="dealflow-report__empty">No owner activity yet.</td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </article>
        </section>

        <section class="dealflow-report__grid">
            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">At-Risk Deals</h3>
                        <p class="dealflow-report__panel-copy">Deals with risk signals.</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body">
                    {% if atRiskDeals is empty %}
                        <div class="dealflow-report__empty">No at-risk deals right now.</div>
                    {% else %}
                        <ul class="dealflow-report__list">
                            {% for entry in atRiskDeals %}
                                {% set deal = entry.deal %}
                                {% set context = atRiskContexts[deal.getId()] ?? {'companyName': null, 'ownerName': null} %}
                                <li class="dealflow-report__item">
                                    <a class="dealflow-report__item-title" href="{{ path('mautic_dealflow_view', {'objectId': deal.getId()}) }}" data-toggle="ajax">{{ deal.getTitle() }}</a>
                                    <div class="dealflow-report__item-meta">
                                        <span>{{ context.companyName ?: 'Unassigned company' }}</span>
                                        <span>{{ context.ownerName ?: 'Unassigned owner' }}</span>
                                        <span>{{ deal.getStage() ? deal.getStage().getName() : 'No stage' }}</span>
                                        <span>{{ include('@DealFlow/Deal/_amount.html.twig', {amount: deal.getAmount(), currency: deal.getCurrency(), compact: true}, false) }}</span>
                                        <span>Updated {{ deal.getDateModified().format('Y-m-d') }}</span>
                                        <span>Close {{ deal.getExpectedCloseDate() ? deal.getExpectedCloseDate().format('Y-m-d') : 'not set' }}</span>
                                    </div>
                                    <div class="dealflow-report__signal-list">
                                        {% for signal in entry.riskSignals %}
                                            <span class="dealflow-report__signal">{{ signal }}</span>
                                        {% endfor %}
                                    </div>
                                </li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </div>
            </article>

            <article class="dealflow-report__panel">
                <div class="dealflow-report__panel-head">
                    <div>
                        <h3 class="dealflow-report__panel-title">Recent Activity</h3>
                        <p class="dealflow-report__panel-copy">Recent deal activity.</p>
                    </div>
                </div>
                <div class="dealflow-report__panel-body">
                    {% if recentActivity is empty %}
                        <div class="dealflow-report__empty">No recent activity recorded yet.</div>
                    {% else %}
                        <ul class="dealflow-report__list">
                            {% for event in recentActivity %}
                                {% set deal = event.getDeal() %}
                                {% set eventLabel = event.getEventType()|replace({'deal.': '', '_': ' ', '.': ' '})|title %}
                                <li class="dealflow-report__item">
                                    <div class="dealflow-report__item-title">{{ eventLabel }}</div>
                                    <div class="dealflow-report__item-meta">
                                        {% if deal %}
                                            <a href="{{ path('mautic_dealflow_view', {'objectId': deal.getId()}) }}" data-toggle="ajax">{{ deal.getTitle() }}</a>
                                            <span>{{ deal.getStage() ? deal.getStage().getName() : 'No stage' }}</span>
                                        {% endif %}
                                        <span>{{ event.getOrigin()|upper }}</span>
                                        <span>{{ event.getCreatedAt().format('Y-m-d H:i') }}</span>
                                    </div>
                                </li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </div>
            </article>
        </section>
    </div>
{% endblock %}
