<?php

namespace App\Services;

use Illuminate\Support\Facades\File;

class MockDataService
{
    private static string $basePath = '';

    private static function path(): string
    {
        if (!self::$basePath) {
            self::$basePath = resource_path('mock-data');
        }
        return self::$basePath;
    }

    private static function load(string $file): array
    {
        $path = self::path() . DIRECTORY_SEPARATOR . $file . '.json';
        if (!File::exists($path)) return [];
        return json_decode(File::get($path), true) ?? [];
    }

    // ----------------------------------------------------------------
    // Games
    // ----------------------------------------------------------------
    public static function games(): array
    {
        return self::load('games');
    }

    public static function game(string $slug): ?array
    {
        return collect(self::games())->firstWhere('id', $slug);
    }

    // ----------------------------------------------------------------
    // Players
    // ----------------------------------------------------------------
    public static function players(array $filters = []): array
    {
        $players = self::load('players');

        if (!empty($filters['game'])) {
            $players = array_filter($players, fn($p) =>
                collect($p['games'])->contains('game_id', $filters['game'])
            );
        }

        if (!empty($filters['country'])) {
            $players = array_filter($players, fn($p) => $p['country'] === $filters['country']);
        }

        if (!empty($filters['looking_for_team'])) {
            $players = array_filter($players, fn($p) => $p['looking_for_team'] === true);
        }

        return array_values($players);
    }

    public static function player(string $slug): ?array
    {
        return collect(self::load('players'))->firstWhere('slug', $slug);
    }

    // ----------------------------------------------------------------
    // Teams
    // ----------------------------------------------------------------
    public static function teams(array $filters = []): array
    {
        $teams = self::load('teams');

        if (!empty($filters['game'])) {
            $teams = array_filter($teams, fn($t) =>
                in_array($filters['game'], $t['games'])
            );
        }

        if (!empty($filters['region'])) {
            $teams = array_filter($teams, fn($t) => $t['region'] === $filters['region']);
        }

        if (!empty($filters['looking_for_players'])) {
            $teams = array_filter($teams, fn($t) => $t['looking_for_players'] === true);
        }

        return array_values($teams);
    }

    public static function team(string $slug): ?array
    {
        return collect(self::load('teams'))->firstWhere('slug', $slug);
    }

    // ----------------------------------------------------------------
    // Tournaments
    // ----------------------------------------------------------------
    public static function tournaments(array $filters = []): array
    {
        $tournaments = self::load('tournaments');

        if (!empty($filters['game'])) {
            $tournaments = array_filter($tournaments, fn($t) => $t['game'] === $filters['game']);
        }

        if (!empty($filters['status'])) {
            $tournaments = array_filter($tournaments, fn($t) => $t['status'] === $filters['status']);
        }

        if (!empty($filters['region'])) {
            $tournaments = array_filter($tournaments, fn($t) =>
                $t['region'] === $filters['region'] || $t['region'] === 'Global'
            );
        }

        return array_values($tournaments);
    }

    public static function tournament(string $slug): ?array
    {
        return collect(self::load('tournaments'))->firstWhere('slug', $slug);
    }

    public static function featuredTournaments(): array
    {
        return array_values(array_filter(self::load('tournaments'), fn($t) => $t['featured'] ?? false));
    }

    // ----------------------------------------------------------------
    // Rankings
    // ----------------------------------------------------------------
    public static function rankings(string $type = 'players', string $game = 'valorstrike'): array
    {
        $players = self::load('players');
        usort($players, fn($a, $b) => $b['stats']['points'] <=> $a['stats']['points']);
        return array_values(array_slice($players, 0, 20));
    }

    // ----------------------------------------------------------------
    // Recruitment
    // ----------------------------------------------------------------
    public static function recruitment(): array
    {
        return [
            [
                'id' => 1, 'type' => 'lft',
                'title' => 'Experienced Duelist LFT — Mythic Rank',
                'title_ar' => 'لاعب دويليست متمرس يبحث عن فريق — رتبة خرافي',
                'player' => self::player('nightfalcon'),
                'game' => 'valorstrike', 'game_name' => 'ValoStrike',
                'role' => 'Duelist', 'rank' => 'Mythic',
                'region' => 'MENA', 'availability' => 'Full Time',
                'compensation' => 'Paid',
                'posted_at' => '2026-07-10',
                'description' => 'Looking for a professional or semi-pro team to join. Ready for regular scrims, tournaments, and boot camps.',
                'tags' => ['Mythic', 'MENA', 'Full Time', 'Paid', 'Verified'],
            ],
            [
                'id' => 2, 'type' => 'lfp',
                'title' => 'Team Nexus Seeking Controller — All Ranks Welcome',
                'title_ar' => 'فريق نيكسوس يبحث عن لاعب تحكم — جميع الرتب مرحب بها',
                'team' => self::team('team-nexus'),
                'game' => 'valorstrike', 'game_name' => 'ValoStrike',
                'role' => 'Controller', 'min_rank' => 'Platinum',
                'region' => 'MENA', 'availability' => 'Part Time',
                'compensation' => 'Unpaid',
                'posted_at' => '2026-07-12',
                'description' => 'We are looking for a reliable Controller player for our Valorstrike roster. Regular scrims on weekends.',
                'tags' => ['Platinum+', 'MENA', 'Part Time', 'Trial', 'Active'],
            ],
            [
                'id' => 3, 'type' => 'lfp',
                'title' => 'Storm Rising — Building Full Roster (StrikeZone)',
                'title_ar' => 'العاصفة الصاعدة — بناء فريق كامل (ستريك زون)',
                'team' => self::team('storm-rising'),
                'game' => 'strikezone', 'game_name' => 'StrikeZone',
                'role' => 'Multiple Roles', 'min_rank' => 'Semi-Pro',
                'region' => 'MENA', 'availability' => 'Flexible',
                'compensation' => 'Unpaid',
                'posted_at' => '2026-07-11',
                'description' => 'Young UAE team looking to build a complete squad. Need Rifler, Entry Fragger, Lurker, and Support.',
                'tags' => ['Semi-Pro', 'UAE', 'Flexible', 'Multiple Roles'],
            ],
            [
                'id' => 4, 'type' => 'lft',
                'title' => 'IGL / AWP specialist — LFT Diamond+',
                'title_ar' => 'متخصص قيادة + قناص يبحث عن فريق — ألماس+',
                'player' => self::player('sandstorm'),
                'game' => 'valorstrike', 'game_name' => 'ValoStrike',
                'role' => 'Duelist / AWP', 'rank' => 'Diamond',
                'region' => 'MENA', 'availability' => 'Part Time',
                'compensation' => 'Any',
                'posted_at' => '2026-07-13',
                'description' => 'Rising Saudi player with Diamond rank, looking to move to organized team environment for ranked and tournaments.',
                'tags' => ['Diamond', 'Saudi Arabia', 'Part Time', 'Rising Talent'],
            ],
        ];
    }

    // ----------------------------------------------------------------
    // Scrims
    // ----------------------------------------------------------------
    public static function scrims(): array
    {
        return [
            [
                'id' => 1,
                'team' => ['name' => 'Team Nexus', 'slug' => 'team-nexus', 'logo' => '/assets/images/generated/teams/team-1.webp', 'tag' => 'NXS'],
                'game' => 'valorstrike', 'game_name' => 'ValoStrike',
                'format' => 'BO3', 'map_pool' => ['Haven', 'Bind', 'Lotus'],
                'min_rank' => 'Platinum', 'region' => 'MENA', 'server' => 'MENA',
                'scheduled_at' => '2026-07-14T20:00:00+03:00',
                'status' => 'open',
                'note' => 'Looking for practice match. We play every other day.',
                'note_ar' => 'نبحث عن مباراة تدريبية. نلعب كل يومين.',
                'slots' => 2, 'applications' => 1,
            ],
            [
                'id' => 2,
                'team' => ['name' => 'Alpha Squad', 'slug' => 'alpha-squad', 'logo' => '/assets/images/generated/teams/team-2.webp', 'tag' => 'ALPH'],
                'game' => 'valorstrike', 'game_name' => 'ValoStrike',
                'format' => 'BO1', 'map_pool' => ['Abyss'],
                'min_rank' => 'Diamond', 'region' => 'APAC', 'server' => 'APAC',
                'scheduled_at' => '2026-07-14T18:00:00+09:00',
                'status' => 'open',
                'note' => 'Serious scrims only. Must have coaching staff.',
                'note_ar' => '',
                'slots' => 1, 'applications' => 0,
            ],
            [
                'id' => 3,
                'team' => ['name' => 'Void Runners', 'slug' => 'void-runners', 'logo' => '/assets/images/generated/teams/team-4.webp', 'tag' => 'VOID'],
                'game' => 'nexus-ops', 'game_name' => 'Nexus Ops',
                'format' => 'Custom', 'map_pool' => ['Warzone Island'],
                'min_rank' => 'Elite', 'region' => 'LATAM', 'server' => 'SA',
                'scheduled_at' => '2026-07-15T19:00:00-03:00',
                'status' => 'open',
                'note' => 'Weekend scrims with video review. Seeking full squads.',
                'note_ar' => '',
                'slots' => 3, 'applications' => 2,
            ],
        ];
    }

    // ----------------------------------------------------------------
    // Feed
    // ----------------------------------------------------------------
    public static function feed(): array
    {
        return [
            [
                'id' => 1, 'type' => 'team_join',
                'actor' => ['name' => 'NightFalcon', 'slug' => 'nightfalcon', 'avatar' => '/assets/images/generated/players/player-1.webp', 'verified' => true],
                'target' => ['name' => 'Team Nexus', 'slug' => 'team-nexus', 'type' => 'team'],
                'text' => 'joined {target} as starting Duelist',
                'text_ar' => 'انضم إلى {target} كلاعب رئيسي',
                'time' => '2026-07-13T12:30:00Z',
                'reactions' => ['🔥' => 42, '💪' => 18, '❤️' => 31],
                'game' => 'ValoStrike',
            ],
            [
                'id' => 2, 'type' => 'achievement',
                'actor' => ['name' => 'StellarX', 'slug' => 'stellarx', 'avatar' => '/assets/images/generated/players/player-2.webp', 'verified' => true],
                'target' => ['name' => 'Mythic 200 Stars', 'type' => 'achievement'],
                'text' => 'reached {target} — top 0.1% globally',
                'text_ar' => 'وصلت إلى {target} — أفضل 0.1% عالمياً',
                'time' => '2026-07-13T10:15:00Z',
                'reactions' => ['🏅' => 128, '⭐' => 94, '🔥' => 77],
                'game' => 'ValoStrike',
            ],
            [
                'id' => 3, 'type' => 'match_result',
                'actor' => ['name' => 'Team Nexus', 'slug' => 'team-nexus', 'avatar' => '/assets/images/generated/teams/team-1.webp', 'verified' => true, 'type' => 'team'],
                'vs' => ['name' => 'Storm Rising', 'slug' => 'storm-rising'],
                'score' => ['home' => 2, 'away' => 0],
                'result' => 'win',
                'text' => 'won their scrim 2-0 against Storm Rising',
                'text_ar' => 'فاز في السكريم 2-0 على العاصفة الصاعدة',
                'time' => '2026-07-13T08:00:00Z',
                'reactions' => ['🏆' => 56, '🔥' => 33],
                'game' => 'ValoStrike',
            ],
            [
                'id' => 4, 'type' => 'tournament_join',
                'actor' => ['name' => 'Alpha Squad', 'slug' => 'alpha-squad', 'avatar' => '/assets/images/generated/teams/team-2.webp', 'verified' => true, 'type' => 'team'],
                'target' => ['name' => 'ALGA ARENA Cup S1', 'slug' => 'alga-arena-cup-s1', 'type' => 'tournament'],
                'text' => 'registered for {target}',
                'text_ar' => 'سجّل في {target}',
                'time' => '2026-07-12T20:45:00Z',
                'reactions' => ['🏆' => 23, '💪' => 41],
                'game' => 'ValoStrike',
            ],
            [
                'id' => 5, 'type' => 'recruitment',
                'actor' => ['name' => 'Storm Rising', 'slug' => 'storm-rising', 'avatar' => '/assets/images/generated/teams/team-3.webp', 'verified' => false, 'type' => 'team'],
                'target' => null,
                'text' => 'posted a new recruitment: Looking for Rifler + Entry Fragger (StrikeZone)',
                'text_ar' => 'نشر إعلان تجنيد جديد: نبحث عن لاعب رايفلر + لاعب اقتحام (ستريك زون)',
                'time' => '2026-07-12T14:30:00Z',
                'reactions' => ['🎯' => 15],
                'game' => 'StrikeZone',
            ],
        ];
    }

    // ----------------------------------------------------------------
    // Transfer Market
    // ----------------------------------------------------------------
    public static function transferMarket(): array
    {
        $players = self::load('players');
        $available = array_filter($players, fn($p) => $p['looking_for_team']);
        return [
            'free_agents' => array_values($available),
            'transfer_listed' => array_slice(array_values($players), 2, 2),
            'loan_listed' => array_slice(array_values($players), 4, 1),
        ];
    }

    // ----------------------------------------------------------------
    // Subscriptions
    // ----------------------------------------------------------------
    public static function subscriptions(): array
    {
        return [
            [
                'id' => 'free', 'name' => 'Free', 'name_ar' => 'مجاني',
                'price_monthly' => 0, 'price_yearly' => 0,
                'color' => '--arena-text-muted',
                'features' => [
                    ['text' => 'Public profile', 'included' => true],
                    ['text' => '2 game profiles', 'included' => true],
                    ['text' => 'Join 1 team', 'included' => true],
                    ['text' => 'View public scrims', 'included' => true],
                    ['text' => 'Community feed', 'included' => true],
                    ['text' => 'Advanced analytics', 'included' => false],
                    ['text' => 'Transfer market access', 'included' => false],
                    ['text' => 'Priority support', 'included' => false],
                    ['text' => 'Verification badge', 'included' => false],
                    ['text' => 'Unlimited teams', 'included' => false],
                ],
            ],
            [
                'id' => 'player_pro', 'name' => 'Player Pro', 'name_ar' => 'لاعب برو',
                'price_monthly' => 9.99, 'price_yearly' => 89.99,
                'featured' => true,
                'color' => 'var(--arena-accent)',
                'features' => [
                    ['text' => 'Everything in Free', 'included' => true],
                    ['text' => 'Unlimited game profiles', 'included' => true],
                    ['text' => 'Advanced player analytics', 'included' => true],
                    ['text' => 'Transfer market access', 'included' => true],
                    ['text' => 'Join unlimited teams', 'included' => true],
                    ['text' => 'Priority scrim matching', 'included' => true],
                    ['text' => 'Verification eligible', 'included' => true],
                    ['text' => 'Custom profile themes', 'included' => true],
                    ['text' => 'Priority support', 'included' => true],
                    ['text' => 'Pro badge on profile', 'included' => true],
                ],
            ],
            [
                'id' => 'team_pro', 'name' => 'Team Pro', 'name_ar' => 'فريق برو',
                'price_monthly' => 29.99, 'price_yearly' => 269.99,
                'color' => 'var(--arena-violet)',
                'features' => [
                    ['text' => 'Everything in Player Pro', 'included' => true],
                    ['text' => 'Organization dashboard', 'included' => true],
                    ['text' => 'Team analytics', 'included' => true],
                    ['text' => 'Manage up to 5 rosters', 'included' => true],
                    ['text' => 'Team verification badge', 'included' => true],
                    ['text' => 'Priority tournament placement', 'included' => true],
                    ['text' => 'Contract management tools', 'included' => true],
                    ['text' => 'Dedicated support line', 'included' => true],
                    ['text' => 'Sponsor profile tools', 'included' => true],
                    ['text' => 'Featured in directory', 'included' => true],
                ],
            ],
            [
                'id' => 'organizer_pro', 'name' => 'Organizer Pro', 'name_ar' => 'منظم برو',
                'price_monthly' => 49.99, 'price_yearly' => 449.99,
                'color' => 'var(--arena-warm)',
                'features' => [
                    ['text' => 'Everything in Team Pro', 'included' => true],
                    ['text' => 'Unlimited tournament creation', 'included' => true],
                    ['text' => 'Automated bracket management', 'included' => true],
                    ['text' => 'Prize escrow tools', 'included' => true],
                    ['text' => 'Custom tournament pages', 'included' => true],
                    ['text' => 'Referee management', 'included' => true],
                    ['text' => 'Dispute resolution system', 'included' => true],
                    ['text' => 'Stream integration', 'included' => true],
                    ['text' => 'Analytics dashboard', 'included' => true],
                    ['text' => 'White-label options', 'included' => false],
                ],
            ],
        ];
    }

    // ----------------------------------------------------------------
    // Platform stats (for landing page hero)
    // ----------------------------------------------------------------
    public static function platformStats(): array
    {
        return [
            'players'       => 48234,
            'teams'         => 3201,
            'tournaments'   => 1280,
            'matches_today' => 384,
            'countries'     => 47,
            'prize_awarded' => '2.4M',
        ];
    }
}
