<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Namu\WireChat\Livewire\Concerns\Widget;
use Namu\WireChat\Models\Conversation; // Import the Conversation model

class UnreadIndicator extends Component
{
    use Widget;

    public int $unreadCount = 0;

    public function getListeners(): array
    {
        // Get the active guard from session
        $guard = session('active_guard', 'web');
        $user = auth($guard)->user();

        if (!$user) {
            return [
                'conversations-updated' => 'updateUnreadCount',
                'refresh' => 'updateUnreadCount',
            ];
        }

        // Listen to both the standard users channel and the participant channel
        $userId = $user->id;
        $encodedType = \Namu\WireChat\Helpers\MorphClassResolver::encode($user->getMorphClass());

        return [
            'conversations-updated' => 'updateUnreadCount',
            'refresh' => 'updateUnreadCount', // Listen to generic refresh events
            'refreshList' => 'updateUnreadCount', // Listen to chat list refresh events
            "echo-private:users.{$userId},.Illuminate\\Notifications\\Events\\BroadcastNotificationCreated" => 'updateUnreadCount',
            "echo-private:participant.{$encodedType}.{$userId},.Namu\\WireChat\\Events\\NotifyParticipant" => 'updateUnreadCount',
        ];
    }

    public function mount(): void
    {
        $this->updateUnreadCount();
    }

    public function updateUnreadCount(): void
    {
        // Get the active guard from session
        $guard = session('active_guard', 'web');
        $user = auth($guard)->user();

        if ($user) {
            // Use the Conversation model with the unreadFor scope
            $previousCount = $this->unreadCount;
            $this->unreadCount = Conversation::unreadFor($user)->count();

            // Debug: Log when unread count changes
            if ($previousCount !== $this->unreadCount) {
                \Log::info('UnreadIndicator count changed', [
                    'user_id' => $user->id,
                    'user_type' => get_class($user),
                    'guard' => $guard,
                    'previous_count' => $previousCount,
                    'new_count' => $this->unreadCount,
                    'backtrace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5),
                ]);
            }

            // Dispatch browser event to notify JS when unread count changes
            $this->dispatch('unread-count-updated', count: $this->unreadCount);
        }
    }

    public function render()
    {
        return view('livewire.unread-indicator');
    }
}