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

{% block headerTitle deal.getTitle() %}

{% block preHeader %}
    <a class="btn btn-ghost btn-sm btn-nospin" href="{{ backUrl }}" data-toggle="ajax">
        <i class="ri-arrow-left-line"></i>
        Pipeline
    </a>
{% endblock %}

{% block actions %}
    <div class="btn-group">
        <a class="btn btn-default" href="{{ path('mautic_dealflow_index') }}" data-toggle="ajax">Deals</a>
        {% if securityIsGranted('dealflow:reports:viewown') or securityIsGranted('dealflow:reports:viewother') %}
            <a class="btn btn-default" href="{{ path('mautic_dealflow_reports') }}" data-toggle="ajax">Dashboard</a>
        {% endif %}
        {% if canEditDeal %}
            <a class="btn btn-primary" href="{{ path('mautic_dealflow_edit', {'objectId': deal.getId()}) }}" data-toggle="ajax">
                <i class="ri-pencil-line"></i>
                Edit Deal
            </a>
        {% endif %}
    </div>
{% endblock %}

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

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

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

        .dealflow-detail__sidebar,
        .dealflow-detail__main {
            padding: 0;
        }

        .dealflow-detail__sidebar-shell {
            background: var(--layer-01);
            height: 100%;
            padding: 24px;
        }

        .dealflow-detail__main {
            background: var(--layer-02);
            border-left: 1px solid var(--border-subtle-01);
        }

        .dealflow-detail__main-shell {
            padding: 24px;
        }

        .dealflow-card--mobile-overview {
            display: none;
        }

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

        .dealflow-hero__top {
            align-items: flex-start;
            display: flex;
            gap: 16px;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .dealflow-pills {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }

        .dealflow-hero__grid {
            display: grid;
            gap: 20px;
            grid-template-columns: minmax(0, 1.3fr) minmax(280px, 1fr);
        }

        .dealflow-amount {
            color: var(--text-primary);
            font-size: 40px;
            font-weight: 700;
            line-height: 1.05;
            margin-bottom: 14px;
        }

        .dealflow-description {
            color: var(--text-secondary);
            font-size: 15px;
            line-height: 1.6;
            margin: 0;
            white-space: pre-line;
        }

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

        .dealflow-metric {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: 12px;
            min-height: 92px;
            padding: 14px 16px;
        }

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

        .dealflow-metric__value {
            color: var(--text-primary);
            font-size: 16px;
            font-weight: 600;
            line-height: 1.35;
        }

        .dealflow-detail__sidebar .dealflow-meta {
            grid-template-columns: minmax(0, 1fr);
        }

        .dealflow-detail__sidebar .dealflow-meta__item,
        .dealflow-detail__sidebar .dealflow-meta__item:nth-last-child(-n+2) {
            border-bottom: 1px solid var(--border-subtle-01);
            padding-bottom: 12px;
        }

        .dealflow-detail__sidebar .dealflow-meta__item:last-child {
            border-bottom: 0;
            padding-bottom: 0;
        }

        .dealflow-sidebar-section + .dealflow-sidebar-section {
            border-top: 1px solid var(--border-subtle-01);
            margin-top: 24px;
            padding-top: 24px;
        }

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

        .dealflow-sidebar-section__title {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 700;
            letter-spacing: .08em;
            margin: 0 0 16px;
            text-transform: uppercase;
        }

        .dealflow-sidebar-section__header .dealflow-sidebar-section__title {
            margin-bottom: 0;
        }

        .dealflow-detail__sidebar .dealflow-list {
            gap: 0;
        }

        .dealflow-detail__sidebar .dealflow-list__item {
            background: transparent;
            border: 0;
            border-bottom: 1px solid var(--border-subtle-01);
            border-radius: 0;
            flex-wrap: wrap;
            padding: 12px 0;
        }

        .dealflow-detail__sidebar .dealflow-list__item:first-child {
            padding-top: 0;
        }

        .dealflow-detail__sidebar .dealflow-list__item:last-child {
            border-bottom: 0;
            padding-bottom: 0;
        }

        .dealflow-detail__sidebar .dealflow-list__actions {
            justify-content: flex-start;
            width: 100%;
        }

        .dealflow-contact-label {
            background: var(--label-background-gray);
            border-radius: 999px;
            color: var(--label-color-gray);
            display: inline-flex;
            font-size: 11px;
            font-weight: 600;
            margin-left: 8px;
            padding: 4px 8px;
        }

        .dealflow-file-link {
            color: var(--link-primary);
            font-weight: 600;
        }

        .dealflow-stakeholder-table-wrap {
            overflow-x: auto;
        }

        .dealflow-stakeholder-table {
            border-collapse: collapse;
            width: 100%;
        }

        .dealflow-stakeholder-table th {
            background: var(--layer-01);
            border-bottom: 2px solid var(--border-subtle-01);
            color: var(--text-secondary);
            font-size: 11px;
            font-weight: 700;
            letter-spacing: .06em;
            padding: 10px 14px;
            text-align: left;
            text-transform: uppercase;
        }

        .dealflow-stakeholder-table td {
            border-bottom: 1px solid var(--border-subtle-01);
            font-size: 14px;
            padding: 12px 14px;
            vertical-align: middle;
        }

        .dealflow-stakeholder-table tbody tr:last-child td {
            border-bottom: 0;
        }

        .dealflow-stakeholder-table tbody tr:hover {
            background: var(--layer-01);
        }

        .dealflow-stakeholder-link {
            color: var(--link-primary);
            font-weight: 600;
            text-decoration: none;
        }

        .dealflow-stakeholder-link:hover {
            text-decoration: underline;
        }

        .dealflow-stakeholder-email {
            color: var(--text-secondary);
        }

        .dealflow-stakeholder-role {
            background: var(--label-background-gray);
            border-radius: 999px;
            color: var(--label-color-gray);
            display: inline-block;
            font-size: 12px;
            font-weight: 600;
            padding: 3px 10px;
        }

        .dealflow-stakeholder-date {
            color: var(--text-secondary);
            font-size: 13px;
        }

        .dealflow-inline-form {
            display: inline-block;
            margin: 0;
        }

        .dealflow-associate-form {
            border-bottom: 1px solid var(--border-subtle-01);
            margin-bottom: 18px;
            padding-bottom: 18px;
        }

        .dealflow-inline-edit {
            background: var(--field-01);
            border: 1px solid var(--border-subtle-02);
            border-radius: 6px;
            color: var(--text-primary);
            font-size: 13px;
            padding: 4px 8px;
            width: 100%;
        }

        @media (max-width: 991px) {
            .dealflow-hero {
                margin: 0 0 20px;
            }

            .dealflow-detail__main {
                border-left: 0;
                border-top: 0;
                order: 1;
            }

            .dealflow-detail__sidebar {
                border-top: 1px solid var(--border-subtle-01);
                order: 2;
            }

            .dealflow-detail__sidebar-shell,
            .dealflow-detail__main-shell {
                padding: 20px;
            }

            .dealflow-card--mobile-overview {
                display: block;
            }

            .dealflow-sidebar-section--overview {
                display: none;
            }

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

            .dealflow-metrics,
            .dealflow-meta {
                grid-template-columns: 1fr;
            }

            .dealflow-meta__item,
            .dealflow-meta__item:nth-last-child(-n+2) {
                border-bottom: 1px solid var(--border-subtle-01);
                padding-bottom: 12px;
            }

            .dealflow-meta__item:last-child {
                border-bottom: 0;
                padding-bottom: 0;
            }
        }
    </style>

    <div class="dealflow-detail">
        <div class="dealflow-hero">
            <div class="dealflow-hero__top">
                <div class="dealflow-pills">
                    <span class="dealflow-pill dealflow-pill--{{ deal.getStatus() }}">{{ deal.getStatus() }}</span>
                    <span class="dealflow-chip">{{ deal.getStage() ? deal.getStage().getName() : 'No stage' }}</span>
                    <span class="dealflow-chip">Deal #{{ deal.getId() }}</span>
                </div>
            </div>

            <div class="dealflow-hero__grid">
                <div>
                    <div class="dealflow-kicker">Deal Value</div>
                    <div class="dealflow-amount">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: deal.getAmount(), currency: deal.getCurrency()}, false) }}</div>
                    {% if deal.getDescription() %}
                        <p class="dealflow-description">{{ deal.getDescription() }}</p>
                    {% endif %}
                </div>

                <div class="dealflow-metrics">
                    <div class="dealflow-metric">
                        <div class="dealflow-metric__label">Company</div>
                        <div class="dealflow-metric__value">{{ dealContext.companyName ?: 'Unassigned' }}</div>
                    </div>
                    <div class="dealflow-metric">
                        <div class="dealflow-metric__label">Owner</div>
                        <div class="dealflow-metric__value">{{ dealContext.ownerName ?: 'Unassigned' }}</div>
                    </div>
                    <div class="dealflow-metric">
                        <div class="dealflow-metric__label">Expected Close</div>
                        <div class="dealflow-metric__value">{{ deal.getExpectedCloseDate() ? deal.getExpectedCloseDate().format('Y-m-d') : 'Not set' }}</div>
                    </div>
                    <div class="dealflow-metric">
                        <div class="dealflow-metric__label">Contacts</div>
                        <div class="dealflow-metric__value">{{ dealContext.contacts|length }} associated</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="box-layout dealflow-detail__layout">
            <aside class="col-md-3 height-auto dealflow-detail__sidebar">
                <div class="dealflow-detail__sidebar-shell">
                    <section class="dealflow-sidebar-section dealflow-sidebar-section--overview">
                        <h3 class="dealflow-sidebar-section__title">Overview</h3>
                        <div class="dealflow-meta">
                            <div class="dealflow-meta__item">
                                <span class="dealflow-meta__label">Status</span>
                                {% if canEditDeal %}
                                    <div class="dealflow-meta__value">
                                        <select class="dealflow-inline-edit" data-dealflow-inline-status data-deal-id="{{ deal.getId() }}" data-csrf="{{ csrf_token('dealflow_inline_status_' ~ deal.getId()) }}">
                                            {% for s in ['open', 'won', 'lost'] %}
                                                <option value="{{ s }}" {{ deal.getStatus() == s ? 'selected' : '' }}>{{ s|upper }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                {% else %}
                                    <div class="dealflow-meta__value">{{ deal.getStatus()|upper }}</div>
                                {% endif %}
                            </div>
                            <div class="dealflow-meta__item">
                                <span class="dealflow-meta__label">Stage</span>
                                {% if canEditDeal and stages|default([])|length > 0 %}
                                    <div class="dealflow-meta__value">
                                        <select class="dealflow-inline-edit" data-dealflow-inline-stage data-deal-id="{{ deal.getId() }}" data-csrf="{{ csrf_token('dealflow_move_stage_' ~ deal.getId()) }}">
                                            {% for stage in stages %}
                                                <option value="{{ stage.getId() }}" {{ deal.getStage() and deal.getStage().getId() == stage.getId() ? 'selected' : '' }}>{{ stage.getName() }}</option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                {% else %}
                                    <div class="dealflow-meta__value">{{ deal.getStage() ? deal.getStage().getName() : 'Unassigned' }}</div>
                                {% endif %}
                            </div>
                            <div class="dealflow-meta__item">
                                <span class="dealflow-meta__label">Source</span>
                                <div class="dealflow-meta__value">{{ deal.getSource() ?: 'Not set' }}</div>
                            </div>
                            <div class="dealflow-meta__item">
                                <span class="dealflow-meta__label">External Ref</span>
                                <div class="dealflow-meta__value">{{ deal.getExternalRef() ?: 'Not set' }}</div>
                            </div>
                            <div class="dealflow-meta__item">
                                <span class="dealflow-meta__label">Currency</span>
                                <div class="dealflow-meta__value">{{ deal.getCurrency() ?: 'Not set' }}</div>
                            </div>
                            <div class="dealflow-meta__item">
                                <span class="dealflow-meta__label">Confidence</span>
                                <div class="dealflow-meta__value">{{ deal.getConfidence() is not null ? deal.getConfidence() ~ '%' : 'Not set' }}</div>
                            </div>
                            {% for row in customFieldDisplayRows %}
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">{{ row.label }}</span>
                                    <div class="dealflow-meta__value">{{ row.displayValue }}</div>
                                </div>
                            {% endfor %}
                        </div>
                    </section>

                    <section class="dealflow-sidebar-section">
                        <div class="dealflow-sidebar-section__header">
                            <h3 class="dealflow-sidebar-section__title">Contacts</h3>
                            {% if canEditDeal %}
                                <button
                                    class="btn btn-xs btn-default"
                                    type="button"
                                    data-toggle="collapse"
                                    data-target="#dealflowAssociateContact"
                                    aria-expanded="false"
                                    aria-controls="dealflowAssociateContact"
                                >
                                    Associate Contact
                                </button>
                            {% endif %}
                        </div>
                        {% if canEditDeal %}
                            <div class="collapse dealflow-associate-form" id="dealflowAssociateContact">
                                <form class="dealflow-form" method="post" action="{{ path('mautic_dealflow_contact_attach', {'objectId': deal.getId()}) }}">
                                    <input type="hidden" name="_token" value="{{ csrf_token('dealflow_attach_contact_' ~ deal.getId()) }}">
                                    <div class="form-group">
                                        <label class="control-label" for="dealflow_associate_contact_display">Contact</label>
                                        <input
                                            class="form-control"
                                            id="dealflow_associate_contact_display"
                                            type="text"
                                            autocomplete="off"
                                            placeholder="Start typing a contact name"
                                            data-toggle="field-lookup"
                                            data-callback="activateDealFlowContactLookupField"
                                            data-lookup-callback="updateDealFlowContactLookupListFilter"
                                            data-chosen-lookup="lead:contactList"
                                            data-target="undefined"
                                            data-no-record-message="No matching contacts found"
                                        >
                                        <input id="dealflow_associate_contact_id" type="hidden" name="contact_id">
                                    </div>
                                    <div class="form-group">
                                        <label class="control-label" for="dealflow_associate_contact_label">Association label</label>
                                        <input
                                            class="form-control"
                                            id="dealflow_associate_contact_label"
                                            type="text"
                                            name="label"
                                            placeholder="Role label (optional)"
                                        >
                                    </div>
                                    <button class="btn btn-default" type="submit">Associate Contact</button>
                                </form>
                            </div>
                        {% endif %}

                        {% if dealContext.contacts is empty %}
                            <p class="dealflow-empty mb-0">No contacts associated yet.</p>
                        {% else %}
                            <div class="dealflow-list">
                                {% for contact in dealContext.contacts %}
                                    <div class="dealflow-list__item">
                                        <div class="dealflow-list__body">
                                            <p class="dealflow-list__title">
                                                {{ contact.name }}
                                                {% if contact.label %}<span class="dealflow-contact-label">{{ contact.label }}</span>{% endif %}
                                            </p>
                                            <p class="dealflow-list__meta">{{ contact.email ?: 'No email on file' }}</p>
                                        </div>
                                    </div>
                                {% endfor %}
                            </div>
                        {% endif %}
                    </section>

                    <section class="dealflow-sidebar-section">
                        <h3 class="dealflow-sidebar-section__title">Files</h3>
                        {% if canEditDeal %}
                            <form class="dealflow-form mb-lg" method="post" action="{{ path('mautic_dealflow_attachment_add', {'objectId': deal.getId()}) }}" enctype="multipart/form-data">
                                <input type="hidden" name="_token" value="{{ csrf_token('dealflow_add_attachment_' ~ deal.getId()) }}">
                                <div class="form-group">
                                    <input class="form-control" type="file" name="attachment">
                                </div>
                                <button class="btn btn-default" type="submit">Upload Attachment</button>
                            </form>
                        {% endif %}

                        {% if deal.getAttachments() is empty %}
                            <p class="dealflow-empty mb-0">No attachments yet.</p>
                        {% else %}
                            <div class="dealflow-list">
                                {% for attachment in deal.getAttachments() %}
                                    <div class="dealflow-list__item">
                                        <div class="dealflow-list__body">
                                            <p class="dealflow-list__title">
                                                <a class="dealflow-file-link" href="{{ path('mautic_dealflow_attachment_download', {'attachmentId': attachment.getId()}) }}">{{ attachment.getOriginalFilename() }}</a>
                                            </p>
                                            <p class="dealflow-list__meta">{{ attachment.getSizeBytes() }} bytes</p>
                                        </div>
                                        <div class="dealflow-list__actions">
                                            {% if canEditDeal %}
                                                <button class="btn btn-xs btn-danger" type="button" data-toggle="modal" data-target="#dealflowAttachmentDelete{{ attachment.getId() }}">Delete</button>
                                            {% endif %}
                                        </div>
                                    </div>

                                    {% if canEditDeal %}
                                        <div class="modal fade" id="dealflowAttachmentDelete{{ attachment.getId() }}" tabindex="-1" role="dialog" aria-labelledby="dealflowAttachmentDeleteLabel{{ attachment.getId() }}">
                                            <div class="modal-dialog" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                                        <h4 class="modal-title" id="dealflowAttachmentDeleteLabel{{ attachment.getId() }}">Delete attachment</h4>
                                                    </div>
                                                    <div class="modal-body">
                                                        <p>Delete <strong>{{ attachment.getOriginalFilename() }}</strong> from this deal?</p>
                                                        <p class="text-muted">This removes the file from Deal Flow and deletes the stored upload.</p>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                                        <form class="dealflow-inline-form" method="post" action="{{ path('mautic_dealflow_attachment_delete', {'objectId': deal.getId(), 'attachmentId': attachment.getId()}) }}">
                                                            <input type="hidden" name="_token" value="{{ csrf_token('dealflow_delete_attachment_' ~ attachment.getId()) }}">
                                                            <button class="btn btn-danger" type="submit">Delete attachment</button>
                                                        </form>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    {% endif %}
                                {% endfor %}
                            </div>
                        {% endif %}
                    </section>
                </div>
            </aside>

            <section class="col-md-9 height-auto dealflow-detail__main">
                <div class="dealflow-detail__main-shell">
                    <div class="dealflow-card">
                        <div class="dealflow-card__header">
                            <h3 class="dealflow-card__title">Activity</h3>
                        </div>
                        <div class="dealflow-card__body">
                            {% if timeline is empty %}
                                <p class="dealflow-empty mb-0">No activity yet.</p>
                            {% else %}
                                <div class="dealflow-timeline">
                                    {% for item in timeline %}
                                        {% set timelineLabel = item.label %}
                                        {% if item.type == 'audit' %}
                                            {% set timelineLabel = item.label|replace({'deal.': '', 'dealflow.': '', '_': ' ', '.': ' '})|title %}
                                        {% endif %}
                                        <div class="dealflow-timeline__item">
                                            <div class="dealflow-timeline__title">{{ timelineLabel }}</div>
                                            <div class="dealflow-timeline__stamp">{{ item.timestamp.format('Y-m-d H:i') }}</div>
                                            {% if item.body %}
                                                <div class="dealflow-timeline__body">{{ item.body }}</div>
                                            {% endif %}
                                        </div>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="dealflow-card">
                        <div class="dealflow-card__header">
                            <h3 class="dealflow-card__title">Notes</h3>
                        </div>
                        <div class="dealflow-card__body">
                            {% if canEditDeal %}
                                <form class="dealflow-form" method="post" action="{{ path('mautic_dealflow_note_add', {'objectId': deal.getId()}) }}">
                                    <input type="hidden" name="_token" value="{{ csrf_token('dealflow_add_note_' ~ deal.getId()) }}">
                                    <div class="form-group">
                                        <textarea class="form-control" name="body" rows="4" placeholder="Add a note to the deal timeline"></textarea>
                                    </div>
                                    <button class="btn btn-primary" type="submit">Save Note</button>
                                </form>
                            {% endif %}
                        </div>
                    </div>

                    <div class="dealflow-card">
                        <div class="dealflow-card__header">
                            <h3 class="dealflow-card__title">Tasks</h3>
                        </div>
                        <div class="dealflow-card__body">
                            {% if canEditDeal %}
                                <button class="btn btn-xs btn-default mb-md" type="button" data-toggle="collapse" data-target="#dealflowTaskForm" aria-expanded="false">
                                    <i class="ri-add-line"></i> Add Task
                                </button>
                                <div class="collapse" id="dealflowTaskForm">
                                    <form class="dealflow-form mb-lg" method="post" action="{{ path('mautic_dealflow_task_add', {'objectId': deal.getId()}) }}">
                                        <input type="hidden" name="_token" value="{{ csrf_token('dealflow_add_task_' ~ deal.getId()) }}">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="form-group">
                                                    <input class="form-control" type="text" name="title" placeholder="Task title">
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <div class="form-group">
                                                    <select class="form-control" name="priority">
                                                        <option value="normal">Normal priority</option>
                                                        <option value="urgent">Urgent</option>
                                                        <option value="high">High</option>
                                                        <option value="low">Low</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <input class="form-control" type="date" name="due_at">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <select class="form-control" name="owner_id">
                                                        <option value="">No owner assigned</option>
                                                        {% for label, ownerId in taskOwnerChoices %}
                                                            <option value="{{ ownerId }}">{{ label }}</option>
                                                        {% endfor %}
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <input class="form-control" type="datetime-local" name="reminder_at" placeholder="Reminder time">
                                        </div>
                                        <div class="form-group">
                                            <textarea class="form-control" name="description" rows="2" placeholder="Task details"></textarea>
                                        </div>
                                        <div class="d-flex ai-center jc-flex-end fw-wrap gap-sm">
                                            <button class="btn btn-default" type="submit">Create Task</button>
                                        </div>
                                    </form>
                                </div>
                            {% endif %}

                            {% if deal.getTasks() is empty %}
                                <p class="dealflow-empty mb-0">No tasks yet.</p>
                            {% else %}
                                <div class="dealflow-list">
                                    {% for task in deal.getTasks() %}
                                        <div class="dealflow-list__item">
                                            <div class="dealflow-list__body">
                                                <p class="dealflow-list__title">
                                                    {{ task.getTitle() }}
                                                    <span class="dealflow-pill dealflow-pill--{{ task.getPriority() in ['urgent', 'high'] ? 'lost' : 'open' }}">{{ task.getPriority() }}</span>
                                                    <span class="dealflow-pill dealflow-pill--{{ task.getStatus() == 'completed' ? 'won' : 'open' }}">{{ task.getStatus() }}</span>
                                                </p>
                                                <p class="dealflow-list__meta">
                                                    {% if task.getDueAt() %}Due {{ task.getDueAt().format('Y-m-d') }}{% else %}No due date{% endif %}
                                                    {% if task.getReminderAt() %} · Reminder {{ task.getReminderAt().format('Y-m-d H:i') }}{% endif %}
                                                    {% if task.getOwnerId() %} · Owner {{ taskOwnerLabels[task.getOwnerId()] ?? ('User #' ~ task.getOwnerId()) }}{% endif %}
                                                </p>
                                                {% if task.getDescription() %}
                                                    <div class="dealflow-list__hint">{{ task.getDescription()|e('html') }}</div>
                                                {% endif %}
                                            </div>
                                            {% if task.getStatus() != 'completed' %}
                                                <div class="dealflow-list__actions">
                                                    {% if canEditDeal %}
                                                        <form class="dealflow-inline-form" method="post" action="{{ path('mautic_dealflow_task_complete', {'objectId': deal.getId(), 'taskId': task.getId()}) }}">
                                                            <input type="hidden" name="_token" value="{{ csrf_token('dealflow_complete_task_' ~ task.getId()) }}">
                                                            <button class="btn btn-xs btn-default" type="submit">Complete</button>
                                                        </form>
                                                    {% endif %}
                                                </div>
                                            {% endif %}
                                        </div>
                                    {% endfor %}
                                </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="dealflow-card">
                        <div class="dealflow-card__header">
                            <h3 class="dealflow-card__title">{{ 'dealflow.stakeholder.header'|trans }}</h3>
                        </div>
                        <div class="dealflow-card__body">
                            {% if dealContext.contacts is empty %}
                                <p class="dealflow-empty mb-0">{{ 'dealflow.stakeholder.empty'|trans }}</p>
                            {% else %}
                                <div class="dealflow-stakeholder-table-wrap">
                                    <table class="dealflow-stakeholder-table">
                                        <thead>
                                            <tr>
                                                <th>{{ 'dealflow.stakeholder.col.name'|trans }}</th>
                                                <th>{{ 'dealflow.stakeholder.col.email'|trans }}</th>
                                                <th>{{ 'dealflow.stakeholder.col.role'|trans }}</th>
                                                <th>{{ 'dealflow.stakeholder.col.added'|trans }}</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            {% for contact in dealContext.contacts %}
                                                <tr>
                                                    <td>
                                                        <a href="{{ path('mautic_contact_action', {'objectAction': 'view', 'objectId': contact.id}) }}" data-toggle="ajax" class="dealflow-stakeholder-link">
                                                            {{ contact.name }}
                                                        </a>
                                                    </td>
                                                    <td class="dealflow-stakeholder-email">{{ contact.email ?: '—' }}</td>
                                                    <td>
                                                        {% if contact.label %}
                                                            <span class="dealflow-stakeholder-role">{{ contact.label }}</span>
                                                        {% else %}
                                                            <span class="text-muted">—</span>
                                                        {% endif %}
                                                    </td>
                                                    <td class="dealflow-stakeholder-date">{{ contact.createdAt|date('Y-m-d') }}</td>
                                                </tr>
                                            {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="dealflow-card dealflow-card--mobile-overview">
                        <div class="dealflow-card__header">
                            <h3 class="dealflow-card__title">Overview</h3>
                        </div>
                        <div class="dealflow-card__body">
                            <div class="dealflow-meta">
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">Status</span>
                                    {% if canEditDeal %}
                                        <div class="dealflow-meta__value">
                                            <select class="dealflow-inline-edit" data-dealflow-inline-status data-deal-id="{{ deal.getId() }}" data-csrf="{{ csrf_token('dealflow_inline_status_' ~ deal.getId()) }}">
                                                {% for s in ['open', 'won', 'lost'] %}
                                                    <option value="{{ s }}" {{ deal.getStatus() == s ? 'selected' : '' }}>{{ s|upper }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    {% else %}
                                        <div class="dealflow-meta__value">{{ deal.getStatus()|upper }}</div>
                                    {% endif %}
                                </div>
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">Stage</span>
                                    {% if canEditDeal and stages|default([])|length > 0 %}
                                        <div class="dealflow-meta__value">
                                            <select class="dealflow-inline-edit" data-dealflow-inline-stage data-deal-id="{{ deal.getId() }}" data-csrf="{{ csrf_token('dealflow_move_stage_' ~ deal.getId()) }}">
                                                {% for stage in stages %}
                                                    <option value="{{ stage.getId() }}" {{ deal.getStage() and deal.getStage().getId() == stage.getId() ? 'selected' : '' }}>{{ stage.getName() }}</option>
                                                {% endfor %}
                                            </select>
                                        </div>
                                    {% else %}
                                        <div class="dealflow-meta__value">{{ deal.getStage() ? deal.getStage().getName() : 'Unassigned' }}</div>
                                    {% endif %}
                                </div>
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">Source</span>
                                    <div class="dealflow-meta__value">{{ deal.getSource() ?: 'Not set' }}</div>
                                </div>
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">External Ref</span>
                                    <div class="dealflow-meta__value">{{ deal.getExternalRef() ?: 'Not set' }}</div>
                                </div>
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">Currency</span>
                                    <div class="dealflow-meta__value">{{ deal.getCurrency() ?: 'Not set' }}</div>
                                </div>
                                <div class="dealflow-meta__item">
                                    <span class="dealflow-meta__label">Confidence</span>
                                    <div class="dealflow-meta__value">{{ deal.getConfidence() is not null ? deal.getConfidence() ~ '%' : 'Not set' }}</div>
                                </div>
                                {% for row in customFieldDisplayRows %}
                                    <div class="dealflow-meta__item">
                                        <span class="dealflow-meta__label">{{ row.label }}</span>
                                        <div class="dealflow-meta__value">{{ row.displayValue }}</div>
                                    </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>

    <script>
        (function () {
            Mautic.updateDealFlowContactLookupListFilter = function (field, item) {
                if (item && item.id) {
                    mQuery('#dealflow_associate_contact_id').val(item.id);
                    mQuery('#' + field).val(item.value || item.name || '');
                }
            };

            Mautic.activateDealFlowContactLookupField = function () {
                var lookupElementId = 'dealflow_associate_contact_display';
                var fieldEl = mQuery('#' + lookupElementId);

                if (!fieldEl.length) {
                    return;
                }

                var action = fieldEl.attr('data-chosen-lookup');
                var options = {
                    limit: 20,
                    searchKey: 'lead.lead'
                };

                Mautic.activateFieldTypeahead(lookupElementId, 'undefined', options, action);

                fieldEl.off('change.dealflow').on('change.dealflow', function (event) {
                    if (event.target.value === '') {
                        mQuery('#dealflow_associate_contact_id').val('');
                    }
                });
            };

            Mautic.activateDealFlowContactLookupField();
        })();
    </script>

    {{ include('@DealFlow/_scripts.html.twig') }}
    <script>
        (function () {
            document.querySelectorAll('[data-dealflow-inline-stage]').forEach(function (select) {
                select.addEventListener('change', function () {
                    var dealId = select.getAttribute('data-deal-id');
                    var csrf = select.getAttribute('data-csrf');
                    var stageId = select.value;
                    var formData = new FormData();
                    formData.append('stage_id', stageId);
                    formData.append('_token', csrf);
                    formData.append('return_url', window.location.pathname);

                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '{{ path("mautic_dealflow_move_stage", {"objectId": "__ID__"}) }}'.replace('__ID__', dealId));
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    xhr.onload = function () {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            window.DealFlow.showToast('Stage updated.');
                        } else {
                            window.DealFlow.showToast('Failed to update stage.');
                        }
                    };
                    xhr.onerror = function () {
                        window.DealFlow.showToast('Network error updating stage.');
                    };
                    xhr.send(formData);
                });
            });

            document.querySelectorAll('[data-dealflow-inline-status]').forEach(function (select) {
                select.addEventListener('change', function () {
                    var dealId = select.getAttribute('data-deal-id');
                    var csrf = select.getAttribute('data-csrf');
                    var status = select.value;
                    var formData = new FormData();
                    formData.append('deal[status]', status);
                    formData.append('deal[_token]', csrf);

                    var xhr = new XMLHttpRequest();
                    xhr.open('PATCH', '{{ path("mautic_api_dealflow_deal", {"id": "__ID__"}) }}'.replace('__ID__', dealId));
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    xhr.onload = function () {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            window.DealFlow.showToast('Status updated.');
                        } else {
                            window.DealFlow.showToast('Failed to update status.');
                        }
                    };
                    xhr.onerror = function () {
                        window.DealFlow.showToast('Network error updating status.');
                    };
                    xhr.send(formData);
                });
            });
        })();
    </script>
{% endblock %}
