<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class Footer extends Component
{
    public $equity;
    public $freeMargin;
    public $balance;
    public $margin;
    public $marginLevel;
    public $currentTab = null;

    public function mount()
    {
        $this->updateStats();
        $this->updateCurrentTab();
    }

    public function updateStats()
    {
        if (Auth::check()) {
            $user = Auth::user();
            $this->equity = number_format($user->confirmedBalance() + $user->calculateTotalUnrealizedPL(), 2);
            $this->freeMargin = $user->getFormattedFreeMargin();
            $this->balance = $user->confirmedBalance();
            $this->margin = $user->getFormattedTotalMargin();
            $this->marginLevel = $user->getFormattedMarginLevel();
        } else {
            $this->equity = '0.00';
            $this->freeMargin = '0.00';
            $this->balance = '0.00';
            $this->margin = '0.00';
            $this->marginLevel = '0.00';
        }
        // Update tab state when polling
        $this->updateCurrentTab();
    }

    public function updateCurrentTab()
    {
        // Match Dashboard's tab logic
        $tab = request()->get('tab');
        if ($tab === 'positions') {
            $this->currentTab = 'open-orders';
        } elseif ($tab === 'history') {
            $this->currentTab = 'closed-orders';
        } elseif ($tab === 'market') {
            $this->currentTab = 'market';
        } else {
            $this->currentTab = null; // Default: trade view
        }
    }

    public function render()
    {
        return view('livewire.footer');
    }
}
