@extends('layouts.app')

@section('title', 'Leads View')

@section('content')
    @include('leads.partials.status-colors')
    <style>
        .lead-profile-page { padding-top: 20px; background: #f7f9fc; }
        .lead-profile-shell { align-items: flex-start; flex-wrap: nowrap; gap: 20px; margin: 0; }
        .lead-profile-sidebar { position: sticky; top: 86px; flex: 0 0 238px; width: 238px; border: 1px solid #e4e9f1; border-radius: 16px; background: #fff; box-shadow: 0 10px 32px rgba(15, 23, 42, .055); overflow: hidden; }
        .lead-profile-sidebar-head { padding: 18px; border-bottom: 1px solid #edf0f4; background: linear-gradient(145deg, #fbfcff, #f4f7ff); }
        .lead-profile-sidebar-icon { display: inline-flex; width: 38px; height: 38px; align-items: center; justify-content: center; border-radius: 11px; background: #3454d1; color: #fff; box-shadow: 0 7px 15px rgba(52, 84, 209, .18); }
        .lead-profile-sidebar .content-sidebar-body { padding: 10px; }
        .lead-profile-sidebar .nav-item { border: 0 !important; margin-bottom: 4px; }
        .lead-profile-sidebar .nav-link { display: flex; align-items: center; gap: 11px; min-height: 42px; padding: 9px 12px; border: 0; border-radius: 9px; color: #64748b; font-size: 13px; font-weight: 650; transition: background .18s ease, color .18s ease, transform .18s ease; }
        .lead-profile-sidebar .nav-link i { width: 18px; font-size: 16px; }
        .lead-profile-sidebar .nav-link:hover { transform: translateX(2px); background: #f6f8fc; color: #3454d1; }
        .lead-profile-sidebar .nav-link.active { background: #eef2ff; color: #3454d1; box-shadow: inset 3px 0 0 #3454d1; }
        .lead-profile-shell > .col { padding: 0; }
        .lead-profile-card { border: 1px solid #e4e9f1 !important; border-radius: 16px; background: #fff; box-shadow: 0 12px 36px rgba(15, 23, 42, .06); overflow: hidden; }
        .lead-profile-hero { padding: 26px; background: radial-gradient(circle at 92% 5%, rgba(52, 84, 209, .09), transparent 30%), linear-gradient(135deg, #fff 0%, #f8faff 100%); border-bottom: 1px solid #e9edf3; }
        .lead-profile-avatar { display: inline-flex; width: 62px; height: 62px; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 18px; background: linear-gradient(145deg, #3454d1, #5573e8); color: #fff; font-size: 19px; font-weight: 800; letter-spacing: .04em; box-shadow: 0 10px 22px rgba(52, 84, 209, .24); }
        .lead-profile-eyebrow { color: #7c8798; font-size: 10px; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
        .lead-profile-title { color: #172033; font-size: 23px; font-weight: 780; letter-spacing: -.025em; }
        .lead-profile-contact { color: #64748b; font-size: 13px; }
        .lead-profile-facts { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; }
        .lead-profile-fact { display: inline-flex; align-items: center; gap: 7px; min-width: 0; min-height: 34px; max-width: 260px; padding: 7px 10px; border: 1px solid #e5e9f0; border-radius: 9px; background: rgba(255,255,255,.9); color: #526072; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .lead-profile-fact i { color: #3454d1; }
        .lead-profile-quick-stats { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; }
        .lead-profile-quick-stat { min-width: 112px; padding: 9px 11px; border: 1px solid #e8ecf3; border-radius: 10px; background: rgba(255,255,255,.75); }
        .lead-profile-quick-stat small { display: block; margin-bottom: 2px; color: #8a95a5; font-size: 9px; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }
        .lead-profile-quick-stat strong { display: block; max-width: 160px; overflow: hidden; color: #263247; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
        .lead-profile-status-panel { min-width: 285px; padding: 17px; border: 1px solid #dfe5ef; border-radius: 14px; background: rgba(255,255,255,.94); box-shadow: 0 8px 20px rgba(15,23,42,.045); }
        .lead-profile-status-panel .form-label { color: #64748b; font-size: 10px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }
        .lead-profile-status-panel .select2-container { width: 100% !important; }
        .lead-profile-card > .tab-content > .tab-pane { background: #fbfcfe; }
        .lead-profile-card > .tab-content > .tab-pane.active { min-height: 520px; }
        .lead-product-panel { border: 1px solid #e4e9f1; border-radius: 12px; background: #fff; overflow: hidden; }
        .lead-product-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 18px 20px; border-bottom: 1px solid #edf0f4; background: linear-gradient(135deg, #fff, #f7f9ff); }
        .lead-product-icon { display: inline-flex; width: 40px; height: 40px; align-items: center; justify-content: center; border-radius: 10px; background: #eef2ff; color: #3454d1; }
        .lead-product-form { padding: 16px 20px; border-bottom: 1px solid #edf0f4; background: #fbfcfe; }
        .lead-product-table { min-width: 720px; }
        .lead-product-table th { color: #7c8798; font-size: 11px; font-weight: 750; letter-spacing: .04em; text-transform: uppercase; white-space: nowrap; }
        .lead-product-empty { padding: 42px 20px; text-align: center; color: #7c8798; }
        @media (max-width: 1199.98px) {
            .lead-profile-shell { display: block; }
            .lead-profile-sidebar { position: static; width: 100%; margin-bottom: 16px; }
            .lead-profile-sidebar-head { display: none; }
            .lead-profile-sidebar .nav { flex-direction: row !important; flex-wrap: nowrap; overflow-x: auto; padding-bottom: 2px; }
            .lead-profile-sidebar .nav-item { flex: 0 0 auto; }
            .lead-profile-sidebar .nav-link:hover { transform: none; }
            .lead-profile-sidebar .nav-link.active { box-shadow: inset 0 -3px 0 #3454d1; }
        }
        @media (max-width: 767.98px) {
            .lead-profile-page { padding-top: 12px; }
            .lead-profile-hero { padding: 18px; }
            .lead-profile-title { font-size: 20px; }
            .lead-profile-status-panel { width: 100%; min-width: 0; }
            .lead-profile-fact { max-width: 100%; }
            .lead-product-panel-head { align-items: flex-start; flex-direction: column; }
        }
    </style>
    <div class="page-header">
        <div class="page-header-left d-flex align-items-center">
            <a href="{{ route('leads') }}" class="avatar-text avatar-md me-3" title="Back to Leads" aria-label="Back to Leads">
                <i class="feather-arrow-left"></i>
            </a>
            <div class="page-header-title">
                <h5 class="mb-1">Lead Profile</h5>
                <small class="text-muted d-none d-lg-block">Lead #{{ str_pad((string) $lead->id, 4, '0', STR_PAD_LEFT) }}</small>
            </div>
        </div>
        <div class="page-header-right ms-auto">
            <div class="page-header-right-items">
                <div class="d-flex d-md-none">
                    <a href="javascript:void(0)" class="page-header-right-close-toggle">
                        <i class="feather-arrow-left me-2"></i>
                        <span>Back</span>
                    </a>
                </div>
                <div class="d-flex align-items-center gap-2 page-header-right-items-wrapper">
                    @if ($leadIsCompleted)
                        @can('create_deals')
                            @if ((int) $lead->stage_id === 6 && !$lead->moved_at)
                                <a href="{{ route('leads.conversion-review', $lead->id) }}" class="btn btn-success">
                                    <i class="feather-arrow-right-circle me-2"></i><span>Move to Deal</span>
                                </a>
                            @endif
                        @endcan
                        @if ($canReopen)
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#reopenLeadModal">
                                <i class="feather-rotate-ccw me-2"></i><span>Reopen Lead</span>
                            </button>
                        @endif
                    @else
                    @can('share_leads')
                        <x-internal-share-button :url="route('leads.view', ['id' => $lead->id])"
                            :title="'Lead: '.($lead->topic ?: trim($lead->first_name.' '.$lead->last_name))" />
                    @endcan
                    @can('create_deals')
                        @if ((int) $lead->stage_id === 6 && !$lead->moved_at)
                            <a href="{{ route('leads.conversion-review', $lead->id) }}"
                                class="btn btn-success">
                                <i class="feather-arrow-right-circle me-2"></i>
                                <span>Move to Deal</span>
                            </a>
                        @endif
                    @endcan
                    @if ($lead->stage_id == 7)
                        <button type="button" class="btn btn-danger" data-bs-toggle="modal"
                            data-bs-target="#closedLostModal">
                            <i class="feather-x-circle me-2"></i>
                            <span>Close Lead</span>
                        </button>
                    @endif
                    <a href="{{ route('leads-create') }}" class="btn btn-primary">
                        <i class="feather-plus me-2"></i>
                        <span>Create Lead</span>
                    </a>
                    @endif
                </div>
            </div>
            <div class="d-md-none d-flex align-items-center">
                <a href="javascript:void(0)" class="page-header-right-open-toggle">
                    <i class="feather-align-right fs-20"></i>
                </a>
            </div>
        </div>
    </div>
    <!-- [ page-header ] end -->
    <!-- [ Main Content ] start -->
    <div class="main-content lead-profile-page">

        <x-campaign-conversion-attribution :record="$lead" />

        <div class="row lead-profile-shell">
            {{-- <div class="col-xxl-4 col-xl-6">
                <div class="card stretch stretch-full">
                    <div class="card-body">
                        <div class="mb-4 text-center">

                            <div class="mb-4">
                                <a href="javascript:void(0);" class="fs-20 fw-bold d-block">
                                    {{ $lead->first_name }} {{ $lead->last_name }}</a>
                                @if ($lead->contactEmails->isNotEmpty())
                                    <a href="javascript:void(0);" class="fs-12 fw-normal text-muted d-block">
                                        {{ $lead->contactEmails->first()->email }}
                                    </a>
                                @endif
                            </div>

                        </div>
                        <ul class="list-unstyled mb-4">

                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-phone"></i>Phone</span>
                                @if ($lead->contactPhones->isNotEmpty())
                                    <a href="javascript:void(0);" class="float-end">
                                        {{ $lead->contactPhones->first()->phone }}
                                    </a>
                                @endif
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-mail"></i>Email</span>
                                @if ($lead->contactEmails->isNotEmpty())
                                    <a href="javascript:void(0);" class="float-end">
                                        {{ $lead->contactEmails->first()->email }}
                                    </a>
                                @endif

                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-user"></i>
                                    Full Name:</span>
                                <span class="fw-semibold">{{ $lead->first_name }} {{ $lead->last_name }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-user"></i>
                                    Surname:</span>
                                <span class="fw-semibold">{{ $lead->first_name }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-briefcase"></i>
                                    Job:</span>
                                <span class="fw-semibold">{{ $lead->job_title }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-home"></i>
                                    Company:</span>
                                <span
                                    class="fw-semibold">{{ \App\Models\Company::find($lead->company_id)->name ?? 'No Company' }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-phone"></i>
                                    Mobile Number:</span>
                                <span class="fw-semibold">
                                    @if ($lead->contactPhones->isNotEmpty())
                                        {{ $lead->contactPhones->first()->phone }}
                                    @endif
                                </span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-mail"></i>
                                    Email Address:</span>
                                <span class="fw-semibold">
                                    @if ($lead->contactEmails->isNotEmpty())
                                        {{ $lead->contactEmails->first()->email }}
                                    @endif
                                </span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-map"></i>
                                    Address 1:</span>
                                <span class="fw-semibold">{{ $lead->address_1 }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-map-pin"></i> Address
                                    2:</span>
                                <span class="fw-semibold">{{ $lead->address_2 }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-hash"></i>
                                    Zip Code:</span>
                                <span class="fw-semibold">{{ $lead->zip_code }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-map-pin"></i>
                                    Location:</span>
                                <span
                                    class="fw-semibold">{{ \App\Models\Country::find($lead->country_id)?->name ?? '' }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-map"></i>
                                    Province:</span>
                                <span class="fw-semibold">{{ $lead->province }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-map-pin"></i> City:</span>
                                <span class="fw-semibold">{{ $lead->city }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-calendar"></i> Joining
                                    Date:</span>
                                <span
                                    class="fw-semibold">{{ \Carbon\Carbon::parse($lead->created_at)->format('d M, Y') }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-globe"></i>
                                    Country:</span>
                                <span
                                    class="fw-semibold">{{ \App\Models\Country::find($lead->country_id)?->name ?? '' }}</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-message-square"></i>
                                    Communication:</span>
                                <span class="fw-semibold">Email, Phone</span>
                            </li>
                            <li class="hstack justify-content-between mb-4">
                                <span class="text-muted fw-medium hstack gap-3"><i class="feather-book"></i>
                                    Languages:</span>
                                <span class="fw-semibold">
                                    @foreach ($lead->contactLanguages as $contactLanguage)
                                        @php
                                            $language = \App\Models\Language::find($contactLanguage->language_id);
                                        @endphp
                                        {{ $language ? $language->name : 'No Languages' }},
                                    @endforeach
                                </span>
                            </li>

                        </ul>
                        <div class="d-flex gap-2 text-center pt-4">
                            <a href="javascript:void(0);" class="w-50 btn btn-light-brand">
                                <i class="feather-trash-2 me-2"></i>
                                <span>Delete</span>
                            </a>
                            <a href="{{ route('leads.edit') }}?id={{ $lead->id }}" class="w-50 btn btn-primary">
                                <i class="feather-edit me-2"></i>
                                <span>Edit Profile</span>
                            </a>
                        </div>
                        <div class="card-body">
                            @foreach ($lead->contactSocialMedia as $socialMedia)
                                @php
                                    // Get the social media type by ID
                                    $socialMediaType = $socialMedia->socialMediaType;
                                @endphp

                                <div class="d-flex align-items-center mb-3">
                                    <div class="avatar-text bg-gray-100">
                                        @if ($socialMediaType)
                                            <!-- Display the correct icon based on social media type -->
                                            <i class="feather feather-{{ strtolower($socialMediaType->name) }}"></i>
                                        @endif
                                    </div>
                                    <span class="mx-2 text-gray-300">/</span>
                                    <a href="{{ $socialMedia->value }}" target="_blank" class="text-truncate-1-line">
                                        {{ $socialMedia->value }}
                                    </a>
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>

            </div>
            <div class="col min-w-0">
                <div class="card border-top-0">
                    <div class="card-header p-0">
                        <!-- Nav tabs -->
                        <ul class="nav nav-tabs flex-wrap w-100 text-center customers-nav-tabs" id="myTab"
                            role="tablist">
                            <li class="nav-item flex-fill border-top" role="presentation">
                                <a href="javascript:void(0);" class="nav-link active" id="activityTabLink"
                                    data-bs-toggle="tab" data-bs-target="#activityTab" role="tab"
                                    aria-controls="activityTab" aria-selected="true">Activity</a>
                            </li>
                            <li class="nav-item flex-fill border-top" role="presentation">
                                <a href="javascript:void(0);" class="nav-link" id="noteTabLink" data-bs-toggle="tab"
                                    data-bs-target="#noteTab" role="tab" aria-controls="noteTab"
                                    aria-selected="false">Note</a>
                            </li>


                            <li class="nav-item flex-fill border-top" role="presentation">
                                <a href="javascript:void(0);" class="nav-link" id="accountTabLink" data-bs-toggle="tab"
                                    data-bs-target="#" role="tab" aria-controls="accountTab"
                                    aria-selected="false">Account</a>
                            </li>

                            <li class="nav-item flex-fill border-top" role="presentation">
                                <a href="javascript:void(0);" class="nav-link" id="documentTabLink" data-bs-toggle="tab"
                                    data-bs-target="#" role="tab" aria-controls="documentTab"
                                    aria-selected="false">Document</a>
                            </li>

                        </ul>
                    </div>
                    <div class="tab-content">
                        <div class="tab-pane fade show active p-4" id="activityTab" role="tabpanel"
                            aria-labelledby="activityTabLink">

                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-end">
                                    <a href="{{ route('schedule-activity-create') }}?leadId={{ $lead->id }}"
                                        class="btn btn-sm btn-light-brand">Create
                                        Activity</a>
                                </div>

                                @php
                                    $futureActivities = $activities->filter(function ($activity) {
                                        $activityDate =
                                            $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                        return $activityDate &&
                                            \Carbon\Carbon::parse($activityDate)->isFuture() &&
                                            $activity->activity_type_id != 2;
                                    });
                                @endphp

                                @if ($futureActivities->isNotEmpty())
                                    <div class="profile-details mb-5">
                                        <div class="mb-4 d-flex align-items-center justify-content-between">
                                            <h5 class="fw-bold mb-0">Scheduled Activities:</h5>

                                            <div class="card-body custom-card-action">
                                                <ul class="list-unstyled mb-0 activity-feed-1">
                                                    @foreach ($activities as $activity)
                                                        @php
                                                            $activityDate =
                                                                $activity->end_date ??
                                                                ($activity->due_date ?? $activity->close_by);
                                                        @endphp

                                                        @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isFuture() && $activity->activity_type_id != 2)
                                                            <li class="feed-item feed-item-primary">
                                                                <div class="d-flex gap-4 justify-content-between">
                                                                    <div>
                                                                        <div class="mb-2 text-truncate-1-line">
                                                                            <a href="javascript:void(0)"
                                                                                class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                        </div>
                                                                        <p
                                                                            class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                            {{ $activity->description }}
                                                                        </p>

                                                                        <div>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-success border border-dashed border-gray-500">
                                                                                Start-
                                                                                {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                            </a>

                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-danger border border-dashed border-gray-500">
                                                                                End-
                                                                                {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                            </a>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                                {{ $activity->duration }}</a>
                                                                        </div>
                                                                    </div>
                                                                    <div
                                                                        class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                        {{ $activity->created_at->diffForHumans() }}
                                                                    </div>
                                                                </div>
                                                            </li>
                                                        @endif
                                                    @endforeach
                                                </ul>


                                            </div>
                                        </div>
                                    </div>
                                    <hr class="my-0">

                                @endif
                                @php
                                    $futureActivities = $activities->filter(function ($activity) {
                                        $activityDate =
                                            $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                        return $activityDate &&
                                            \Carbon\Carbon::parse($activityDate)->isPast() &&
                                            $activity->activity_type_id != 2;
                                    });
                                @endphp

                                @if ($futureActivities->isNotEmpty())

                                    <div class="profile-details mb-5">
                                        <div class="mb-4 d-flex align-items-center justify-content-between">
                                            <h5 class="fw-bold mb-0">Expired Activities:</h5>

                                            <div class="card-body custom-card-action">
                                                <ul class="list-unstyled mb-0 activity-feed-1">
                                                    @foreach ($activities as $activity)
                                                        @php
                                                            $activityDate =
                                                                $activity->end_date ??
                                                                ($activity->due_date ?? $activity->close_by);
                                                        @endphp

                                                        @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isPast())
                                                            <li class="feed-item feed-item-primary">
                                                                <div class="d-flex gap-4 justify-content-between">
                                                                    <div>
                                                                        <div class="mb-2 text-truncate-1-line">
                                                                            <a href="javascript:void(0)"
                                                                                class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                        </div>
                                                                        <p
                                                                            class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                            {{ $activity->description }}
                                                                        </p>
                                                                        <div>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-success border border-dashed border-gray-500">
                                                                                Start-
                                                                                {{ $activity->start_date ?? ($activity->due_date ?? $activity->received_on) }}
                                                                            </a>
                                                                            <a href="javascript:void(0)"
                                                                                class="badge text-danger border border-dashed border-gray-500">
                                                                                End-
                                                                                {{ $activity->end_date ?? ($activity->due_date ?? $activity->close_by) }}
                                                                            </a>
                                                                        </div>
                                                                    </div>
                                                                    <div
                                                                        class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                        {{ $activity->created_at->diffForHumans() }}
                                                                    </div>
                                                                </div>
                                                            </li>
                                                        @endif
                                                    @endforeach
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                @endif
                            </div>

                        </div>

                        <div class="tab-pane fade p-4" id="productTab" role="tabpanel" aria-labelledby="productTabLink">
                            <div class="lead-product-panel">
                                <div class="lead-product-panel-head">
                                    <div class="d-flex align-items-center gap-3">
                                        <span class="lead-product-icon"><i class="feather-package"></i></span>
                                        <div>
                                            <h5 class="fw-bold mb-1">Lead Products</h5>
                                            <p class="text-muted mb-0">Products attached only to this Lead.</p>
                                        </div>
                                    </div>
                                    <span class="badge bg-soft-primary text-primary fs-12">
                                        {{ $lead->interestProducts->count() }} linked product(s)
                                    </span>
                                </div>

                                @can('update_leads')
                                    <form method="POST" action="{{ route('leads.products.store', $lead) }}" class="lead-product-form">
                                        @csrf
                                        <div class="row g-3 align-items-end">
                                            <div class="col-lg-8">
                                                <label class="form-label">Product</label>
                                                <select class="form-control" name="product_id" required>
                                                    <option value="">Select Product</option>
                                                    @foreach ($profileProductOptions as $productOption)
                                                        <option value="{{ $productOption->id }}">
                                                            {{ $productOption->product_name }}{{ $productOption->product_code ? ' - '.$productOption->product_code : '' }}
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-lg-4">
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="feather-plus me-1"></i>Add Product
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                @endcan

                                <div class="table-responsive">
                                    <table class="table table-hover align-middle mb-0 lead-product-table">
                                        <thead>
                                            <tr>
                                                <th>Product</th>
                                                <th>Code</th>
                                                <th class="text-end">Price</th>
                                                <th>Status</th>
                                                @can('update_leads')<th class="text-end">Action</th>@endcan
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @forelse($lead->interestProducts as $product)
                                                <tr>
                                                    <td class="fw-semibold">{{ $product->product_name }}</td>
                                                    <td>{{ $product->product_code ?: '-' }}</td>
                                                    <td class="text-end">{{ number_format((float) $product->price, 2) }}</td>
                                                    <td>
                                                        <span class="badge bg-soft-success text-success">
                                                            {{ ucwords($product->status ?: 'active') }}
                                                        </span>
                                                    </td>
                                                    @can('update_leads')
                                                        <td class="text-end">
                                                            <form method="POST" action="{{ route('leads.products.destroy', [$lead, $product]) }}" onsubmit="return confirm('Remove this product from the lead?')">
                                                                @csrf @method('DELETE')
                                                                <button type="submit" class="btn btn-sm bg-soft-danger text-danger" title="Remove product">
                                                                    <i class="feather-trash-2"></i>
                                                                </button>
                                                            </form>
                                                        </td>
                                                    @endcan
                                                </tr>
                                            @empty
                                                <tr>
                                                    <td colspan="5" class="lead-product-empty">
                                                        No products have been added to this Lead.
                                                    </td>
                                                </tr>
                                            @endforelse
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="tab-pane fade p-4" id="noteTab" role="tabpanel" aria-labelledby="noteTabLink">


                            <form action="{{ route('notes.store') }}" method="post">
                                @csrf

                                <input type="hidden" name="contact_id" value="{{ request('id') }}">
                                <div class="mb-3">
                                    <label for="noteTitle" class="form-label">Note Title</label>
                                    <input type="text" class="form-control" id="noteTitle" name="noteTitle"
                                        placeholder="Enter note title" required>
                                </div>
                                <div class="mb-3">
                                    <label for="noteDescription" class="form-label">Note Description</label>
                                    <textarea class="form-control" id="noteDescription" name="noteDescription" rows="4"
                                        placeholder="Enter note description" required></textarea>
                                </div>
                                <div class="d-flex justify-content-end">
                                    <button type="submit" class="btn btn-primary">Add Note</button>
                                </div>
                            </form>


                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-between">
                                    <h5 class="fw-bold mb-0">Notes:</h5>
                                </div>

                                <div class="row">
                                    @foreach ($notes as $note)
                                        <div
                                            class="col-xxl-4 col-xl-6 col-lg-4 col-sm-6 single-note-item all-category note-important note-archive">
                                            <div class="card card-body mb-4 stretch stretch-full">
                                                <span class="side-stick"></span>
                                                <h5 class="note-title text-truncate w-75 mb-1"
                                                    data-noteheading="{{ $note->title }}">
                                                    {{ $note->title }}
                                                    <i class="point bi bi-circle-fill ms-1 fs-7"></i>
                                                </h5>
                                                <p class="fs-11 text-muted note-date">
                                                    {{ $note->created_at->format('d M Y') }}
                                                </p>
                                                <div class="note-content flex-grow-1">
                                                    <p class="text-muted note-inner-content text-truncate-3-line"
                                                        data-notecontent="{{ $note->description }}">
                                                        {{ $note->description }}
                                                    </p>
                                                </div>
                                                <div class="d-flex align-items-center gap-1">
                                                    <span class="avatar-text avatar-sm">
                                                        <i class="feather-star favourite-note"></i>
                                                    </span>
                                                    <span class="avatar-text avatar-sm">
                                                        <i class="feather-trash-2 remove-note"></i>
                                                    </span>
                                                    <div class="ms-auto">
                                                        <div class="dropdown btn-group category-selector">
                                                            <a class="nav-link dropdown-toggle category-dropdown label-group p-0"
                                                                data-bs-toggle="dropdown" href="#" role="button"
                                                                aria-haspopup="true" aria-expanded="true">
                                                                <div class="category">
                                                                    <div class="category-business"></div>
                                                                    <div class="category-social"></div>
                                                                    <div class="category-important"></div>
                                                                </div>
                                                            </a>
                                                            <div class="dropdown-menu dropdown-menu-right category-menu">
                                                                <a class="note-tasks badge-group-item badge-tasks dropdown-item position-relative category-tasks"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-danger rounded-circle me-3"></span>Tasks
                                                                </a>
                                                                <a class="note-works badge-group-item badge-works dropdown-item position-relative category-works"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-primary rounded-circle me-3"></span>Works
                                                                </a>
                                                                <a class="note-social badge-group-item badge-social dropdown-item position-relative category-social"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-info rounded-circle me-3"></span>Social
                                                                </a>
                                                                <a class="note-archive badge-group-item badge-archive dropdown-item position-relative category-archive"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-dark rounded-circle me-3"></span>Archive
                                                                </a>
                                                                <a class="note-priority badge-group-item badge-priority dropdown-item position-relative category-priority"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-danger rounded-circle me-3"></span>Priority
                                                                </a>
                                                                <a class="note-personal badge-group-item badge-personal dropdown-item position-relative category-personal"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-primary rounded-circle me-3"></span>Personal
                                                                </a>
                                                                <a class="note-business badge-group-item badge-business dropdown-item position-relative category-business"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-warning rounded-circle me-3"></span>Business
                                                                </a>
                                                                <a class="note-important badge-group-item badge-important dropdown-item position-relative category-important"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-success rounded-circle me-3"></span>Important
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>




                            </div>
                        </div>


                    </div>
                </div>
            </div> --}}


            <div class="content-sidebar content-sidebar-md lead-profile-sidebar" data-scrollbar-target="#psScrollbarInit">

                <div class="lead-profile-sidebar-head">
                    <div class="d-flex align-items-center gap-3">
                        <span class="lead-profile-sidebar-icon"><i class="feather-layout"></i></span>
                        <div class="min-w-0">
                            <div class="fw-bold text-dark">Lead Workspace</div>
                            <small class="text-muted">Profile navigation</small>
                        </div>
                    </div>
                </div>

                <div class="content-sidebar-body">
                    <ul class="nav flex-column nxl-content-sidebar-item customers-nav-tabs sidebar-style" id="myTab"
                        role="tablist">
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link active" id="overallTabLink" data-bs-toggle="tab"
                                data-bs-target="#overallTab" role="tab" aria-controls="overallTab" aria-selected="true">
                                <i class="feather-pie-chart"></i>
                                <span>Overview</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="activityTabLink" data-bs-toggle="tab"
                                data-bs-target="#activityTab" role="tab" aria-controls="activityTab"
                                aria-selected="false">
                                <i class="feather-activity"></i>
                                <span>Activities</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="productTabLink" data-bs-toggle="tab"
                                data-bs-target="#productTab" role="tab" aria-controls="productTab"
                                aria-selected="false">
                                <i class="feather-box"></i>
                                <span>Product</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="accountsDetailsTabLink" data-bs-toggle="tab"
                                data-bs-target="#accountsDetailsTab" role="tab" aria-controls="accountsDetailsTab"
                                aria-selected="false">
                                <i class="feather-user"></i>
                                <span>Accounts Details</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="ticketTabLink" data-bs-toggle="tab"
                                data-bs-target="#ticketTab" role="tab" aria-controls="ticketTab" aria-selected="false">
                                <i class="feather-tag"></i>
                                <span>Ticket</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="filesTabLink" data-bs-toggle="tab"
                                data-bs-target="#filesTab" role="tab" aria-controls="filesTab">
                                <i class="feather-file"></i>
                                <span>Files</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="campaignsTabLink" data-bs-toggle="tab"
                                data-bs-target="#campaignsTab" role="tab" aria-controls="campaignsTab"
                                aria-selected="false">
                                <i class="feather-mic"></i>
                                <span>Campaigns</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" id="surveyTabLink" data-bs-toggle="tab"
                                data-bs-target="#surveyTab" role="tab" aria-controls="surveyTab"
                                aria-selected="false">
                                <i class="feather-edit"></i>
                                <span>Survey</span>
                            </a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                data-bs-target="#projectsTab" role="tab"><i class="feather-folder"></i><span>Projects</span></a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                data-bs-target="#tradeDetailsTab" role="tab"><i class="feather-file-text"></i><span>Trade Details</span></a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                data-bs-target="#casesTab" role="tab"><i class="feather-briefcase"></i><span>Cases</span></a>
                        </li>
                        <li class="nav-item border-top" role="presentation">
                            <a href="javascript:void(0);" class="nav-link" data-bs-toggle="tab"
                                data-bs-target="#conversionTab" role="tab"><i class="feather-repeat"></i><span>Conversion</span></a>
                        </li>
                    </ul>




                </div>
            </div>

            <div class="col min-w-0">

                <div class="card border-top-0 lead-profile-card">
                    <div class="card stretch stretch-full border-0 mb-0">
                        @php
                            $stageName = \App\Models\LeadStage::find($lead->stage_id)?->name ?? 'New Lead';
                            $profileName = trim(($lead->first_name ?? '').' '.($lead->last_name ?? ''));
                            $profileLanguages = $lead->contactLanguages
                                ->map(fn ($contactLanguage) => $contactLanguage->language?->name)->filter()->join(', ');
                        @endphp
                        <div class="card-body lead-profile-hero">
                            <div class="d-flex flex-column flex-lg-row align-items-lg-start justify-content-between gap-4">
                                <div class="d-flex align-items-start gap-3 min-w-0">
                                    <span class="lead-profile-avatar">{{ strtoupper(substr($lead->topic ?: ($profileName ?: 'LD'), 0, 2)) }}</span>
                                    <div class="min-w-0">
                                        <div class="lead-profile-eyebrow mb-1">Lead #{{ str_pad((string) $lead->id, 4, '0', STR_PAD_LEFT) }} · Created {{ $lead->created_at?->format('d M Y') }}</div>
                                        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
                                            <h4 class="lead-profile-title mb-0 text-truncate">{{ $lead->topic ?: 'Untitled Lead' }}</h4>
                                            <span class="badge lead-current-stage-label {{ (int) $lead->stage_id === 6 ? 'bg-success text-white' : ((int) $lead->stage_id === 7 ? 'bg-danger text-white' : 'bg-soft-primary text-primary') }}"
                                                data-current-stage="{{ $lead->stage_id }}">
                                                {{ $stageName }}{{ $leadIsCompleted ? ' · Completed' : '' }}
                                            </span>
                                        </div>
                                        <div class="lead-profile-contact">
                                            {{ $profileName ?: 'No contact name' }}
                                            @if ($lead->job_title) · {{ $lead->job_title }} @endif
                                        </div>
                                        <div class="lead-profile-facts">
                                            <span class="lead-profile-fact"><i class="feather-mail"></i>{{ $lead->contactEmails->first()?->email ?: 'No email' }}</span>
                                            <span class="lead-profile-fact"><i class="feather-phone"></i>{{ $lead->contactPhones->first()?->phone ?: 'No phone' }}</span>
                                            <span class="lead-profile-fact"><i class="feather-briefcase"></i>{{ $lead->company?->name ?: 'No company' }}</span>
                                            <span class="lead-profile-fact"><i class="feather-globe"></i>{{ $profileLanguages ?: 'No languages' }}</span>
                                        </div>
                                        <div class="lead-profile-quick-stats">
                                            <span class="lead-profile-quick-stat"><small>Owner</small><strong>{{ $lead->assignedUser?->name ?: 'Not assigned' }}</strong></span>
                                            <span class="lead-profile-quick-stat"><small>Lead Score</small><strong>{{ (int) ($lead->lead_score ?? 0) }} / 100</strong></span>
                                            <span class="lead-profile-quick-stat"><small>Temperature</small><strong>{{ ucfirst($lead->temperature ?: 'cold') }}</strong></span>
                                        </div>
                                    </div>
                                </div>

                                <div class="lead-profile-status-panel">
                                    <label class="form-label mb-2">Lead Status</label>
                                    @if ($leadIsCompleted)
                                        <div class="lead-status-locked">
                                            <span class="badge {{ (int) $lead->stage_id === 6 ? 'bg-soft-success text-success' : 'bg-soft-danger text-danger' }} px-3 py-2">
                                                <i class="feather-lock me-1"></i>
                                                {{ (int) $lead->stage_id === 6 ? 'Qualified' : 'Unqualified' }} · Completed
                                            </span>
                                            <small class="text-muted d-block mt-2">Status is locked until this Lead is reopened.</small>
                                        </div>
                                    @else
                                        <select class="form-control update-stage" data-id="{{ $lead->id }}"
                                            data-current-stage="{{ $lead->stage_id }}" data-select2-selector="status">
                                            @foreach ($stages as $stage)
                                                <option value="{{ $stage->id }}" data-bg="bg-success" @selected($lead->stage_id == $stage->id)>
                                                    {{ $stage->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        <small class="text-muted d-block mt-2"><i class="feather-info me-1"></i>Updates the lifecycle flow automatically.</small>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="tab-content">
                        <!-- Activity Tab Content -->
                        <div class="tab-pane fade show active p-4" id="overallTab" role="tabpanel"
                            aria-labelledby="overallTabLink">

                            @include('leads.partials.profile-overview')

                            {{-- Legacy flat overview retained temporarily for reference; replaced by the professional overview above.

                            <div class="pb-5">
                                <div class="arrow-steps clearfix">
                                    @foreach ($stages as $statusStage)
                                        <div class="step {{ $statusStage->id <= $lead->stage_id ? 'current' : '' }}"
                                            data-stage-id="{{ $statusStage->id }}">
                                            <span>{{ $statusStage->name }}</span>
                                        </div>
                                    @endforeach
                                </div>
                            </div>



                            <div class="pt-0 px-5 pb-5">
                                <div class="row">
                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-phone"></i>Phone</span>
                                            @if ($lead->contactPhones->isNotEmpty())
                                                <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                    {{ $lead->contactPhones->first()->phone }}
                                                </a>
                                            @endif
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-mail"></i>Email</span>
                                            @if ($lead->contactEmails->isNotEmpty())
                                                <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                    {{ $lead->contactEmails->first()->email }}
                                                </a>
                                            @endif
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-user"></i>Full Name:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->first_name }} {{ $lead->last_name }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-user"></i>Surname:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->first_name }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-briefcase"></i>Job:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->job_title }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-home"></i>Company:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\Company::find($lead->company_id)->name ?? 'No Company' }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-phone"></i>Mobile Number:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                @if ($lead->contactPhones->isNotEmpty())
                                                    {{ $lead->contactPhones->first()->phone }}
                                                @endif
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-mail"></i>Email Address:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                @if ($lead->contactEmails->isNotEmpty())
                                                    {{ $lead->contactEmails->first()->email }}
                                                @endif
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-map"></i>Address 1:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->address_1 }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-map-pin"></i>Address 2:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->address_2 }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-hash"></i>Zip Code:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->zip_code }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-map-pin"></i>Location:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\Country::find($lead->country_id)?->name ?? '' }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-map"></i>Province:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->province }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-map-pin"></i>City:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ $lead->city }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-calendar"></i>Joining Date:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \Carbon\Carbon::parse($lead->created_at)->format('d M, Y') }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-globe"></i>Country:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                {{ \App\Models\Country::find($lead->country_id)?->name ?? '' }}
                                            </a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-message-square"></i>Communication:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">Email, Phone</a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-2">
                                        <div class="d-flex align-items-center">
                                            <span class="text-muted fw-medium d-flex gap-3"><i
                                                    class="feather-book"></i>Languages:</span>
                                            <a href="javascript:void(0);" class="fw-bold ms-auto">
                                                @foreach ($lead->contactLanguages as $contactLanguage)
                                                    @php
                                                        $language = \App\Models\Language::find(
                                                            $contactLanguage->language_id,
                                                        );
                                                    @endphp
                                                    {{ $language ? $language->name : 'No Languages' }},
                                                @endforeach
                                            </a>
                                        </div>
                                    </div>
                                </div>


                            </div>

                            --}}
                        </div>
                        <!-- Activity Tab Content -->
                        <div class="tab-pane fade p-4" id="activityTab" role="tabpanel"
                            aria-labelledby="activityTabLink">
                            @include('leads.partials.profile-activities')

                            {{-- Legacy activity feed replaced by the professional activity workspace above.
                            <x-crm-related-workflows module="leads" :record="$lead" />
                            <a class="btn btn-sm btn-outline-primary mb-3" href="{{ route('related-activity.index', ['leads', $lead->id]) }}">Messages, Follow-ups & To-dos</a>
                            <!-- Content for Activity Tab -->
                            <div class="about-section mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-end">
                                    <a href="{{ route('schedule-activity-create') }}?id={{ $lead->id }}"
                                        class="btn btn-sm btn-light-brand">Create Activity</a>
                                </div>
                            </div>
                            @php
                                $futureActivities = $activities->filter(function ($activity) {
                                    $activityDate = $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                    return $activityDate &&
                                        \Carbon\Carbon::parse($activityDate)->isFuture() &&
                                        $activity->activity_type_id != 2;
                                });
                            @endphp

                            @if ($futureActivities->isNotEmpty())
                                <div class="profile-details mb-5">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0">Scheduled Activities:</h5>

                                        <div class="card-body custom-card-action">
                                            <ul class="list-unstyled mb-0 activity-feed-1">
                                                @foreach ($activities as $activity)
                                                    @php
                                                        $activityDate =
                                                            $activity->end_date ??
                                                            ($activity->due_date ?? $activity->close_by);
                                                    @endphp

                                                    @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isFuture() && $activity->activity_type_id != 2)
                                                        <li class="feed-item feed-item-primary">
                                                            <div class="d-flex gap-4 justify-content-between">
                                                                <div>
                                                                    <div class="mb-2 text-truncate-1-line">
                                                                        <a href="javascript:void(0)"
                                                                            class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                    </div>
                                                                    <p class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                        {{ $activity->description }}
                                                                    </p>

                                                                    <div>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-success border border-dashed border-gray-500">
                                                                            Start-
                                                                            {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                        </a>

                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-danger border border-dashed border-gray-500">
                                                                            End-
                                                                            {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                        </a>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                            {{ $activity->duration }}</a>
                                                                    </div>
                                                                </div>
                                                                <div
                                                                    class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                    {{ $activity->created_at->diffForHumans() }}
                                                                </div>
                                                            </div>
                                                        </li>
                                                    @endif
                                                @endforeach
                                            </ul>


                                        </div>
                                    </div>
                                </div>
                                <hr class="my-0">

                            @endif
                            @php
                                $futureActivities = $activities->filter(function ($activity) {
                                    $activityDate = $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                    return $activityDate &&
                                        \Carbon\Carbon::parse($activityDate)->isPast() &&
                                        $activity->activity_type_id != 2;
                                });
                            @endphp

                            @if ($futureActivities->isNotEmpty())

                                <div class="profile-details mb-5">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0">Expired Activities:</h5>

                                        <div class="card-body custom-card-action">
                                            <ul class="list-unstyled mb-0 activity-feed-1">
                                                @foreach ($activities as $activity)
                                                    @php
                                                        $activityDate =
                                                            $activity->end_date ??
                                                            ($activity->due_date ?? $activity->close_by);
                                                    @endphp

                                                    @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isPast())
                                                        <li class="feed-item feed-item-primary">
                                                            <div class="d-flex gap-4 justify-content-between">
                                                                <div>
                                                                    <div class="mb-2 text-truncate-1-line">
                                                                        <a href="javascript:void(0)"
                                                                            class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                    </div>
                                                                    <p class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                        {{ $activity->description }}
                                                                    </p>
                                                                    <div>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-success border border-dashed border-gray-500">
                                                                            Start-
                                                                            {{ $activity->start_date ?? ($activity->due_date ?? $activity->received_on) }}
                                                                        </a>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-danger border border-dashed border-gray-500">
                                                                            End-
                                                                            {{ $activity->end_date ?? ($activity->due_date ?? $activity->close_by) }}
                                                                        </a>
                                                                    </div>
                                                                </div>
                                                                <div
                                                                    class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                    {{ $activity->created_at->diffForHumans() }}
                                                                </div>
                                                            </div>
                                                        </li>
                                                    @endif
                                                @endforeach
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            @endif
                            --}}
                        </div>

                        <!-- Note Tab Content -->
                        <div class="tab-pane fade p-4" id="noteTab" role="tabpanel" aria-labelledby="noteTabLink">


                            <form action="{{ route('notes.store') }}" method="post">
                                @csrf

                                <input type="hidden" name="contact_id" value="{{ request('id') }}">
                                <div class="mb-3">
                                    <label for="noteTitle" class="form-label">Note Title</label>
                                    <input type="text" class="form-control" id="noteTitle" name="noteTitle"
                                        placeholder="Enter note title" required>
                                </div>
                                <div class="mb-3">
                                    <label for="noteDescription" class="form-label">Note Description</label>
                                    <textarea class="form-control" id="noteDescription" name="noteDescription" rows="4"
                                        placeholder="Enter note description" required></textarea>
                                </div>
                                <div class="d-flex justify-content-end">
                                    <button type="submit" class="btn btn-primary">Add Note</button>
                                </div>
                            </form>


                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-between">
                                    <h5 class="fw-bold mb-0">Notes:</h5>
                                </div>

                                <div class="row">
                                    @foreach ($notes as $note)
                                        <div
                                            class="col-xxl-4 col-xl-6 col-lg-4 col-sm-6 single-note-item all-category note-important note-archive">
                                            <div class="card card-body mb-4 stretch stretch-full">
                                                <span class="side-stick"></span>
                                                <h5 class="note-title text-truncate w-75 mb-1"
                                                    data-noteheading="{{ $note->title }}">
                                                    {{ $note->title }}
                                                    <i class="point bi bi-circle-fill ms-1 fs-7"></i>
                                                </h5>
                                                <p class="fs-11 text-muted note-date">
                                                    {{ $note->created_at->format('d M Y') }}
                                                </p>
                                                <div class="note-content flex-grow-1">
                                                    <p class="text-muted note-inner-content text-truncate-3-line"
                                                        data-notecontent="{{ $note->description }}">
                                                        {{ $note->description }}
                                                    </p>
                                                </div>
                                                <div class="d-flex align-items-center gap-1">
                                                    <span class="avatar-text avatar-sm">
                                                        <i class="feather-star favourite-note"></i>
                                                    </span>
                                                    <span class="avatar-text avatar-sm">
                                                        <i class="feather-trash-2 remove-note"></i>
                                                    </span>
                                                    <div class="ms-auto">
                                                        <div class="dropdown btn-group category-selector">
                                                            <a class="nav-link dropdown-toggle category-dropdown label-group p-0"
                                                                data-bs-toggle="dropdown" href="#" role="button"
                                                                aria-haspopup="true" aria-expanded="true">
                                                                <div class="category">
                                                                    <div class="category-business"></div>
                                                                    <div class="category-social"></div>
                                                                    <div class="category-important"></div>
                                                                </div>
                                                            </a>
                                                            <div class="dropdown-menu dropdown-menu-right category-menu">
                                                                <a class="note-tasks badge-group-item badge-tasks dropdown-item position-relative category-tasks"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-danger rounded-circle me-3"></span>Tasks
                                                                </a>
                                                                <a class="note-works badge-group-item badge-works dropdown-item position-relative category-works"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-primary rounded-circle me-3"></span>Works
                                                                </a>
                                                                <a class="note-social badge-group-item badge-social dropdown-item position-relative category-social"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-info rounded-circle me-3"></span>Social
                                                                </a>
                                                                <a class="note-archive badge-group-item badge-archive dropdown-item position-relative category-archive"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-dark rounded-circle me-3"></span>Archive
                                                                </a>
                                                                <a class="note-priority badge-group-item badge-priority dropdown-item position-relative category-priority"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-danger rounded-circle me-3"></span>Priority
                                                                </a>
                                                                <a class="note-personal badge-group-item badge-personal dropdown-item position-relative category-personal"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-primary rounded-circle me-3"></span>Personal
                                                                </a>
                                                                <a class="note-business badge-group-item badge-business dropdown-item position-relative category-business"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-warning rounded-circle me-3"></span>Business
                                                                </a>
                                                                <a class="note-important badge-group-item badge-important dropdown-item position-relative category-important"
                                                                    href="javascript:void(0);"><span
                                                                        class="wd-5 ht-5 bg-success rounded-circle me-3"></span>Important
                                                                </a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>




                            </div>
                        </div>

                        <!-- Meeting Tab Content -->
                        <div class="tab-pane fade p-4" id="meetingTab" role="tabpanel" aria-labelledby="meetingTabLink">
                            <!-- Content for Meeting Tab -->
                            <div class="about-section mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-end">
                                    <a href="{{ route('schedule-activity-create') }}?id={{ $lead->id }}"
                                        class="btn btn-sm btn-light-brand">Create Meeting</a>
                                </div>
                            </div>
                            @php
                                $futureMeetings = $activities->filter(function ($activity) {
                                    $activityDate = $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                    return $activityDate &&
                                        \Carbon\Carbon::parse($activityDate)->isFuture() &&
                                        $activity->activity_type_id == 2;
                                });
                            @endphp

                            @if ($futureMeetings->isNotEmpty())
                                <div class="profile-details mb-5">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0">Scheduled Meetings:</h5>

                                        <div class="card-body custom-card-action">
                                            <ul class="list-unstyled mb-0 activity-feed-1">
                                                @foreach ($activities as $activity)
                                                    @php
                                                        $activityDate =
                                                            $activity->end_date ??
                                                            ($activity->due_date ?? $activity->close_by);
                                                    @endphp

                                                    @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isFuture() && $activity->activity_type_id == 2)
                                                        <li class="feed-item feed-item-primary">
                                                            <div class="d-flex gap-4 justify-content-between">
                                                                <div>
                                                                    <div class="mb-2 text-truncate-1-line">
                                                                        <a href="javascript:void(0)"
                                                                            class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                    </div>
                                                                    <p class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                        {{ $activity->description }}
                                                                    </p>

                                                                    <div>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-success border border-dashed border-gray-500">
                                                                            Start-
                                                                            {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                        </a>

                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-danger border border-dashed border-gray-500">
                                                                            End-
                                                                            {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                        </a>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                            {{ $activity->duration }}</a>
                                                                    </div>
                                                                </div>
                                                                <div
                                                                    class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                    {{ $activity->created_at->diffForHumans() }}
                                                                </div>
                                                            </div>
                                                        </li>
                                                    @endif
                                                @endforeach
                                            </ul>


                                        </div>
                                    </div>

                                </div>
                            @endif

                            @php
                                $futureMeetings = $activities->filter(function ($activity) {
                                    $activityDate = $activity->end_date ?? ($activity->due_date ?? $activity->close_by);
                                    return $activityDate &&
                                        \Carbon\Carbon::parse($activityDate)->isPast() &&
                                        $activity->activity_type_id == 2;
                                });
                            @endphp

                            @if ($futureMeetings->isNotEmpty())
                                <div class="profile-details mb-5">
                                    <div class="mb-4 d-flex align-items-center justify-content-between">
                                        <h5 class="fw-bold mb-0">Expired Meetings:</h5>

                                        <div class="card-body custom-card-action">
                                            <ul class="list-unstyled mb-0 activity-feed-1">
                                                @foreach ($activities as $activity)
                                                    @php
                                                        $activityDate =
                                                            $activity->end_date ??
                                                            ($activity->due_date ?? $activity->close_by);
                                                    @endphp

                                                    @if ($activityDate && \Carbon\Carbon::parse($activityDate)->isPast() && $activity->activity_type_id == 2)
                                                        <li class="feed-item feed-item-primary">
                                                            <div class="d-flex gap-4 justify-content-between">
                                                                <div>
                                                                    <div class="mb-2 text-truncate-1-line">
                                                                        <a href="javascript:void(0)"
                                                                            class="fw-semibold text-dark">{{ $activity->title }}</a>
                                                                    </div>
                                                                    <p class="fs-12 text-muted mb-3 text-truncate-2-line">
                                                                        {{ $activity->description }}
                                                                    </p>

                                                                    <div>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-success border border-dashed border-gray-500">
                                                                            Start-
                                                                            {{ \Carbon\Carbon::parse($activity->start_date ?? ($activity->due_date ?? $activity->received_on))->format('Y-m-d') }}
                                                                        </a>

                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-danger border border-dashed border-gray-500">
                                                                            End-
                                                                            {{ \Carbon\Carbon::parse($activity->end_date ?? ($activity->due_date ?? $activity->close_by))->format('Y-m-d') }}
                                                                        </a>
                                                                        <a href="javascript:void(0)"
                                                                            class="badge text-warning border border-dashed border-gray-500">Duration-
                                                                            {{ $activity->duration }}</a>
                                                                    </div>
                                                                </div>
                                                                <div
                                                                    class="fs-10 fw-medium text-uppercase text-muted text-nowrap">
                                                                    {{ $activity->created_at->diffForHumans() }}
                                                                </div>
                                                            </div>
                                                        </li>
                                                    @endif
                                                @endforeach
                                            </ul>


                                        </div>
                                    </div>

                                </div>
                            @endif

                        </div>

                        <!-- Email Tab Content -->
                        <div class="tab-pane fade p-4" id="emailTab" role="tabpanel" aria-labelledby="emailTabLink">
                            <!-- Content for Email Tab -->
                            <div class="about-section mb-5">


                                <div class="modal-content">
                                    <!--! BEGIN: [modal-header] !-->
                                    <div class="modal-header">
                                        <h2 class="d-flex flex-column mb-0">
                                            <span class="fs-18 fw-bold mb-1">Compose Mail</span>

                                        </h2>

                                    </div>
                                    <!--! BEGIN: [modal-body] !-->
                                    <div class="modal-body p-0">
                                        <div class="position-relative border-bottom">
                                            <div class="px-2 d-flex align-items-center">
                                                <div class="p-0 w-100">
                                                    <input class="form-control border-0 text-dark" name="tomailmodal"
                                                        placeholder="TO">
                                                </div>
                                            </div>
                                            <a href="javascript:void(0)"
                                                class="position-absolute top-50 end-0 translate-middle badge bg-gray-100 border border-gray-3 fs-10 fw-semibold text-uppercase text-dark rounded-pill c-pointer z-index-100"
                                                id="ccbccToggleModal"><span data-bs-toggle="tooltip"
                                                    data-bs-trigger="hover" title="CC / BCC"
                                                    style="font-size: 9px !important">CC / BCC</span></a>
                                        </div>
                                        <div class="border-bottom mail-cc-bcc-fields" id="ccbccToggleModalFileds"
                                            style="display: none">
                                            <div class="px-2 w-100 d-flex align-items-center border-bottom">
                                                <input class="form-control border-0 text-dark" name="ccmailmodal"
                                                    placeholder="CC">
                                            </div>
                                            <div class="px-2 w-100 d-flex align-items-center">
                                                <input class="form-control border-0 text-dark" name="bccmailmodal"
                                                    placeholder="BCC">
                                            </div>
                                        </div>
                                        <div class="px-3 w-100 d-flex align-items-center">
                                            <input class="form-control border-0 my-1 w-100 shadow-none" type="email"
                                                placeholder="Subject">
                                        </div>
                                        <div class="px-3">
                                            <textarea class="form-control border-0 text-dark" rows="8" placeholder="Write here..."></textarea>
                                        </div>
                                    </div>
                                    <!--! BEGIN: [modal-footer] !-->
                                    <div class="modal-footer d-flex align-items-center justify-content-between">
                                        <!--! BEGIN: [mail-editor-action-left] !-->
                                        <div class="d-flex align-items-center">
                                            <div class="dropdown me-2">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-primary dropdown-toggle" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Send Message"> Send </span>
                                                </a>
                                                <div class="dropdown-menu">
                                                    <a href="javascript:void(0)" class="dropdown-item"
                                                        data-action-target="#mailActionMessage">
                                                        <i class="feather-send me-3"></i>
                                                        <span>Instant Send</span>
                                                    </a>
                                                    <a href="javascript:void(0);"
                                                        class="dropdown-item successAlertMessage">
                                                        <i class="feather-clock me-3"></i>
                                                        <span>Schedule Send</span>
                                                    </a>
                                                    <div class="dropdown-divider"></div>
                                                    <a href="javascript:void(0)"
                                                        class="dropdown-item successAlertMessage">
                                                        <i class="feather-x me-3"></i>
                                                        <span>Discard Now</span>
                                                    </a>
                                                    <a href="javascript:void(0)"
                                                        class="dropdown-item successAlertMessage">
                                                        <i class="feather-edit-3 me-3"></i>
                                                        <span>Save as Draft</span>
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="dropdown me-2 d-none d-sm-block">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Pick Template">
                                                        <i class="feather-hash"></i>
                                                    </span>
                                                </a>
                                                <div class="dropdown-menu wd-300">
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Welcome you message</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Your issues solved</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Thank you message</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Make a offer message</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Add the Unsubscribe option</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Thank your customer for joining</span>
                                                    </a>
                                                    <div class="dropdown-divider"></div>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-save me-3"></i>
                                                        <span>Save as Template</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-sun me-3"></i>
                                                        <span>Manage Template</span>
                                                    </a>
                                                </div>
                                            </div>
                                            <div class="dropdown">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Upload Attachments">
                                                        <i class="feather-upload"></i>
                                                    </span>
                                                </a>
                                                <div class="dropdown-menu">
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-image me-3"></i>
                                                        <span>Upload Images</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-video me-3"></i>
                                                        <span>Upload Videos</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-mic me-3"></i>
                                                        <span>Upload Musics</span>
                                                    </a>
                                                    <a href="javascript:void(0)" class="dropdown-item">
                                                        <i class="feather-file-text me-3"></i>
                                                        <span>Upload Documents</span>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                        <!--! BEGIN: [mail-editor-action-right] !-->
                                        <div class="d-flex align-items-center">
                                            <div class="dropdown me-2">
                                                <a href="javascript:void(0)" data-bs-toggle="dropdown"
                                                    data-bs-offset="0, 0">
                                                    <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                        data-bs-trigger="hover" title="Editing Actions">
                                                        <i class="feather-more-horizontal"></i>
                                                    </span>
                                                </a>
                                                <ul class="dropdown-menu">
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-type me-3"></i>
                                                            <span>Plain Text Mode</span>
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-check me-3"></i>
                                                            <span>Check Spelling</span>
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-compass me-3"></i>
                                                            <span>Smart Compose</span>
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a href="javascript:void(0)" class="dropdown-item">
                                                            <i class="feather-feather me-3"></i>
                                                            <span>Manage Signature</span>
                                                        </a>
                                                    </li>
                                                </ul>
                                            </div>
                                            <a href="javascript:void(0);" data-bs-dismiss="modal">
                                                <span class="btn btn-icon" data-bs-toggle="tooltip"
                                                    data-bs-trigger="hover" title="Delete Message">
                                                    <i class="feather-x"></i>
                                                </span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="profile-details mb-5">
                                <div class="mb-4 d-flex align-items-center justify-content-between">
                                    {{-- <h5 class="fw-bold mb-0">Scheduled Emails:</h5> --}}
                                </div>
                            </div>
                        </div>

                        @include('leads.partials.lifecycle-tabs')

                    </div>
                </div>
            </div>
        </div>

    </div>
    <!-- [ Main Content ] end -->
@endsection

@section('modals')
    @if ($leadIsCompleted && $canReopen)
    <div class="modal fade" id="reopenLeadModal" tabindex="-1" aria-labelledby="reopenLeadModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <form method="POST" action="{{ route('leads.reopen', $lead) }}">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="reopenLeadModalLabel">Reopen Lead</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p class="text-muted">This returns the Lead to <strong>Contacted</strong> and unlocks status changes and editing.</p>
                        <label for="reopenLeadReason" class="form-label">Reason <span class="text-danger">*</span></label>
                        <textarea class="form-control @error('reason') is-invalid @enderror" id="reopenLeadReason"
                            name="reason" rows="4" minlength="10" maxlength="2000" required>{{ old('reason') }}</textarea>
                        @error('reason')<div class="invalid-feedback">{{ $message }}</div>@enderror
                    </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"><i class="feather-rotate-ccw me-1"></i>Reopen Lead</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    @endif

    <!-- Closed WON Modal -->
    <div class="modal fade" id="closedWonModal" tabindex="-1" aria-labelledby="closedWonModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="{{ route('won-lost.storeOrUpdate') }}" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="closedWonModalLabel">Closed WON</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Hidden ID field for update -->
                        <input type="hidden" name="lead_id" value="{{ $lead->id }}">

                        <input type="hidden" name="id" value="{{ $won->first()->id ?? old('id') }}">
                        <input type="hidden" name="status" value="WON">

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="finalProposal" class="form-label">Final Proposal</label>
                                <select class="form-select" name="final_proposal" id="finalProposal">
                                    <option value="none"
                                        {{ ($won->first()->final_proposal ?? old('final_proposal')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="mark"
                                        {{ ($won->first()->final_proposal ?? old('final_proposal')) == 'mark' ? 'selected' : '' }}>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        {{ ($won->first()->final_proposal ?? old('final_proposal')) == 'completed' ? 'selected' : '' }}>
                                        Completed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="finalQuotation" class="form-label">Final Quotation</label>
                                <select class="form-select" name="final_quotation" id="finalQuotation">
                                    <option value="none"
                                        {{ ($won->first()->final_quotation ?? old('final_quotation')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="mark"
                                        {{ ($won->first()->final_quotation ?? old('final_quotation')) == 'mark' ? 'selected' : '' }}>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        {{ ($won->first()->final_quotation ?? old('final_quotation')) == 'completed' ? 'selected' : '' }}>
                                        Completed</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="finalInvoice" class="form-label">Final Invoice</label>
                                <select class="form-select" name="final_invoice" id="finalInvoice">
                                    <option value="none"
                                        {{ ($won->first()->final_invoice ?? old('final_invoice')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="mark"
                                        {{ ($won->first()->final_invoice ?? old('final_invoice')) == 'mark' ? 'selected' : '' }}>
                                        Mark
                                    </option>
                                    <option value="completed"
                                        {{ ($won->first()->final_invoice ?? old('final_invoice')) == 'completed' ? 'selected' : '' }}>
                                        Completed</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="closedDate" class="form-label">Closed Date</label>
                                <input type="date" class="form-control" name="closed_date" id="closedDate"
                                    value="{{ $won->first()->closed_date ?? old('closed_date') }}">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="deliveryDate" class="form-label">Delivery or Implementation Date</label>
                                <input type="date" class="form-control" name="delivery_date" id="deliveryDate"
                                    value="{{ $won->first()->delivery_date ?? old('delivery_date') }}">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="paymentStatus" class="form-label">Payment Status</label>
                                <select class="form-select" name="payment_status" id="paymentStatus">
                                    <option value="none"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'none' ? 'selected' : '' }}>
                                        None
                                    </option>
                                    <option value="not_paid"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'not_paid' ? 'selected' : '' }}>
                                        Not Paid</option>
                                    <option value="advance_paid"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'advance_paid' ? 'selected' : '' }}>
                                        Advance Paid
                                    </option>
                                    <option value="paid"
                                        {{ ($won->first()->payment_status ?? old('payment_status')) == 'paid' ? 'selected' : '' }}>
                                        Paid
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="paymentMethod" class="form-label">Payment Method <span class="text-danger">*</span></label>
                                <input class="form-control" name="payment_method" id="paymentMethod" maxlength="100" required
                                    value="{{ $won->first()->payment_method ?? old('payment_method') }}" placeholder="e.g. Bank transfer">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="sentFeedback" class="form-label">Customer Feedback Sent <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="sent_feedback" id="sentFeedback" rows="3" required>{{ $won->first()->sent_feedback ?? old('sent_feedback') }}</textarea>
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Closed LOST Modal -->
    <div class="modal fade" id="closedLostModal" tabindex="-1" aria-labelledby="closedLostModalLabel"
        aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form action="{{ route('won-lost.storeOrUpdate') }}" method="POST">
                    @csrf
                    <div class="modal-header">
                        <h5 class="modal-title" id="closedLostModalLabel">Closed LOST</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Hidden ID field for update -->
                        <input type="hidden" name="lead_id" value="{{ $lead->id }}">

                        <input type="hidden" name="id" value="{{ $lost->first()->id ?? old('id') }}">
                        <input type="hidden" name="status" value="LOST">

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="lostStage" class="form-label">Unqualified Reason</label>
                                <select class="form-select" name="lost_stage" id="lostStage">
                                    <option value="lost"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'lost' ? 'selected' : '' }}>
                                        Lost
                                    </option>
                                    <option value="not_qualified"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'not_qualified' ? 'selected' : '' }}>
                                        Not-Qualified</option>
                                    <option value="contacted_future"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'contacted_future' ? 'selected' : '' }}>
                                        Contacted in Future
                                    </option>
                                    <option value="competition"
                                        {{ ($lost->first()->lost_stage ?? old('lost_stage')) == 'competition' ? 'selected' : '' }}>
                                        Competition</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="lostDate" class="form-label">Lost Date</label>
                                <input type="date" class="form-control" name="lost_date" id="lostDate"
                                    value="{{ $lost->first()->lost_date ?? old('lost_date') }}">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="lostReason" class="form-label">Lost Reason</label>
                            <textarea class="form-control" name="lost_reason" id="lostReason" rows="3">{{ $lost->first()->lost_reason ?? old('lost_reason') }}</textarea>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary">Save</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

@endsection



@section('scripts')
    <script>
        // jQuery to handle submenu toggling
        $(document).ready(function() {
            $('.dropdown-submenu > a').on('click', function(e) {
                var $submenu = $(this).next('ul');
                if ($submenu.is(':visible')) {
                    $submenu.slideUp();
                } else {
                    $submenu.stop(true, true).slideDown();
                }
                e.stopPropagation();
                e.preventDefault(); // Prevent closing of the parent dropdown
            });
        });

        // Handle stage status change when a new option is selected from the dropdown
        document.querySelectorAll('.stage-status-select').forEach(select => {
            select.addEventListener('change', function() {
                const stageId = this.dataset.stageId;
                const leadId = this.dataset.leadId;
                const selectedStatus = this.value;

                let stageStatus = 1; // Default 'None'
                if (selectedStatus === 'Mark') {
                    stageStatus = 2; // Mark
                } else if (selectedStatus === 'Completed') {
                    stageStatus = 3; // Completed
                }

                // Send the AJAX request to update the stage_status
                fetch('{{ route('update.stage.status') }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        },
                        body: JSON.stringify({
                            lead_id: leadId,
                            stage_id: stageId,
                            stage_status: stageStatus,
                        }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Refresh the page after a successful update
                            location.reload();
                        } else {
                            alert('Failed to update Lead Status.');
                        }
                    });
            });
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            @if ($leadIsCompleted && $canReopen && (request('action') === 'reopen' || $errors->has('reason')))
                bootstrap.Modal.getOrCreateInstance(document.getElementById('reopenLeadModal')).show();
            @endif
            @if ($lead->stage_id == 7 && request('action') === 'close')
                bootstrap.Modal.getOrCreateInstance(document.getElementById('closedLostModal')).show();
            @endif

            console.log("Script is running!");

            $('.update-stage').select2();

            $('.update-stage').next('.select2').css({
                'width': 'auto',
                'min-width': '200px'
            });
            $('.update-stage').on('change', function() {
                const select = this;
                const leadId = $(select).data('id');
                const stageId = $(select).val();
                const previousStageId = select.dataset.currentStage;
                const unqualifiedReason = String(stageId) === '7'
                    ? window.prompt('Please enter the Unqualified reason:')
                    : null;
                if (String(stageId) === '7' && !unqualifiedReason) {
                    $(select).val(previousStageId).trigger('change.select2');
                    return;
                }

                console.log("Dropdown changed. Contact ID:", leadId);
                console.log("Selected Stage ID:", stageId);

                if (leadId && stageId) {
                    select.disabled = true;
                    fetch(`/leads/${leadId}/update-lead-stage`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                            },
                            body: JSON.stringify({
                                stage_id: stageId,
                                unqualified_reason: unqualifiedReason,
                            }),
                        })
                        .then(async response => {
                            const data = await response.json().catch(() => ({}));
                            if (!response.ok) {
                                const validationMessage = data.errors
                                    ? Object.values(data.errors).flat().join('\n')
                                    : null;
                                throw new Error(validationMessage || data.message || 'Failed to update Lead Status.');
                            }
                            return data;
                        })
                        .then(data => {
                            console.log("Response received:", data.message);

                            const savedStageId = Number(data.stage_id || stageId);

                            document.querySelectorAll('.arrow-steps .step[data-stage-id]').forEach(step => {
                                const stepId = Number(step.dataset.stageId);
                                const terminalStage = [6, 7].includes(savedStageId);
                                const selectedTerminal = terminalStage && stepId === savedStageId;
                                step.classList.toggle('current', terminalStage ? stepId <= 5 || selectedTerminal : stepId <= savedStageId);
                                step.classList.toggle('done', terminalStage && (stepId <= 5 || selectedTerminal));
                                step.classList.toggle('qualified-completed', savedStageId === 6 && stepId === 6);
                                step.classList.toggle('unqualified-completed', savedStageId === 7 && stepId === 7);
                                step.classList.toggle('terminal-alternative', terminalStage && [6, 7].includes(stepId) && !selectedTerminal);
                            });

                            document.querySelectorAll('.lead-current-stage-label').forEach(label => {
                                const stageLabel = data.stage_name || select.options[select.selectedIndex]?.text || '';
                                label.textContent = data.completed ? `${stageLabel} · Completed` : stageLabel;
                                label.dataset.currentStage = String(savedStageId);
                            });

                            select.dataset.currentStage = String(savedStageId);
                            select.disabled = false;
                            $(select).val(String(savedStageId)).trigger('change.select2');

                            if (data.conversion_url) {
                                window.location.href = data.conversion_url;
                            } else if (data.action === 'close') {
                                window.location.reload();
                            } else {
                                // Reload from the saved database value so all Lead profile controls stay in sync.
                                window.location.reload();
                            }
                        })
                        .catch(error => {
                            console.error("Error:", error);
                            $(select).val(previousStageId).trigger('change.select2');
                            select.disabled = false;
                            window.alert(error.message);
                        });
                } else {
                    console.warn("Contact ID or Stage ID is missing!");
                }
            });
        });
    </script>

@endsection
