@props(['module', 'record'])
@php
    $relation = ['related_type' => $record::class, 'related_id' => $record->id];
    $activityForeign = ['contacts'=>'contact_id','leads'=>'lead_id','accounts'=>'account_id','deals'=>'deal_id','projects'=>'project_id','cases'=>'case_id'][$module] ?? null;
    $relatedActivities = $activityForeign && \Illuminate\Support\Facades\Schema::hasColumn('activities', $activityForeign)
        ? \App\Models\Activity::where('business_id', $record->business_id)->where($activityForeign, $record->id)->get()
        : collect();
    $relatedMessages = \App\Models\Message::where($relation)->latest()->limit(20)->get();
    $noteForeign = ['contacts'=>'contact_id','leads'=>'lead_id','accounts'=>'account_id','deals'=>'deal_id','tickets'=>'ticket_id','campaigns'=>'campaign_id','projects'=>'project_id','cases'=>'case_id','surveys'=>'survey_id'][$module] ?? null;
    $relatedNotes = $noteForeign && \Illuminate\Support\Facades\Schema::hasColumn('notes', $noteForeign)
        ? \App\Models\Note::where('business_id', $record->business_id)->where($noteForeign, $record->id)->visibleTo(auth()->user())->latest()->limit(20)->get()
        : collect();
    $relatedFollowUps = \App\Models\FollowUp::where($relation)->latest()->limit(20)->get();
    $relatedTodos = \App\Models\Todo::where($relation)->latest()->limit(20)->get();
    $assignmentUserNames = \App\Models\User::where('business_id', $record->business_id)->pluck('name', 'id');
    $assignmentAudits = in_array($module, ['leads','deals','cases'], true) ? \DB::table('assignment_rule_executions as audit')->leftJoin('assignment_rules as rule','rule.id','=','audit.rule_id')->where('audit.assignable_type', $record::class)->where('audit.assignable_id', $record->id)->select('audit.*','rule.name as rule_name')->latest('audit.id')->get()->map(function($audit) use($assignmentUserNames){$audit->rule_name=$audit->rule_name?:'Assignment rule';$audit->eligible_names=collect(json_decode($audit->eligible_user_ids,true))->map(fn($id)=>$assignmentUserNames[$id]??'Former user')->join(', ');$audit->selected_name=$assignmentUserNames[$audit->selected_user_id]??'Unassigned';return $audit;}) : collect();
    $lastInteraction = $relatedActivities->where('lifecycle_status', 'completed')
        ->sortByDesc(fn ($item) => $item->completed_at ?? $item->created_at)->first();
    $nextInteraction = $relatedActivities->whereNotIn('lifecycle_status', ['completed', 'cancelled'])
        ->map(fn ($item) => ['title' => $item->title ?: $item->subject, 'at' => \Carbon\Carbon::parse(($item->start_date ?: now()->toDateString()).' '.($item->start_time ?: '00:00'))])
        ->merge($relatedFollowUps->where('status', 'pending')->map(fn ($item) => ['title' => $item->title, 'at' => $item->follow_up_at]))
        ->merge($relatedTodos->whereNotIn('status', ['completed', 'cancelled'])->map(fn ($item) => ['title' => $item->title, 'at' => $item->due_at]))
        ->filter(fn ($item) => $item['at'])->sortBy('at')->first();
@endphp
<div class="card mt-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">Interaction timeline</h5>
        <a class="btn btn-sm btn-outline-primary" href="{{ route('related-activity.index', [$module, $record->id]) }}">Full timeline</a>
    </div>
    <div class="card-body">
        <div class="row g-3 mb-3">
            <div class="col-md-6"><div class="border rounded p-3 h-100"><small class="text-muted">Last interaction</small><strong class="d-block">{{ $lastInteraction?->title ?: $lastInteraction?->subject ?: 'None recorded' }}</strong>@if($lastInteraction)<small>{{ ($lastInteraction->completed_at ?: $lastInteraction->created_at)?->format('M d, Y H:i') }}</small>@endif</div></div>
            <div class="col-md-6"><div class="border rounded p-3 h-100"><small class="text-muted">Next interaction</small><strong class="d-block">{{ $nextInteraction['title'] ?? 'None scheduled' }}</strong>@if(isset($nextInteraction['at']))<small>{{ $nextInteraction['at']->format('M d, Y H:i') }}</small>@endif</div></div>
        </div>
        @if($assignmentAudits->isNotEmpty())<div class="alert alert-light border"><strong>Automatic assignment audit</strong>@foreach($assignmentAudits as $audit)<div class="small"><strong>{{ $audit->rule_name }}</strong> · {{ ucwords(str_replace('_',' ',$audit->strategy)) }} selected {{ $audit->selected_name }} from {{ $audit->eligible_names }} — {{ $audit->reason }} ({{ $audit->created_at }})</div>@endforeach</div>@endif
        <div class="row g-3">
            @foreach(['Messages'=>$relatedMessages,'Notes'=>$relatedNotes,'Follow-ups'=>$relatedFollowUps,'To-dos'=>$relatedTodos] as $heading=>$items)
                <div class="col-lg-3 col-md-6">
                    <h6>{{ $heading }} <span class="badge bg-secondary">{{ $items->count() }}</span></h6>
                    <div class="list-group">
                        @forelse($items as $item)
                            <div class="list-group-item">
                                <strong class="d-block text-truncate">{{ $item->title ?? $item->subject ?? $item->content }}</strong>
                                <small class="text-muted">{{ ucfirst(str_replace('_',' ',$item->status ?? '')) }} · {{ ($item->follow_up_at ?? $item->due_at ?? $item->created_at)?->format('M d, Y H:i') }}</small>
                            </div>
                        @empty
                            <div class="list-group-item text-muted">No records.</div>
                        @endforelse
                    </div>
                </div>
            @endforeach
        </div>
        <div class="mt-3 d-flex gap-2">
            <a class="btn btn-sm btn-light" href="{{ route('workflow.index',['messages','related_type'=>rtrim($module,'s'),'related_id'=>$record->id]) }}">Add Message</a>
            <a class="btn btn-sm btn-light" href="{{ route('workflow.index',['notes','related_type'=>rtrim($module,'s'),'related_id'=>$record->id]) }}">Add Note</a>
            <a class="btn btn-sm btn-light" href="{{ route('workflow.index',['follow-ups','related_type'=>rtrim($module,'s'),'related_id'=>$record->id]) }}">Add Follow-up</a>
            <a class="btn btn-sm btn-light" href="{{ route('workflow.index',['todos','related_type'=>rtrim($module,'s'),'related_id'=>$record->id]) }}">Add To-do</a>
        </div>
    </div>
</div>
