@extends('layouts.app')

@section('title', 'Leads')

@section('content')
    @include('leads.partials.status-colors')
    <style>
        .lead-workspace { padding-top: 20px; }
        .lead-list-card { border: 1px solid #e7eaf0; border-radius: 14px; box-shadow: 0 8px 28px rgba(15, 23, 42, .055); overflow: hidden; }
        .lead-list-card .crm-list-filter-toolbar { padding: 18px 20px !important; background: linear-gradient(180deg, #fff 0%, #fbfcfe 100%); }
        #leadServerList { margin-bottom: 0; }
        #leadServerList thead th { padding: 13px 14px; border-bottom: 1px solid #e8ebf0; background: #f7f9fc; color: #64748b; font-size: 11px; font-weight: 700; letter-spacing: .055em; text-transform: uppercase; }
        #leadServerList tbody td { padding: 15px 14px; border-color: #eef1f5; color: #334155; }
        #leadServerList tbody tr { transition: background-color .16s ease, box-shadow .16s ease; }
        #leadServerList tbody tr:hover { background: #fafcff; box-shadow: inset 3px 0 0 #3454d1; }
        .lead-topic-avatar, .lead-owner-avatar { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; border-radius: 10px; font-weight: 700; }
        .lead-topic-avatar { width: 38px; height: 38px; background: #eef2ff; color: #3454d1; font-size: 13px; }
        .lead-owner-avatar { width: 32px; height: 32px; border-radius: 50%; background: #ecfdf5; color: #16845b; font-size: 11px; }
        .lead-primary-link { color: #172033 !important; font-weight: 650; line-height: 1.3; }
        .lead-primary-link:hover { color: #3454d1 !important; }
        .lead-meta { color: #94a3b8; font-size: 11px; }
        .lead-contact-list { padding: 0; margin: 0; }
        .lead-contact-list li { list-style: none; margin-bottom: 3px; }
        .lead-contact-link { color: #475569; }
        .lead-contact-link:hover { color: #3454d1; }
        .lead-activity-card { width: 230px; padding: 10px 12px; border: 1px solid #e9edf3; border-radius: 10px; background: #fbfcfe; }
        .lead-activity-card .progress { background: #e8edf5; }
        .lead-activity-metrics { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
        .lead-activity-metric { color: #64748b; font-size: 10px; }
        .lead-activity-metric strong { display: block; margin-top: 1px; color: #334155; font-size: 12px; }
        .lead-row-actions .avatar-text { border: 1px solid #e5e9f0; border-radius: 9px; background: #fff; color: #64748b; box-shadow: none; transition: all .15s ease; }
        .lead-row-actions .avatar-text:hover { border-color: #c8d2f0; background: #f2f5ff; color: #3454d1; transform: translateY(-1px); }
        .lead-assign-button { display: inline-flex !important; align-items: center; justify-content: center; }
        .lead-status-locked { padding: 10px; border: 1px solid #e9edf3; border-radius: 10px; background: #fbfcfe; }
        .lead-empty-state { padding: 60px 24px !important; text-align: center; }
        .lead-empty-state-icon { display: inline-flex; width: 52px; height: 52px; align-items: center; justify-content: center; margin-bottom: 12px; border-radius: 14px; background: #eef2ff; color: #3454d1; font-size: 22px; }
        @media (max-width: 767.98px) {
            .lead-workspace { padding-top: 12px; }
            .lead-list-card { border-radius: 10px; }
        }
    </style>
    <!-- [ page-header ] start -->
    <div class="page-header">
        <div class="page-header-left d-flex align-items-center">
            <div class="page-header-title">
                <h5 class="mb-1">Leads</h5>
                <small class="text-muted d-none d-lg-block">Manage prospects, engagement and pipeline progress</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">
                    <a href="javascript:void(0);" class="btn btn-icon btn-light-brand" data-bs-toggle="collapse"
                        data-bs-target="#collapseOne" title="Lead insights" aria-label="Lead insights">
                        <i class="feather-bar-chart"></i>
                    </a>
                    <div class="dropdown">
                        <a class="btn btn-icon btn-light-brand" data-bs-toggle="dropdown" data-bs-offset="0, 10"
                            data-bs-auto-close="outside" title="Change view" aria-label="Change view">
                            <i class="feather-eye"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a href="{{ route('leads') }}" class="dropdown-item active">
                                <i class="feather-list me-3"></i>
                                <span>Table View</span>
                            </a>
                            <a href="{{ route('leads-dashboard') }}" class="dropdown-item">
                                <i class="feather-grid me-3"></i>
                                <span>Dashboard View</span>
                            </a>
                        </div>

                    </div>
                    <div class="dropdown">
                        <a class="btn btn-icon btn-light-brand" data-bs-toggle="dropdown" data-bs-offset="0, 10"
                            data-bs-auto-close="outside" title="Export Leads" aria-label="Export Leads">
                            <i class="feather-paperclip"></i>
                        </a>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a href="{{ route('leads.export', ['format' => 'pdf'] + request()->query()) }}" class="dropdown-item">
                                <i class="bi bi-filetype-pdf me-3"></i>
                                <span>PDF</span>
                            </a>
                            <a href="{{ route('leads.export', ['format' => 'csv'] + request()->query()) }}" class="dropdown-item">
                                <i class="bi bi-filetype-csv me-3"></i>
                                <span>CSV</span>
                            </a>
                            <a href="{{ route('leads.export', ['format' => 'xml'] + request()->query()) }}" class="dropdown-item">
                                <i class="bi bi-filetype-xml me-3"></i>
                                <span>XML</span>
                            </a>
                            <a href="{{ route('leads.export', ['format' => 'txt'] + request()->query()) }}" class="dropdown-item">
                                <i class="bi bi-filetype-txt me-3"></i>
                                <span>Text</span>
                            </a>
                            <a href="{{ route('leads.export', ['format' => 'xlsx'] + request()->query()) }}" class="dropdown-item">
                                <i class="bi bi-filetype-exe me-3"></i>
                                <span>Excel</span>
                            </a>
                            <div class="dropdown-divider"></div>
                            <button type="button" class="dropdown-item" onclick="window.print()">
                                <i class="bi bi-printer me-3"></i>
                                <span>Print</span>
                            </button>
                        </div>
                    </div>
                    @if((int) auth()->user()->is_admin === 1 || auth()->user()->can('create_leads'))
                    <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>
    <div id="collapseOne" class="accordion-collapse collapse page-header-collapse">
        <div class="accordion-body pb-2">
            <div class="row">
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-users"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Today Leads</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $todayLeadsCount }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-success text-success">
                                    <i class="feather-arrow-up fs-10 me-1"></i>
                                    <span>36.85%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-user-check"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Month Leads</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $monthLeadsCount }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-danger text-danger">
                                    <i class="feather-arrow-down fs-10 me-1"></i>
                                    <span>24.56%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-user-plus"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Month Won</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $monthLeadWon }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-success text-success">
                                    <i class="feather-arrow-up fs-10 me-1"></i>
                                    <span>33.29%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-md-6">
                    <div class="card stretch stretch-full">
                        <div class="card-body">
                            <div class="d-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="avatar-text avatar-xl rounded">
                                        <i class="feather-user-minus"></i>
                                    </div>
                                    <a href="javascript:void(0);" class="fw-bold d-block">
                                        <span class="text-truncate-1-line">Month Lost</span>
                                        <span class="fs-24 fw-bolder d-block">{{ $monthLeadLost }}</span>
                                    </a>
                                </div>
                                <!-- <div class="badge bg-soft-danger text-danger">
                                    <i class="feather-arrow-down fs-10 me-1"></i>
                                    <span>42.47%</span>
                                </div> -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- [ page-header ] end -->
    <!-- [ Main Content ] start -->
    <div class="main-content lead-workspace">
        <div class="row">
            <div class="col-lg-12">
                <div class="card stretch stretch-full lead-list-card">
                    <div class="card-body p-0">
                        <x-server-list-toolbar form-id="lead-filter-form" title="Filter Leads"
                            description="Find and refine prospects across your pipeline"
                            :total="$leadPaginator->total()" total-label="Leads"
                            placeholder="Search by topic, contact, or job title" :filters="[
                            'status'=>['label'=>'Record status','options'=>['active'=>'Active','inactive'=>'Inactive','completed'=>'Completed']],
                            'stage_id'=>['label'=>'Lead status','options'=>$stages->pluck('name','id')->all()],
                            'priority_id'=>['label'=>'Priority','options'=>$priorities->pluck('name','id')->all()],
                            'date_from'=>['label'=>'Created from','type'=>'date'],'date_to'=>['label'=>'Created to','type'=>'date'],
                        ]" />
                        <div class="table-responsive crm-list-table-scroll">
                            <table class="table table-hover crm-list-table" id="leadServerList">
                                <thead>
                                    <tr>
                                        <th class="wd-30">
                                            <div class="btn-group mb-1">
                                                <div class="custom-control custom-checkbox ms-1">
                                                    <input type="checkbox" class="custom-control-input"
                                                        id="checkAllCustomer">
                                                    <label class="custom-control-label" for="checkAllCustomer"></label>
                                                </div>
                                            </div>
                                        </th>
                                        <th>Topic</th>
                                        <th>Name</th>
                                        <th class="text-center">Phone No</th>
                                        <th>Email</th>
                                        <th>Country</th>
                                        <th>Activity Timeline</th>
                                        <th>Assigned Employee</th>
                                        <th class="lead-status-column">Lead Status</th>
                                        <th class="text-end crm-list-actions-column">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($leads as $lead)
                                        @php
                                            $leadIsCompleted = in_array((int) $lead->stage_id, [6, 7], true) || $lead->status === 'completed';
                                            $canReopenLead = (bool) auth()->user()->is_admin
                                                || (int) $lead->assignedUser?->reporting_manager_id === (int) auth()->id()
                                                || auth()->user()->can('reopen_completed_leads');
                                        @endphp
                                        <tr class="single-item">
                                            <td>
                                                <div class="item-checkbox ms-1">
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" class="custom-control-input checkbox"
                                                            id="checkBox_{{ $lead->id }}">
                                                        <label class="custom-control-label"
                                                            for="checkBox_{{ $lead->id }}"></label>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center gap-3" style="min-width: 210px;">
                                                    <span class="lead-topic-avatar">
                                                        {{ strtoupper(substr($lead->topic ?: ($lead->first_name ?: 'L'), 0, 2)) }}
                                                    </span>
                                                    <div class="min-w-0">
                                                        <a href="{{ route('leads.view') }}?id={{ $lead->id }}"
                                                            class="lead-primary-link d-block text-truncate">
                                                            {{ $lead->topic ?: 'Untitled Lead' }}
                                                        </a>
                                                        <span class="lead-meta">Lead #{{ str_pad((string) $lead->id, 4, '0', STR_PAD_LEFT) }}</span>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="fw-semibold text-dark">{{ trim(($lead->first_name ?? '').' '.($lead->last_name ?? '')) ?: 'No contact name' }}</div>
                                                <small class="text-muted">{{ $lead->job_title ?: ($lead->company?->name ?: 'Prospect') }}</small>
                                            </td>
                                            <td>
                                                <ul class="lead-contact-list">
                                                    @foreach ($lead->contactPhones as $phone)
                                                        <li><a class="lead-contact-link" href="tel:{{ $phone->phone }}"><i
                                                                    class="feather-phone fs-12 me-2 text-success"></i>{{ $phone->phone }}</a>
                                                        </li>
                                                    @endforeach
                                                    @if ($lead->contactPhones->isEmpty())
                                                        <li class="text-muted">—</li>
                                                    @endif
                                                </ul>
                                            </td>
                                            <td><a class="lead-contact-link"
                                                    href="mailto:{{ $lead->contactEmails->first()->email ?? '' }}">
                                                    <i class="feather-mail fs-12 me-2 text-primary"></i>{{ $lead->contactEmails->first()->email ?? 'No email' }}</a>
                                            </td>
                                            {{-- <td>
                                                <div class="d-flex flex-wrap">
                                                    @foreach ($lead->contactLanguages as $contactLanguage)
                                                        @php
                                                            $language = \App\Models\Language::find(
                                                                $contactLanguage->language_id,
                                                            );
                                                        @endphp
                                                        <span class="me-2 mb-2">
                                                            <i class="bi bi-circle-fill text-success"
                                                                style="font-size: 5px; margin-right: 5px;"></i>
                                                            {{ $language ? $language->name : 'Unknown' }}
                                                        </span>
                                                    @endforeach
                                                </div>
                                            </td> --}}
                                            <td><i class="feather-map-pin fs-12 me-2 text-muted"></i>{{ $lead->country?->name ?? 'Not specified' }}</td>
                                            <td>
                                                @php
                                                    $leadStatusProgress = match ((int) $lead->stage_id) {
                                                        1 => 0,
                                                        2 => 20,
                                                        3 => 40,
                                                        4 => 60,
                                                        5 => 80,
                                                        6, 7 => 100,
                                                        default => 0,
                                                    };
                                                    $activityProgress = $lead->activities_count > 0
                                                        ? (int) round(($lead->completed_activities_count / $lead->activities_count) * 100)
                                                        : 0;
                                                    $timelineSummaryProgress = (int) round(($leadStatusProgress + $activityProgress) / 2);
                                                @endphp
                                                <div class="lead-activity-card">
                                                    <div class="d-flex align-items-start justify-content-between gap-2 mb-2">
                                                        <div class="min-w-0">
                                                            <div class="fw-semibold text-dark text-truncate">
                                                                {{ $lead->latestActivity?->title ?: 'No activity scheduled' }}
                                                            </div>
                                                            <small class="text-muted">
                                                                @if ($lead->latestActivity)
                                                                    {{ \Carbon\Carbon::parse(
                                                                        $lead->latestActivity->start_date
                                                                        ?? $lead->latestActivity->due_date
                                                                        ?? $lead->latestActivity->received_on
                                                                        ?? $lead->latestActivity->created_at
                                                                    )->format('M d, Y · H:i') }}
                                                                @else
                                                                    Add the first follow-up
                                                                @endif
                                                            </small>
                                                        </div>
                                                        <span class="badge bg-soft-primary text-primary">{{ $lead->activities_count }} total</span>
                                                    </div>
                                                    <div class="d-flex justify-content-between small mb-1">
                                                        <span class="fw-semibold">Summary</span>
                                                        <strong class="text-primary">{{ $timelineSummaryProgress }}%</strong>
                                                    </div>
                                                    <div class="progress ht-6" role="progressbar" aria-label="Activity timeline summary progress"
                                                        aria-valuenow="{{ $timelineSummaryProgress }}" aria-valuemin="0" aria-valuemax="100">
                                                        <div class="progress-bar bg-primary" style="width: {{ $timelineSummaryProgress }}%"></div>
                                                    </div>
                                                    <div class="lead-activity-metrics">
                                                        <div class="lead-activity-metric">Lead Status<strong>{{ $leadStatusProgress }}%</strong></div>
                                                        <div class="lead-activity-metric">Activities<strong>{{ $activityProgress }}%</strong></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center gap-2" style="min-width: 180px;">
                                                    <span class="lead-owner-avatar">{{ strtoupper(substr($lead->assignedUser?->name ?: 'NA', 0, 2)) }}</span>
                                                    <div class="min-w-0">
                                                        <div class="fw-semibold text-dark text-truncate">{{ $lead->assignedUser?->name ?? 'Not Assigned' }}</div>
                                                        <small class="text-muted text-truncate d-block">{{ $lead->assignedUser?->email ?: 'No owner selected' }}</small>
                                                    </div>
                                                </div>
                                            </td>

                                            <td class="lead-status-column">
                                                @if ($leadIsCompleted)
                                                    <div class="lead-status-locked" data-lead-id="{{ $lead->id }}">
                                                        <span class="badge {{ (int) $lead->stage_id === 6 ? 'bg-soft-success text-success' : 'bg-soft-danger text-danger' }} lead-completed-badge px-3 py-2">
                                                            <i class="feather-check-circle me-1"></i>
                                                            {{ (int) $lead->stage_id === 6 ? 'Qualified' : 'Unqualified' }} · Completed
                                                        </span>
                                                        <small class="text-muted d-block mt-1">Status is locked until this Lead is reopened.</small>
                                                        <div class="d-flex flex-wrap gap-2 mt-2">
                                                            @can('create_deals')
                                                                @if ((int) $lead->stage_id === 6 && !$lead->moved_at)
                                                                    <a href="{{ route('leads.conversion-review', $lead->id) }}"
                                                                        class="btn btn-sm btn-success">
                                                                        <i class="feather-arrow-right-circle me-1"></i>Move to Deal
                                                                    </a>
                                                                @endif
                                                            @endcan
                                                            @if ($canReopenLead)
                                                                <a href="{{ route('leads.view', ['id' => $lead->id, 'action' => 'reopen']) }}"
                                                                    class="btn btn-sm btn-outline-primary">
                                                                    <i class="feather-rotate-ccw me-1"></i>Reopen Lead
                                                                </a>
                                                            @endif
                                                        </div>
                                                    </div>
                                                @else
                                                    <select class="form-control update-stage" data-id="{{ $lead->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>
                                                @endif
                                                @unless ($leadIsCompleted)
                                                <div class="mt-2 lead-completion-action">
                                                    @can('create_deals')
                                                        @if ((int) $lead->stage_id === 6 && !$lead->moved_at)
                                                            <a href="{{ route('leads.conversion-review', $lead->id) }}"
                                                                class="btn btn-sm btn-success">
                                                                <i class="feather-arrow-right-circle me-1"></i>Move to Deal
                                                            </a>
                                                        @elseif (!in_array((int) $lead->stage_id, [6, 7], true) && !$lead->moved_at)
                                                            <small class="text-muted d-block">Qualify this Lead to convert it.</small>
                                                        @endif
                                                    @endcan
                                                </div>
                                                @endunless
                                            </td>

                                            <td class="text-end crm-list-actions-column">
                                                <div class="d-inline-flex align-items-center justify-content-end gap-2 lead-row-actions">
                                                    @if (!$leadIsCompleted)
                                                    @can('create_activities')
                                                        <a href="{{ route('schedule-activity-create', ['leadId' => $lead->id]) }}"
                                                            class="avatar-text avatar-md"
                                                            title="Add Activity" aria-label="Add Activity">
                                                            <i class="feather feather-activity text-primary"></i>
                                                        </a>
                                                    @endcan
                                                    @endif
                                                    @if (!$leadIsCompleted && ((bool) auth()->user()->is_admin || auth()->user()->can('assign_leads')))
                                                        <button type="button"
                                                            class="avatar-text avatar-md border-0 lead-assign-button assign-lead-employee"
                                                            data-bs-toggle="modal" data-bs-target="#assignLeadEmployeeModal"
                                                            data-action="{{ route('leads.assign-employee', $lead) }}"
                                                            data-current-owner="{{ $lead->contact_owner_id }}"
                                                            data-lead-topic="{{ $lead->topic ?: 'Lead #'.$lead->id }}"
                                                            title="Assign Lead" aria-label="Assign Lead">
                                                            <i class="feather-user-plus text-info"></i>
                                                        </button>
                                                    @endif
                                                    @can('share_leads')
                                                        <x-internal-share-button compact :url="route('leads.view', ['id' => $lead->id])"
                                                            :title="'Lead: '.($lead->topic ?: trim($lead->first_name.' '.$lead->last_name))"
                                                            label="Share Lead" />
                                                    @endcan
                                                    <a href="{{ route('leads.view') }}?id={{ $lead->id }}"
                                                        class="avatar-text avatar-md"
                                                        title="View Lead" aria-label="View Lead">
                                                        <i class="feather feather-eye"></i>
                                                    </a>
                                                    @if (!$leadIsCompleted)
                                                    @can('update_leads')
                                                        <a href="{{ route('leads.edit') }}?id={{ $lead->id }}"
                                                            class="avatar-text avatar-md"
                                                            title="Edit Lead" aria-label="Edit Lead">
                                                            <i class="feather feather-edit-3"></i>
                                                        </a>
                                                    @endcan
                                                    @endif
                                                    @if (!$leadIsCompleted)
                                                    @can('create_deals')
                                                        @if ((int) $lead->stage_id === 6 && !$lead->moved_at)
                                                            <a href="{{ route('deals-create', ['leadId' => $lead->id]) }}"
                                                                class="avatar-text avatar-md"
                                                                title="Assign Deal" aria-label="Assign Deal">
                                                                <i class="feather feather-briefcase text-success"></i>
                                                            </a>
                                                        @endif
                                                    @endcan
                                                    @endif
                                                    @if (!$leadIsCompleted)
                                                    @can('delete_leads')
                                                        <form action="{{ route('leads.destroy', $lead->id) }}" method="POST"
                                                            class="d-inline-flex m-0"
                                                            onsubmit="return confirm('Are you sure you want to delete this lead?');">
                                                            @csrf
                                                            @method('DELETE')
                                                            <button type="submit"
                                                                class="avatar-text avatar-md border-0 bg-transparent text-danger p-0"
                                                                title="Delete Lead" aria-label="Delete Lead">
                                                                <i class="feather feather-trash-2"></i>
                                                            </button>
                                                        </form>
                                                    @endcan
                                                    @endif
                                                </div>
                                            </td>


                                        </tr>
                                    @endforeach
                                    @if ($leads->isEmpty())
                                        <tr>
                                            <td colspan="10" class="lead-empty-state">
                                                <span class="lead-empty-state-icon"><i class="feather-users"></i></span>
                                                <h6 class="fw-bold mb-1">No Leads found</h6>
                                                <p class="text-muted mb-3">Adjust the filters or create a new Lead to start building your pipeline.</p>
                                                @if((int) auth()->user()->is_admin === 1 || auth()->user()->can('create_leads'))
                                                    <a href="{{ route('leads-create') }}" class="btn btn-sm btn-primary">
                                                        <i class="feather-plus me-1"></i>Create Lead
                                                    </a>
                                                @endif
                                            </td>
                                        </tr>
                                    @endif
                                </tbody>
                            </table>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="px-4 pb-4">{{ $leadPaginator->links() }}</div>
    <!-- [ Main Content ] end -->
@endsection

@section('modals')
    <div class="modal fade" id="assignLeadEmployeeModal" tabindex="-1"
        aria-labelledby="assignLeadEmployeeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <form method="POST" id="assignLeadEmployeeForm" class="modal-content border-0">
                @csrf
                <div class="modal-header">
                    <div>
                        <h5 class="modal-title" id="assignLeadEmployeeModalLabel">Assign Lead to Employee</h5>
                        <small class="text-muted" id="assignLeadEmployeeTopic">Select a user to own this Lead.</small>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <label for="assignLeadEmployeeSelect" class="form-label fw-semibold">Assign To</label>
                    <select class="form-select" name="user_id" id="assignLeadEmployeeSelect" required>
                        <option value="">Select Employee</option>
                        @foreach ($assignmentUsers as $employee)
                            <option value="{{ $employee->id }}">
                                {{ $employee->name }}{{ $employee->email ? ' · '.$employee->email : '' }}
                            </option>
                        @endforeach
                    </select>
                    <div class="form-text mt-2">The selected employee becomes the Lead owner and receives an assignment notification.</div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="feather-user-check me-1"></i>Assign Lead
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="modal fade" id="addActivity" aria-labelledby="addActivityLabel" aria-hidden="true" x-data>
        <form id="createActivityForm" method="POST" action="/activity/store" class="p-3" enctype="multipart/form-data">
            @csrf
            <input type="hidden" name="activity_type_id" x-bind:value="$store.activity.selectedButton" />

            <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Activity</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">

                        <!-- Title Field -->
                        <div class="col-lg-16 mb-4">
                            <div class="input-group">
                                <div class="input-group-text"><i class="feather-tag"></i></div>
                                <input type="text" class="form-control" name="title" id="titleInput"
                                    placeholder="Title">
                            </div>
                        </div>


                        <!-- Title Field -->
                        <div class="col-lg-12 mb-4" x-show="([4, 2,].includes($store.activity.selectedButton))"
                            x-transition>
                            <div class="activity-date-time-row d-flex gap-2 align-items-center flex-wrap">
                                <!-- Start Date -->
                                <input type="date" class="form-control flex-grow-1" name="start_date"
                                    placeholder="Dec 9, 2024" />

                                <!-- Start Time -->
                                <input type="time" class="form-control flex-grow-1" name="start_time"
                                    placeholder="h:mm AM" />

                                <span class="align-self-center">-</span>

                                <!-- End Date -->
                                <input type="date" class="form-control flex-grow-1" name="end_date"
                                    placeholder="Dec 9, 2024" />

                                <!-- End Time -->
                                <input type="time" class="form-control flex-grow-1" name="end_time"
                                    placeholder="h:mm AM" />
                            </div>
                        </div>

                        @php
                            $selectedContactId = request('id');
                            $selectedDealId = request('dealId');
                        @endphp
                        <div class="row">
                            <div class="col-lg-6 mb-4">
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <select class="form-control" name="contact_id" id="contactInput">
                                        <option value="">Select
                                            Contact</option>
                                        @foreach ($contacts as $contact)
                                            <option value="{{ $contact->id }}">
                                                {{ $contact->first_name }}
                                            </option>
                                        @endforeach
                                    </select>

                                </div>
                            </div>

                            <!-- Hidden Inputs for lead_id and deal_id -->

                            <input type="hidden" name="lead_id" id="hiddenLeadId">


                            @if ($selectedDealId)
                                <input type="hidden" name="deal_id" value="{{ $selectedDealId }}">
                            @endif

                            <!-- Priority Dropdown -->
                            <div class="col-lg-6 mb-4" x-show="([1,3,4,9].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-award"></i></div>
                                    <select class="form-control" name="priority" id="priorityInput">
                                        <option value="" disabled selected>Priority</option>
                                        @foreach ($priorities as $priority)
                                            <option value="{{ $priority->id }}">{{ $priority->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>







                            {{-- <div class="col-lg-6 mb-4" x-show="([6].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-map-pin"></i></div>
                                    <select class="form-control" name="location" id="locationInput">
                                        <option value="" disabled selected>Select Location</option>
                                        @foreach ($countries as $country)
                                            <option value="{{ $country->id }}">{{ $country->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div> --}}

                            {{-- <div class="col-lg-6 mb-4" x-show="([6,10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-users"></i></div>
                                    <select class="form-control" name="customer" id="customerInput">
                                        <option value="" disabled selected>Select Customer</option>
                                        <option value="1">Customer 1</option>
                                        <option value="2">Customer 2</option>
                                        <option value="3">Customer 3</option>
                                        <option value="4">Customer 4</option>
                                    </select>
                                </div>
                            </div> --}}
                            {{-- <div class="col-lg-6 mb-4" x-show="([6].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-briefcase"></i></div>
                                    <input type="text" class="form-control" name="service" id="serviceInput"
                                        placeholder="Service" />
                                </div>
                            </div> --}}


                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <select class="form-control" name="meeting_integration" id="meetingIntegrationInput">
                                        <option value="" disabled selected>Select Meeting Integration
                                        </option>
                                        @foreach ($meetings as $meeting)
                                            <option value="{{ $meeting->id }}">{{ $meeting->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>



                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <select class="form-control" name="allDayEventStatus" id="allDayEventStatus">
                                        <option value="" disabled selected>All Day Event Status</option>
                                        @foreach ($eventStatuses as $status)
                                            <option value="{{ $status->name }}">{{ $status->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>


                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="callFrom" id="callFromInput"
                                        placeholder="Call From" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-phone"></i></div>
                                    <input type="text" class="form-control" name="phoneNumber" id="phoneNumberInput"
                                        placeholder="Phone Number" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([1, 3, 4].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-flag"></i></div>
                                    <input type="text" class="form-control" name="regarding" id="regardingInput"
                                        placeholder="Regarding" />
                                </div>
                            </div>


                            {{-- <div class="col-lg-16 mb-4" x-show="([7].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-map-pin"></i></div>
                                    <input type="text" class="form-control" name="address" id="addressInput"
                                        placeholder="Address" />
                                </div>
                            </div>
                            <div class="col-lg-6 mb-4" x-show="([8].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-printer"></i></div>
                                    <input type="text" class="form-control" name="fax" id="faxInput"
                                        placeholder="Fax" />
                                </div>
                            </div> --}}

                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-compass"></i></div>
                                    <input type="text" class="form-control" name="direction" id="directionInput"
                                        placeholder="Direction" />
                                </div>
                            </div>


                            <!-- From Email -->
                            <div class="col-lg-6 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="fromEmailInput" class="form-label">From Email</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-mail"></i></div>
                                    <x-activity-email-sender id="fromEmailInput" />
                                </div>
                            </div>

                            <!-- Email To -->
                            <div class="col-lg-6 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="emailToInput" class="form-label">Email To</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-send"></i></div>
                                    <input type="email" class="form-control" name="email_to" id="emailToInput"
                                        placeholder="Email To" />
                                </div>
                            </div>

                            <!-- Subject -->
                            <div class="col-lg-12 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="subjectInput" class="form-label">Subject</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-align-left"></i></div>
                                    <input type="text" class="form-control" name="subject" id="subjectInput"
                                        placeholder="Subject" />
                                </div>
                            </div>

                            <!-- Email Body -->
                            <div class="col-lg-12 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="emailBodyInput" class="form-label">Email Body</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                    <textarea class="form-control" name="email_body" id="emailBodyInput" rows="5" placeholder="Email Body"></textarea>
                                </div>
                            </div>

                            <!-- Attachment -->
                            <div class="col-lg-12 mb-4" x-show="([9].includes($store.activity.selectedButton))"
                                x-transition>
                                <label for="attachmentInput" class="form-label">Attachment</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-paperclip"></i></div>
                                    <input type="file" class="form-control" name="attachment" id="attachmentInput" />
                                </div>
                            </div>

                            <!-- Company Dropdown -->
                            {{-- <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-briefcase"></i></div>
                                    <select class="form-control" name="company" id="companyInput">
                                        <option value="" disabled selected>Select Company</option>
                                        @foreach ($companies as $company)
                                            <option value="{{ $company->id }}">{{ $company->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div> --}}


                            <!-- Owner Dropdown -->
                            <div class="col-lg-6 mb-4">
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <select class="form-control" name="owner" id="ownerInput">
                                        @foreach ($users as $user)
                                            <option value="{{ $user->id }}"
                                                {{ auth()->id() == $user->id ? 'selected' : '' }}>
                                                {{ $user->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>


                            <!-- First Name Field -->
                            {{-- <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="first_name" id="firstNameInput"
                                        placeholder="First Name" />
                                </div>
                            </div>

                            <!-- Last Name Field -->
                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="last_name" id="lastNameInput"
                                        placeholder="Last Name" />
                                </div>
                            </div> --}}

                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="text" class="form-control" name="meeting_details"
                                        id="meetingDetailsInput" placeholder="Meeting Details" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-monitor"></i></div>
                                    <input type="text" class="form-control" name="hosting" id="hostingInput"
                                        placeholder="Hosting" />
                                </div>
                            </div>
                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-link"></i></div>
                                    <select class="form-control" name="related_to" id="relatedToInput">
                                        <option value="" disabled selected>Related To</option>
                                        <option value="1">Lead</option>
                                        <option value="2">Contact</option>
                                        <option value="3">Deal</option>
                                        <option value="4">Account</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-refresh-ccw"></i></div>
                                    <select class="form-control" name="repeat_type" id="repeatTypeInput">
                                        <option value="" disabled selected>Select Repeat Type</option>
                                        @foreach ($repeats as $repeat)
                                            <option value="{{ $repeat->id }}">{{ $repeat->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>



                            <div class="col-lg-6 mb-4" x-show="([2,4].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-users"></i></div>
                                    <select class="form-control" name="participants" id="participantsInput">
                                        <option value="" disabled selected>Select Participants</option>
                                        <option value="1">Lead</option>
                                        <option value="2">Contact</option>
                                        <option value="3">Deal</option>
                                        <option value="4">Account</option>
                                        <option value="5">Users</option>
                                        <option value="6">New Invite Account</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Duration Field -->
                            <div class="col-lg-6 mb-4">
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-clock"></i></div>
                                    <input type="text" class="form-control" name="duration" id="durationInput"
                                        placeholder="Duration" />
                                </div>
                            </div>

                            <!-- Due Date Field -->
                            <div class="col-lg-6 mb-4" x-show="([1, 3, 9, 2].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="date" class="form-control" name="due_date" id="dueDateInput"
                                        placeholder="Due Date" />
                                </div>
                            </div>

                            {{-- <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-tag"></i></div>
                                    <input type="text" class="form-control" name="promotion_code"
                                        id="promotionCodeInput" placeholder="Promotion Code" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-target"></i></div>
                                    <select class="form-control" name="related_campaign" id="relatedCampaignInput">
                                        <option value="" disabled selected>Related Campaign</option>
                                        <option value="1">Campaign 1</option>
                                        <option value="2">Campaign 2</option>
                                        <option value="3">Campaign 3</option>
                                        <option value="4">Campaign 4</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-code"></i></div>
                                    <input type="text" class="form-control" name="response_code"
                                        id="responseCodeInput" placeholder="Response Code" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-radio"></i></div>
                                    <select class="form-control" name="channel" id="channelInput">
                                        <option value="" disabled selected>Select Channel</option>
                                        <option value="1">Email</option>
                                        <option value="2">SMS</option>
                                        <option value="3">Phone</option>
                                        <option value="4">Social Media</option>
                                        <option value="5">Web</option>
                                        <option value="6">Push Notification</option>
                                    </select>
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <!-- Received On Input -->
                                <label for="receivedOnInput" class="form-label">Received On</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="date" class="form-control" name="received_on" id="receivedOnInput"
                                        placeholder="Received On" />
                                </div>
                            </div>

                            <div class="col-lg-6 mb-4" x-show="([10].includes($store.activity.selectedButton))"
                                x-transition>
                                <!-- Close By Input -->
                                <label for="closeByInput" class="form-label">Close By</label>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-calendar"></i></div>
                                    <input type="date" class="form-control" name="close_by" id="closeByInput"
                                        placeholder="Close By" />
                                </div>
                            </div> --}}

                            <!-- Call From Field -->
                            <div class="col-lg-6 mb-4" x-show="([1].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-user"></i></div>
                                    <input type="text" class="form-control" name="callFrom" id="callFromInput"
                                        placeholder="Call From" />
                                </div>
                            </div>
                            <div class="col-lg-16 mb-4" x-show="([1, 2, 3, 4,].includes($store.activity.selectedButton))"
                                x-transition>
                                <div class="input-group">
                                    <div class="input-group-text"><i class="feather-file-text"></i></div>
                                    <textarea class="form-control" name="description" id="descriptionInput" placeholder="Description"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>



                    <div class="modal-footer">
                        <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Discard</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="feather-activity me-2"></i>
                            <span>Create Activity</span>
                        </button>
                    </div>

                </div>

            </div>


        </form>
    </div>
@endsection
@section('scripts')

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const modal = document.getElementById('assignLeadEmployeeModal');
            const form = document.getElementById('assignLeadEmployeeForm');
            const select = document.getElementById('assignLeadEmployeeSelect');
            const topic = document.getElementById('assignLeadEmployeeTopic');
            if (!modal || !form || !select || !topic) return;

            modal.addEventListener('show.bs.modal', function (event) {
                const trigger = event.relatedTarget;
                if (!trigger) return;
                form.action = trigger.dataset.action;
                topic.textContent = `Assign “${trigger.dataset.leadTopic}” to another employee.`;
                const currentOwner = String(trigger.dataset.currentOwner || '');
                [...select.options].forEach(function (option) {
                    option.disabled = option.value !== '' && option.value === currentOwner;
                    option.selected = false;
                });
                select.value = '';
            });
        });
    </script>


    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log("Script is running!");

            // Ensure Select2 is initialized
            $('.update-stage').select2();

            // Attach event listener to Select2 elements
            $('.update-stage').on('change', function() {
                const leadId = $(this).data('id'); // Get contact ID using jQuery
                const stageId = $(this).val(); // Get selected stage ID using jQuery
                const unqualifiedReason = String(stageId) === '7'
                    ? window.prompt('Please enter the Unqualified reason:')
                    : null;
                if (String(stageId) === '7' && !unqualifiedReason) {
                    location.reload();
                    return;
                }

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

                if (leadId && stageId) {
                    fetch(`/leads/${leadId}/update-lead-stage`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')
                                    .getAttribute('content'),
                            },
                            body: JSON.stringify({
                                stage_id: stageId,
                                unqualified_reason: unqualifiedReason,
                            }),
                        })
                        .then(response => {
                            if (!response.ok) throw new Error('Failed to update Lead Status');
                            return response.json();
                        })
                        .then(data => {
                            console.log("Response received:", data.message);
                            if (data.conversion_url) {
                                window.location.href = data.conversion_url;
                            } else {
                                location.reload();
                            }
                        })
                        .catch(error => {
                            console.error("Error:", error);
                        });
                } else {
                    console.warn("Contact ID or Stage ID is missing!");
                }
            });
        });
    </script>



    <script>
        document.addEventListener('alpine:init', () => {
            Alpine.store('activity', {
                selectedButton: null, // Track the currently selected button
                activityTypes: {
                    'call': 1,
                    'meeting': 2,
                    'task': 3,
                    'event': 4,
                    'deadline': 5,
                    'otheractivity': 6,
                    'letter': 7,
                    'fax': 8,
                    'email': 9,
                    'campaign': 10
                },
            });
        });

        document.addEventListener('DOMContentLoaded', function() {

            document.querySelectorAll('[data-id]').forEach(function(element) {
                element.addEventListener('click', function() {
                    const selectedId = this.getAttribute('data-id');
                    console.log(selectedId); // Log the selected ID for debugging

                    // Map selectedId to numeric value based on activityTypes
                    const activityType = Alpine.store('activity').activityTypes[selectedId];
                    Alpine.store('activity').selectedButton = activityType;

                    const leadId = this.getAttribute('data-lead-id');
                    console.log(leadId); // Log the lead ID for debugging

                    // Set the value of the hidden lead_id input field
                    const leadInput = document.querySelector('input[name="lead_id"]');
                    if (leadInput) {
                        leadInput.value = leadId;
                    }
                    // Open the modal using Bootstrap's JavaScript API
                    const modal = document.querySelector('#addActivity');

                });
            });

            // Event listener for modal close
            const modalElement = document.querySelector('#addActivity');
            modalElement.addEventListener('hidden.bs.modal', function() {
                // Remove the backdrop after modal is closed
                removeBackdrop();
            });
        });

        // Function to add the backdrop if it's not there
        function addBackdrop() {
            if (!document.querySelector('.modal-backdrop')) {
                const backdrop = document.createElement('div');
                backdrop.classList.add('modal-backdrop', 'fade', 'show');
                document.body.appendChild(backdrop);
            }
        }

        // Function to remove the backdrop if exists
        function removeBackdrop() {
            const existingBackdrop = document.querySelector('.modal-backdrop');
            if (existingBackdrop) {
                existingBackdrop.remove();
            }
        }
    </script>


@endsection
