<?php

namespace App\Providers\Filament;

use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\View\PanelsRenderHook;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\Support\Facades\Blade;
use Illuminate\View\Middleware\ShareErrorsFromSession;

/**
 * Central panel — only on the central domain (service.mir.md/admin).
 * Uses the 'central' auth guard (super_admins).
 */
class CentralPanelProvider extends PanelProvider
{
    public function panel(Panel $panel): Panel
    {
        return $panel
            ->default()
            ->id('central')
            ->path('admin')
            ->domain(env('CENTRAL_DOMAIN', 'service.mir.md'))
            ->login()
            ->brandName('AutoCRM — Platformă')
            ->colors([
                'primary' => Color::Indigo,
            ])
            ->authGuard('central')
            ->authPasswordBroker('super_admins')
            ->multiFactorAuthentication([
                \Filament\Auth\MultiFactor\App\AppAuthentication::make(),
                \Filament\Auth\MultiFactor\Email\EmailAuthentication::make(),
            ])
            ->profile()
            ->discoverResources(in: app_path('Filament/Central/Resources'), for: 'App\\Filament\\Central\\Resources')
            ->discoverPages(in: app_path('Filament/Central/Pages'), for: 'App\\Filament\\Central\\Pages')
            ->pages([
                Dashboard::class,
            ])
            ->discoverWidgets(in: app_path('Filament/Central/Widgets'), for: 'App\\Filament\\Central\\Widgets')
            ->widgets([
                \App\Filament\Central\Widgets\PlatformStats::class,
                \App\Filament\Central\Widgets\RevenueChart::class,
                \App\Filament\Central\Widgets\PendingPayments::class,
                \App\Filament\Central\Widgets\RecentTenants::class,
            ])
            ->databaseNotifications()
            ->databaseNotificationsPolling('60s')
            ->globalSearch()
            ->globalSearchKeyBindings(['mod+k'])
            ->globalSearchFieldKeyBindingSuffix()
            ->renderHook(
                PanelsRenderHook::HEAD_END,
                fn (): string => Blade::render(<<<'BLADE'
                    <link rel="manifest" href="/admin-manifest.json">
                    <meta name="theme-color" content="#6366f1">
                    <meta name="apple-mobile-web-app-capable" content="yes">
                    <meta name="apple-mobile-web-app-status-bar-style" content="default">
                    <meta name="apple-mobile-web-app-title" content="AutoCRM Admin">
                    <link rel="icon" type="image/svg+xml" href="/pwa/admin-icon.svg">
                    <link rel="apple-touch-icon" href="/pwa/admin-512.png">
                BLADE)
            )
            ->renderHook(
                PanelsRenderHook::BODY_END,
                fn (): string => <<<'HTML'
                    <script>
                    if ('serviceWorker' in navigator) {
                        window.addEventListener('load', () => {
                            navigator.serviceWorker.register('/admin-sw.js', { scope: '/' }).catch(() => {});
                        });
                    }
                    </script>
                HTML
            )
            ->middleware([
                EncryptCookies::class,
                AddQueuedCookiesToResponse::class,
                StartSession::class,
                AuthenticateSession::class,
                ShareErrorsFromSession::class,
                VerifyCsrfToken::class,
                SubstituteBindings::class,
                DisableBladeIconComponents::class,
                DispatchServingFilamentEvent::class,
            ])
            ->authMiddleware([
                Authenticate::class,
            ]);
    }
}
