@php
    $leadStatusProgress = match ((int) $lead->stage_id) {
        1 => 0,
        2 => 20,
        3 => 40,
        4 => 60,
        5 => 80,
        6, 7 => 100,
        default => 0,
    };
    $completedActivities = $activities->filter(
        fn ($activity) => in_array(strtolower((string) ($activity->lifecycle_status ?: $activity->status)), ['completed', 'done'], true)
    )->count();
    $activityProgress = $activities->isNotEmpty()
        ? (int) round(($completedActivities / $activities->count()) * 100)
        : 0;
    $summaryProgress = (int) round(($leadStatusProgress + $activityProgress) / 2);
    $isTerminalLead = in_array((int) $lead->stage_id, [6, 7], true);
    $primaryPhone = $lead->contactPhones->first()?->phone;
    $primaryEmail = $lead->contactEmails->first()?->email;
    $languageNames = $lead->contactLanguages->pluck('language.name')->filter()->join(', ');
    $communicationMethods = collect($lead->contact_method ?: [])->filter()->map(fn ($method) => ucwords((string) $method))->join(', ');
    $interestProductNames = $lead->interestProducts->pluck('product_name')->filter()->join(', ');
    $canUpdateLeadProfileData = ! $leadIsCompleted
        && ((bool) auth()->user()->is_admin || auth()->user()->can('update_leads'));
    $leadEditFieldUrl = fn (string $field) => route('leads.edit', ['id' => $lead->id, 'focus' => $field]);
    $profileFieldOptions = [
        'first_name' => ['label' => 'Full Name', 'type' => 'name', 'value' => $lead->first_name, 'secondary' => $lead->last_name],
        'emails' => ['label' => 'Email', 'type' => 'email', 'value' => $primaryEmail],
        'phones' => ['label' => 'Phone', 'type' => 'tel', 'value' => $primaryPhone],
        'job_title' => ['label' => 'Job Title', 'type' => 'text', 'value' => $lead->job_title],
        'company_id' => ['label' => 'Company', 'type' => 'select', 'value' => $lead->company_id, 'options' => $profileCompanyOptions->map(fn ($company) => ['value' => $company->id, 'label' => $company->name])->values()],
        'languages' => ['label' => 'Languages', 'type' => 'multiselect', 'value' => $lead->contactLanguages->pluck('language_id')->map(fn ($id) => (string) $id)->values(), 'options' => $profileLanguageOptions->map(fn ($language) => ['value' => $language->id, 'label' => $language->name])->values()],
        'lead_source' => ['label' => 'Source', 'type' => 'select', 'value' => $lead->lead_source, 'options' => collect([2 => 'Social Media', 3 => 'Referral', 4 => 'Email Campaign', 5 => 'Cold Call', 6 => 'Trade Show', 7 => 'Website'])->map(fn ($label, $id) => ['value' => $id, 'label' => $label])->values()],
        'qualification' => ['label' => 'Qualification', 'type' => 'textarea', 'value' => $lead->qualification],
        'interest_products' => ['label' => 'Interest Products', 'type' => 'multiselect', 'value' => $lead->interestProducts->pluck('id')->map(fn ($id) => (string) $id)->values(), 'options' => $profileProductOptions->map(fn ($product) => ['value' => $product->id, 'label' => $product->product_name])->values()],
        'address1' => ['label' => 'Address', 'type' => 'address', 'value' => $lead->address_1, 'secondary' => $lead->address_2],
        'city' => ['label' => 'City / Province', 'type' => 'city', 'value' => $lead->city, 'secondary' => $lead->province],
        'country_id' => ['label' => 'Country', 'type' => 'select', 'value' => $lead->country_id, 'options' => $profileCountryOptions->map(fn ($country) => ['value' => $country->id, 'label' => $country->name])->values()],
        'zipcode' => ['label' => 'Zip Code', 'type' => 'text', 'value' => $lead->zip_code],
        'contact_methods' => ['label' => 'Contact Method', 'type' => 'multiselect', 'value' => collect($lead->contact_method)->map(fn ($method) => (string) $method)->values(), 'options' => collect(['Phone', 'Email', 'Social Media', 'Postal Mail', 'Fax'])->map(fn ($method) => ['value' => $method, 'label' => $method])->values()],
    ];
    $sourceNames = [1 => 'Not selected', 2 => 'Social Media', 3 => 'Referral', 4 => 'Email Campaign', 5 => 'Cold Call', 6 => 'Trade Show', 7 => 'Website'];
    $sourceName = $sourceNames[(int) $lead->lead_source] ?? ($lead->lead_source ?: 'Not selected');
    $temperature = ucfirst((string) ($lead->temperature ?: 'cold'));
    $temperatureClass = match (strtolower($temperature)) {
        'hot' => 'danger',
        'warm' => 'warning',
        default => 'info',
    };
    $activityMoment = function ($activity) {
        if (!$activity) {
            return null;
        }

        return $activity->start_date
            ? \Carbon\Carbon::parse($activity->start_date.' '.($activity->start_time ?: '00:00:00'))
            : $activity->created_at;
    };
@endphp

@once
    <style>
        .lead-overview {
            --lead-overview-border: #e9edf3;
            --lead-overview-muted: #64748b;
        }

        .lead-overview .overview-heading {
            padding: 2px 2px 18px;
            border-bottom: 1px solid #edf0f4;
        }

        .lead-overview .overview-heading-label {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 5px 8px;
            border-radius: 7px;
            background: #eef2ff;
            color: #3454d1;
            font-size: 10px;
            font-weight: 750;
            letter-spacing: .05em;
            text-transform: uppercase;
        }

        .lead-overview .overview-stage-card {
            margin-bottom: 20px;
            padding: 16px 16px 5px;
            border: 1px solid var(--lead-overview-border);
            border-radius: 14px;
            background: #fff;
        }

        .lead-overview .overview-stage-flow {
            overflow-x: auto;
            padding: 4px 2px 14px;
        }

        .lead-overview .overview-stage-flow .arrow-steps {
            min-width: 760px;
        }

        .lead-overview .arrow-steps .step.done span:before {
            opacity: 1;
        }

        .lead-overview .arrow-steps .step.qualified-completed {
            color: #fff;
            background-color: #198754;
        }

        .lead-overview .arrow-steps .step.qualified-completed:after {
            border-left-color: #198754;
        }

        .lead-overview .arrow-steps .step.unqualified-completed {
            color: #fff;
            background-color: #dc3545;
        }

        .lead-overview .arrow-steps .step.unqualified-completed:after {
            border-left-color: #dc3545;
        }

        .lead-overview .arrow-steps .step.terminal-alternative {
            color: #94a3b8;
            background-color: #f1f5f9;
        }

        .lead-overview .arrow-steps .step.terminal-alternative:after {
            border-left-color: #f1f5f9;
        }

        .lead-overview .arrow-step-state {
            display: block;
            margin-top: 1px;
            font-size: 9px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: .04em;
        }

        .lead-overview .overview-metric {
            position: relative;
            height: 100%;
            padding: 18px;
            border: 1px solid var(--lead-overview-border);
            border-radius: 14px;
            background: #fff;
            box-shadow: 0 6px 18px rgba(15, 23, 42, .04);
            overflow: hidden;
            transition: transform .18s ease, box-shadow .18s ease;
        }

        .lead-overview .overview-metric:before {
            position: absolute;
            top: 0;
            right: 0;
            left: 0;
            height: 3px;
            background: var(--metric-accent, #3454d1);
            content: '';
        }

        .lead-overview .overview-metric:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 24px rgba(15, 23, 42, .075);
        }

        .lead-overview .overview-metric.metric-primary { --metric-accent: #3454d1; }
        .lead-overview .overview-metric.metric-success { --metric-accent: #22a06b; }
        .lead-overview .overview-metric.metric-warning { --metric-accent: #f59e0b; }
        .lead-overview .overview-metric.metric-info { --metric-accent: #0ea5e9; }

        .lead-overview .overview-metric-icon,
        .lead-overview .overview-section-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            flex: 0 0 auto;
            border-radius: 12px;
        }

        .lead-overview .overview-metric-icon {
            width: 42px;
            height: 42px;
            font-size: 18px;
        }

        .lead-overview .overview-panel {
            height: 100%;
            border: 1px solid var(--lead-overview-border);
            border-radius: 16px;
            background: #fff;
            box-shadow: 0 8px 24px rgba(15, 23, 42, .04);
            overflow: hidden;
        }

        .lead-overview .overview-panel-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 18px 20px;
            border-bottom: 1px solid var(--lead-overview-border);
            background: linear-gradient(135deg, #fbfcfe, #f7f9fd);
        }

        .lead-overview .overview-section-icon {
            width: 36px;
            height: 36px;
            background: rgba(52, 88, 255, .10);
            color: #3458ff;
        }

        .lead-overview .overview-panel-body {
            padding: 8px 20px;
        }

        .lead-overview .overview-detail-row {
            display: grid;
            grid-template-columns: minmax(125px, .8fr) minmax(0, 1.2fr);
            gap: 18px;
            align-items: center;
            min-height: 52px;
            padding: 11px 0;
            border-bottom: 1px solid #f0f2f5;
        }

        .lead-overview .overview-detail-row:last-child {
            border-bottom: 0;
        }

        .lead-overview .overview-detail-label {
            color: var(--lead-overview-muted);
            font-size: 13px;
            font-weight: 600;
        }

        .lead-overview .overview-detail-value {
            min-width: 0;
            color: #172033;
            font-weight: 600;
            overflow-wrap: anywhere;
            text-align: right;
        }

        .lead-overview .overview-empty-value {
            display: inline-flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: flex-end;
            gap: 7px;
            color: #94a3b8;
            font-weight: 550;
        }

        .lead-overview .overview-add-field {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 7px;
            border: 1px solid #d8e0f1;
            border-radius: 7px;
            background: #f7f9ff;
            color: #3454d1;
            font-size: 10px;
            font-weight: 750;
            white-space: nowrap;
        }

        .lead-overview .overview-add-field:hover {
            border-color: #3454d1;
            background: #eef2ff;
            color: #2944ad;
        }

        .lead-overview .overview-edit-field {
            display: inline-flex;
            align-items: center;
            justify-content: flex-end;
            gap: .45rem;
            color: inherit;
            text-decoration: none;
            border-radius: .45rem;
            padding: .2rem .4rem;
            margin: -.2rem -.4rem;
            transition: background-color .18s ease, color .18s ease;
        }

        .lead-overview .overview-edit-field:hover,
        .lead-overview .overview-edit-field:focus-visible {
            color: var(--bs-primary);
            background: rgba(var(--bs-primary-rgb), .08);
            outline: none;
        }

        .lead-profile-field-modal,
        .lead-profile-field-modal .modal-dialog,
        .lead-profile-field-modal .modal-content {
            box-shadow: none !important;
            filter: none !important;
        }

        .lead-profile-field-modal {
            z-index: 2000 !important;
        }

        .lead-profile-field-modal .modal-content {
            visibility: visible !important;
            opacity: 1 !important;
            background: #fff !important;
        }

        .lead-overview .activity-snapshot {
            position: relative;
            padding: 16px 16px 16px 48px;
            border: 1px solid var(--lead-overview-border);
            border-radius: 12px;
            background: #fbfcfe;
        }

        .lead-overview .activity-snapshot-icon {
            position: absolute;
            top: 16px;
            left: 16px;
            color: #3458ff;
        }

        .lead-overview .progress {
            background-color: #edf1f7;
        }

        @media (max-width: 575.98px) {
            .lead-overview .overview-detail-row {
                grid-template-columns: 1fr;
                gap: 4px;
            }

            .lead-overview .overview-detail-value {
                text-align: left;
            }
        }
    </style>
@endonce

<div class="lead-overview" data-testid="lead-profile-overview">
    <div class="overview-heading d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
        <div>
            <span class="overview-heading-label mb-2"><i class="feather-grid"></i>Profile summary</span>
            <h5 class="fw-bold mb-1">Lead Overview</h5>
            <p class="text-muted mb-0">A complete snapshot of this Lead's progress, contact details, and engagement.</p>
        </div>
        @unless ($leadIsCompleted)
        <div class="d-flex flex-wrap gap-2">
            @can('create_activities')
                <a href="{{ route('schedule-activity-create', ['leadId' => $lead->id]) }}" class="btn btn-sm btn-outline-primary">
                    <i class="feather-activity me-1"></i>Add Activity
                </a>
            @endcan
            @can('update_leads')
                <a href="{{ route('leads.edit', ['id' => $lead->id]) }}" class="btn btn-sm btn-primary">
                    <i class="feather-edit-3 me-1"></i>Edit Lead
                </a>
            @endcan
        </div>
        @endunless
    </div>

    <div class="overview-stage-card">
        <div class="d-flex align-items-center justify-content-between gap-3 mb-3">
            <div><div class="fw-bold text-dark">Lifecycle Progress</div><small class="text-muted">Current position in the Lead pipeline</small></div>
            <span class="badge bg-soft-primary text-primary">{{ $leadStatusProgress }}%</span>
        </div>
        <div class="overview-stage-flow">
            <div class="arrow-steps clearfix">
            @foreach ($stages as $statusStage)
                @php
                    $statusStageId = (int) $statusStage->id;
                    $selectedTerminal = $isTerminalLead && $statusStageId === (int) $lead->stage_id;
                    $isCompletedPath = $isTerminalLead
                        ? $statusStageId <= 5 || $selectedTerminal
                        : $statusStageId <= (int) $lead->stage_id;
                @endphp
                <div @class([
                        'step',
                        'current' => $isCompletedPath,
                        'done' => $isTerminalLead && $isCompletedPath,
                        'qualified-completed' => (int) $lead->stage_id === 6 && $statusStageId === 6,
                        'unqualified-completed' => (int) $lead->stage_id === 7 && $statusStageId === 7,
                        'terminal-alternative' => $isTerminalLead && in_array($statusStageId, [6, 7], true) && !$selectedTerminal,
                    ])
                    data-stage-id="{{ $statusStage->id }}">
                    <span>
                        {{ $statusStage->name }}
                        @if ($selectedTerminal)
                            <small class="arrow-step-state">Completed</small>
                        @endif
                    </span>
                </div>
            @endforeach
            </div>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-sm-6 col-xl-3">
            <div class="overview-metric metric-primary">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <span class="overview-metric-icon bg-soft-primary text-primary"><i class="feather-trending-up"></i></span>
                    <strong class="fs-5">{{ $summaryProgress }}%</strong>
                </div>
                <div class="fw-semibold mb-1">Overall Progress</div>
                <div class="progress ht-5" role="progressbar" aria-label="Overall Lead progress" aria-valuenow="{{ $summaryProgress }}" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar bg-primary" style="width: {{ $summaryProgress }}%"></div>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="overview-metric metric-success">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <span class="overview-metric-icon bg-soft-success text-success"><i class="feather-check-circle"></i></span>
                    <strong class="fs-5">{{ $activityProgress }}%</strong>
                </div>
                <div class="fw-semibold mb-1">Activity Completion</div>
                <small class="text-muted">{{ $completedActivities }} of {{ $activities->count() }} completed</small>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="overview-metric metric-warning">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <span class="overview-metric-icon bg-soft-warning text-warning"><i class="feather-activity"></i></span>
                    <strong class="fs-5">{{ $activities->count() }}</strong>
                </div>
                <div class="fw-semibold mb-1">Total Activities</div>
                <small class="text-muted">All Lead interactions</small>
            </div>
        </div>
        <div class="col-sm-6 col-xl-3">
            <div class="overview-metric metric-info">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <span class="overview-metric-icon bg-soft-info text-info"><i class="feather-briefcase"></i></span>
                    <strong class="fs-5">{{ $deals->count() }}</strong>
                </div>
                <div class="fw-semibold mb-1">Linked Deals</div>
                <small class="text-muted">Converted opportunities</small>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-xl-6">
            <section class="overview-panel">
                <div class="overview-panel-header">
                    <span class="overview-section-icon"><i class="feather-user"></i></span>
                    <div><h6 class="fw-bold mb-0">Contact Information</h6><small class="text-muted">Primary contact channels</small></div>
                </div>
                <div class="overview-panel-body">
                    @foreach ([
                        ['Full Name', trim($lead->first_name.' '.$lead->last_name), 'first_name'],
                        ['Email', $primaryEmail, 'emails'],
                        ['Phone', $primaryPhone, 'phones'],
                        ['Job Title', $lead->job_title, 'job_title'],
                        ['Company', $lead->company?->name, 'company_id'],
                        ['Languages', $languageNames, 'languages'],
                    ] as [$label, $value, $field])
                        <div class="overview-detail-row">
                            <span class="overview-detail-label">{{ $label }}</span>
                            <span class="overview-detail-value">
                                @if ($canUpdateLeadProfileData)
                                    <a href="{{ $leadEditFieldUrl($field) }}" class="overview-edit-field" data-edit-field="{{ $field }}" title="Update {{ $label }}">
                                        @if (filled($value))
                                            {{ $value }}
                                        @else
                                            <span class="overview-empty-value">Not provided <span class="overview-add-field"><i class="feather-plus"></i>Add data</span></span>
                                        @endif
                                    </a>
                                @elseif (filled($value))
                                    {{ $value }}
                                @else
                                    <span class="overview-empty-value">Not provided</span>
                                @endif
                            </span>
                        </div>
                    @endforeach
                </div>
            </section>
        </div>
        <div class="col-xl-6">
            <section class="overview-panel">
                <div class="overview-panel-header">
                    <span class="overview-section-icon"><i class="feather-target"></i></span>
                    <div><h6 class="fw-bold mb-0">Lead Details</h6><small class="text-muted">Qualification and ownership</small></div>
                </div>
                <div class="overview-panel-body">
                    <div class="overview-detail-row"><span class="overview-detail-label">Current Status</span><span class="overview-detail-value"><span class="badge {{ (int) $lead->stage_id === 6 ? 'bg-success' : ((int) $lead->stage_id === 7 ? 'bg-danger' : 'bg-primary') }}">{{ $stageName }}{{ $isTerminalLead ? ' · Completed' : '' }}</span></span></div>
                    <div class="overview-detail-row"><span class="overview-detail-label">Record Status</span><span class="overview-detail-value"><span class="badge {{ $isTerminalLead ? 'bg-soft-primary text-primary' : 'bg-soft-success text-success' }}">{{ $isTerminalLead ? 'Completed' : ucfirst($lead->status ?: 'active') }}</span></span></div>
                    <div class="overview-detail-row"><span class="overview-detail-label">Owner</span><span class="overview-detail-value">{{ $lead->assignedUser?->name ?: 'Not assigned' }}</span></div>
                    <div class="overview-detail-row">
                        <span class="overview-detail-label">Source</span>
                        <span class="overview-detail-value">
                            @if ($canUpdateLeadProfileData)
                                <a href="{{ $leadEditFieldUrl('lead_source') }}" class="overview-edit-field" data-edit-field="lead_source" title="Update Source">
                                    @if (filled($lead->lead_source))
                                        {{ $sourceName }}
                                    @else
                                        <span class="overview-empty-value">Not selected <span class="overview-add-field"><i class="feather-plus"></i>Add data</span></span>
                                    @endif
                                </a>
                            @elseif (filled($lead->lead_source))
                                {{ $sourceName }}
                            @else
                                <span class="overview-empty-value">Not selected</span>
                            @endif
                        </span>
                    </div>
                    <div class="overview-detail-row">
                        <span class="overview-detail-label">Qualification</span>
                        <span class="overview-detail-value">
                            @if ($canUpdateLeadProfileData)
                                <a href="{{ $leadEditFieldUrl('qualification') }}" class="overview-edit-field" data-edit-field="qualification" title="Update Qualification">
                                    @if (filled($lead->qualification))
                                        {{ $lead->qualification }}
                                    @else
                                        <span class="overview-empty-value">Not provided <span class="overview-add-field"><i class="feather-plus"></i>Add data</span></span>
                                    @endif
                                </a>
                            @elseif (filled($lead->qualification))
                                {{ $lead->qualification }}
                            @else
                                <span class="overview-empty-value">Not provided</span>
                            @endif
                        </span>
                    </div>
                    <div class="overview-detail-row"><span class="overview-detail-label">Priority</span><span class="overview-detail-value">{{ $lead->priority?->name ?: 'Not set' }}</span></div>
                    <div class="overview-detail-row">
                        <span class="overview-detail-label">Interest Products</span>
                        <span class="overview-detail-value">
                            @if ($canUpdateLeadProfileData)
                                <a href="{{ $leadEditFieldUrl('interest_products') }}" class="overview-edit-field" data-edit-field="interest_products" title="Update Interest Products">
                                    @if ($interestProductNames)
                                        {{ $interestProductNames }}
                                    @else
                                        <span class="overview-empty-value">Not selected <span class="overview-add-field"><i class="feather-plus"></i>Add data</span></span>
                                    @endif
                                </a>
                            @elseif ($interestProductNames)
                                {{ $interestProductNames }}
                            @else
                                <span class="overview-empty-value">Not selected</span>
                            @endif
                        </span>
                    </div>
                    <div class="overview-detail-row"><span class="overview-detail-label">Temperature</span><span class="overview-detail-value"><span class="badge bg-soft-{{ $temperatureClass }} text-{{ $temperatureClass }}">{{ $temperature }}</span></span></div>
                    <div class="overview-detail-row"><span class="overview-detail-label">Lead Score</span><span class="overview-detail-value">{{ (int) ($lead->lead_score ?? 0) }} / 100</span></div>
                    <div class="overview-detail-row"><span class="overview-detail-label">Created</span><span class="overview-detail-value">{{ $lead->created_at?->format('d M Y, h:i A') ?: '—' }}</span></div>
                </div>
            </section>
        </div>
    </div>

    <div class="row g-4">
        <div class="col-xl-7">
            <section class="overview-panel">
                <div class="overview-panel-header">
                    <span class="overview-section-icon"><i class="feather-clock"></i></span>
                    <div><h6 class="fw-bold mb-0">Activity Snapshot</h6><small class="text-muted">Recent and upcoming engagement</small></div>
                </div>
                <div class="overview-panel-body py-3">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="activity-snapshot h-100">
                                <i class="feather-check-circle activity-snapshot-icon"></i>
                                <small class="text-muted d-block mb-1">Last interaction</small>
                                <div class="fw-semibold">{{ $lastInteraction?->title ?: 'No past activity' }}</div>
                                @if ($activityMoment($lastInteraction))
                                    <small class="text-muted">{{ $activityMoment($lastInteraction)->format('d M Y, h:i A') }}</small>
                                @endif
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="activity-snapshot h-100">
                                <i class="feather-calendar activity-snapshot-icon"></i>
                                <small class="text-muted d-block mb-1">Next interaction</small>
                                <div class="fw-semibold">{{ $nextInteraction?->title ?: 'Nothing scheduled' }}</div>
                                @if ($activityMoment($nextInteraction))
                                    <small class="text-muted">{{ $activityMoment($nextInteraction)->format('d M Y, h:i A') }}</small>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
        <div class="col-xl-5">
            <section class="overview-panel">
                <div class="overview-panel-header">
                    <span class="overview-section-icon"><i class="feather-map-pin"></i></span>
                    <div><h6 class="fw-bold mb-0">Location & Preferences</h6><small class="text-muted">Address and communication</small></div>
                </div>
                <div class="overview-panel-body">
                    @foreach ([
                        ['Address', collect([$lead->address_1, $lead->address_2])->filter()->join(', '), 'address1', 'Not provided'],
                        ['City / Province', collect([$lead->city, $lead->province])->filter()->join(', '), 'city', 'Not provided'],
                        ['Country', $lead->country?->name, 'country_id', 'Not provided'],
                        ['Zip Code', $lead->zip_code, 'zipcode', 'Not provided'],
                        ['Contact Method', $communicationMethods, 'contact_methods', 'Not selected'],
                    ] as [$label, $value, $field, $emptyText])
                        <div class="overview-detail-row">
                            <span class="overview-detail-label">{{ $label }}</span>
                            <span class="overview-detail-value">
                                @if ($canUpdateLeadProfileData)
                                    <a href="{{ $leadEditFieldUrl($field) }}" class="overview-edit-field" data-edit-field="{{ $field }}" title="Update {{ $label }}">
                                        @if (filled($value))
                                            {{ $value }}
                                        @else
                                            <span class="overview-empty-value">{{ $emptyText }} <span class="overview-add-field"><i class="feather-plus"></i>Add data</span></span>
                                        @endif
                                    </a>
                                @elseif (filled($value))
                                    {{ $value }}
                                @else
                                    <span class="overview-empty-value">{{ $emptyText }}</span>
                                @endif
                            </span>
                        </div>
                    @endforeach
                </div>
            </section>
        </div>
    </div>
</div>

@if ($canUpdateLeadProfileData)
    <div class="modal lead-profile-field-modal" id="leadProfileFieldModal" tabindex="-1" aria-labelledby="leadProfileFieldModalLabel" aria-hidden="true" data-bs-backdrop="false">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border">
                <form id="leadProfileFieldForm">
                    <div class="modal-header">
                        <div>
                            <h5 class="modal-title" id="leadProfileFieldModalLabel">Update Lead field</h5>
                            <small class="text-muted">Changes are saved directly to this Lead.</small>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" id="leadProfileFieldName" name="field">
                        <div id="leadProfileFieldControl"></div>
                        <div class="alert alert-danger d-none mt-3 mb-0" id="leadProfileFieldError" role="alert"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="leadProfileFieldSave"><i class="feather-save me-1"></i>Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    @once
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const fieldConfig = @json($profileFieldOptions);
                const modalElement = document.getElementById('leadProfileFieldModal');
                const form = document.getElementById('leadProfileFieldForm');
                const control = document.getElementById('leadProfileFieldControl');
                const errorBox = document.getElementById('leadProfileFieldError');
                const saveButton = document.getElementById('leadProfileFieldSave');
                document.body.appendChild(modalElement);
                const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
                let activeLink = null;

                const addLabel = function (text, target) {
                    const label = document.createElement('label');
                    label.className = 'form-label fw-semibold';
                    label.htmlFor = target;
                    label.textContent = text;
                    control.appendChild(label);
                };

                const addInput = function (name, label, value, type = 'text') {
                    const id = `lead-profile-${name}`;
                    addLabel(label, id);
                    const input = document.createElement('input');
                    input.type = type;
                    input.name = name;
                    input.id = id;
                    input.className = 'form-control mb-3';
                    input.value = value || '';
                    input.required = true;
                    control.appendChild(input);
                    return input;
                };

                const renderControl = function (field) {
                    const config = fieldConfig[field];
                    control.replaceChildren();
                    document.getElementById('leadProfileFieldName').value = field;
                    document.getElementById('leadProfileFieldModalLabel').textContent = `Update ${config.label}`;

                    if (config.type === 'name') {
                        addInput('value', 'First Name', config.value);
                        addInput('secondary_value', 'Last Name', config.secondary);
                        return;
                    }
                    if (config.type === 'address') {
                        addInput('value', 'Address Line 1', config.value);
                        addInput('secondary_value', 'Address Line 2', config.secondary).required = false;
                        return;
                    }
                    if (config.type === 'city') {
                        addInput('value', 'City', config.value);
                        addInput('secondary_value', 'Province', config.secondary).required = false;
                        return;
                    }
                    if (config.type === 'textarea') {
                        const id = 'lead-profile-value';
                        addLabel(config.label, id);
                        const textarea = document.createElement('textarea');
                        textarea.name = 'value';
                        textarea.id = id;
                        textarea.rows = 4;
                        textarea.required = true;
                        textarea.className = 'form-control';
                        textarea.value = config.value || '';
                        control.appendChild(textarea);
                        return;
                    }
                    if (config.type === 'select' || config.type === 'multiselect') {
                        const id = 'lead-profile-value';
                        addLabel(config.label, id);
                        const select = document.createElement('select');
                        select.name = 'value';
                        select.id = id;
                        select.required = true;
                        select.multiple = config.type === 'multiselect';
                        select.className = 'form-select';
                        if (select.multiple) select.size = Math.min(6, Math.max(3, config.options.length));
                        const selectedValues = new Set((Array.isArray(config.value) ? config.value : [config.value]).map(String));
                        config.options.forEach(function (option) {
                            const item = document.createElement('option');
                            item.value = option.value;
                            item.textContent = option.label;
                            item.selected = selectedValues.has(String(option.value));
                            select.appendChild(item);
                        });
                        control.appendChild(select);
                        if (select.multiple) {
                            const help = document.createElement('small');
                            help.className = 'text-muted d-block mt-2';
                            help.textContent = 'Select one or more options.';
                            control.appendChild(help);
                        }
                        return;
                    }
                    addInput('value', config.label, config.value, config.type);
                };

                document.querySelectorAll('[data-edit-field]').forEach(function (link) {
                    link.addEventListener('click', function (event) {
                        event.preventDefault();
                        activeLink = link;
                        errorBox.classList.add('d-none');
                        renderControl(link.dataset.editField);
                        modal.show();
                        modalElement.addEventListener('shown.bs.modal', function focusField() {
                            control.querySelector('input, select, textarea')?.focus();
                        }, { once: true });
                    });
                });

                form.addEventListener('submit', async function (event) {
                    event.preventDefault();
                    errorBox.classList.add('d-none');
                    const field = document.getElementById('leadProfileFieldName').value;
                    const valueControl = form.elements.value;
                    const payload = { field };
                    payload.value = valueControl.multiple
                        ? Array.from(valueControl.selectedOptions).map(option => option.value)
                        : valueControl.value;
                    if (form.elements.secondary_value) payload.secondary_value = form.elements.secondary_value.value;

                    saveButton.disabled = true;
                    saveButton.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Saving';
                    try {
                        const response = await fetch(@json(route('leads.profile-field.update', $lead->id)), {
                            method: 'PATCH',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
                            },
                            body: JSON.stringify(payload),
                        });
                        const result = await response.json();
                        if (!response.ok) {
                            const validationMessage = result.errors ? Object.values(result.errors).flat()[0] : null;
                            throw new Error(validationMessage || result.message || 'Unable to update this field.');
                        }
                        fieldConfig[field].value = payload.value;
                        if ('secondary_value' in payload) fieldConfig[field].secondary = payload.secondary_value;
                        activeLink.textContent = result.display_value;
                        modal.hide();
                    } catch (error) {
                        errorBox.textContent = error.message;
                        errorBox.classList.remove('d-none');
                    } finally {
                        saveButton.disabled = false;
                        saveButton.innerHTML = '<i class="feather-save me-1"></i>Save';
                    }
                });
            });
        </script>
    @endonce
@endif
