<?php

declare(strict_types=1);

namespace App\View\Components;

use App\Models\Coach;
use App\Support\Uploads\ImageVariants;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\Component;

class CoachSpotlight extends Component
{
    /**
     * @var array<int, array<string, mixed>>
     */
    public array $trainers;

    /**
     * @param  iterable<int, array<string, mixed>>|null  $trainers
     */
    public function __construct(iterable $trainers = [])
    {
        $asArray = $trainers instanceof Collection
            ? $trainers->all()
            : (is_array($trainers) ? $trainers : iterator_to_array($trainers));

        $this->trainers = array_values(array_filter($asArray, static fn ($value): bool => is_array($value) && $value !== []));

        if ($this->trainers === []) {
            $this->trainers = $this->loadDefaultTrainers();
        }
    }

    public function render(): View
    {
        return view('components.coach-spotlight');
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    protected function loadDefaultTrainers(): array
    {
        /** @var \Illuminate\Filesystem\FilesystemAdapter $publicDisk */
        $publicDisk = Storage::disk('public');

        return Coach::query()
            ->where('is_active', true)
            ->with([
                'venues' => fn (\Illuminate\Database\Eloquent\Relations\BelongsToMany $query) =>
                    $query
                        ->where('venues.is_active', true)
                        ->wherePivot('is_active', true)
                        ->orderBy('coach_venue.sort_order')
                        ->orderBy('venues.sort_order'),
            ])
            ->orderBy('sort_order')
            ->orderBy('id')
            ->limit(10)
            ->get([
                'id',
                'name',
                'english_name',
                'title',
                'avatar_image_path',
                'specialties',
                'certifications',
            ])
            ->map(function (Coach $coach) use ($publicDisk): array {
                $imageUrl = filled($coach->avatar_image_path)
                    ? (ImageVariants::mediumUrl($coach->avatar_image_path, 'public') ?? $publicDisk->url($coach->avatar_image_path))
                    : 'https://placehold.co/240x240/png?text=Coach';

                /** @var ?\App\Models\Venue $primaryVenue */
                $primaryVenue = $coach->venues->first();

                $lines = $this->buildSpotlightLines($coach);

                return [
                    'img' => $imageUrl,
                    'name' => (string) ($coach->name ?? ''),
                    'nameEn' => (string) ($coach->english_name ?? ''),
                    'club' => (string) ($primaryVenue?->name ?? ''),
                    'job_title' => (string) ($coach->title ?? ''),
                    'lines' => $lines,
                ];
            })
            ->all();
    }

    /**
     * @return array<int, string>
     */
    protected function buildSpotlightLines(Coach $coach): array
    {
        $lines = [];

        if (filled($coach->specialties)) {
            $parts = preg_split('/[\r\n,]+/', (string) $coach->specialties) ?: [];
            foreach ($parts as $part) {
                $value = trim((string) $part);
                if ($value === '') {
                    continue;
                }
                $lines[] = $value;
                if (count($lines) >= 2) {
                    break;
                }
            }
        }

        if ($lines === [] && is_array($coach->certifications)) {
            foreach (Arr::flatten($coach->certifications) as $cert) {
                $value = trim((string) $cert);
                if ($value === '') {
                    continue;
                }
                $lines[] = $value;
                if (count($lines) >= 2) {
                    break;
                }
            }
        }

        return $lines;
    }
}
