<?php

namespace App\Http\Livewire;

use App\Services\PresenceService;
use Livewire\Component;

class ProfileStatusBadge extends Component
{
    public $profileId;
    public $profileType;
    public $guard = 'web';
    public $status = 'offline';
    public $lastSeen;
    public $showText = true;
    public $showIcon = true;
    public $size = 'sm';

    public function mount($profileId = null, $guard = 'web', $showText = true, $showIcon = true, $size = 'sm')
    {
        $this->profileId = $profileId ?? auth($guard)->id();
        $this->guard = strtolower($guard);
        $this->showText = $showText;
        $this->showIcon = $showIcon;
        $this->size = $size;

        $this->checkStatus();
    }

    public function checkStatus()
    {
        try {
            if (!$this->profileId) {
                $this->status = 'offline';
                return;
            }

            $profileModel = $this->getUserModel();

            if (!$profileModel) {
                $this->status = 'offline';
                return;
            }

            // Use PresenceService to determine online status
            // This relies on recent activity tracking, not just authentication status
            $presenceService = app(PresenceService::class);

            if ($presenceService->isUserOnline($profileModel, $this->guard)) {
                $lastSeen = $presenceService->getUserLastSeen($profileModel, $this->guard);

                if ($lastSeen) {
                    $this->lastSeen = $lastSeen;
                    $minutesAgo = $lastSeen->diffInMinutes(now());

                    if ($minutesAgo <= 2) {
                        $this->status = 'online';
                    } elseif ($minutesAgo <= 5) {
                        $this->status = 'idle';
                    } else {
                        $this->status = 'offline';
                    }
                } else {
                    $this->status = 'online';
                }
            } else {
                $this->status = 'offline';
                $this->lastSeen = $presenceService->getUserLastSeen($profileModel, $this->guard);
            }
        } catch (\Exception $e) {
            $this->status = 'offline';
        }
    }

    protected function getUserModel()
    {
        switch ($this->guard) {
            case 'admin':
                return \App\Models\Admin::find($this->profileId);
            case 'bank':
                return \App\Models\Bank::find($this->profileId);
            case 'organization':
                return \App\Models\Organization::find($this->profileId);
            default:
                return \App\Models\User::find($this->profileId);
        }
    }

    public function render()
    {
        return view('livewire.profile-status-badge');
    }
}
