<div>
<x-slot name="header">

    {{-- ── Header de la empresa ─────────────────────────────────────────────── --}}
    <div class="flex items-start justify-between gap-4 flex-wrap">

        {{-- Izquierda: logo + datos --}}
        <div class="flex items-start gap-4">

            {{-- Logo --}}
            @if($company->logo_path && \Illuminate\Support\Facades\Storage::disk('public')->exists($company->logo_path))
                <img src="{{ \Illuminate\Support\Facades\Storage::disk('public')->url($company->logo_path) }}"
                     class="w-16 h-16 rounded-xl object-contain border border-base-300 bg-white shadow shrink-0"
                     alt="Logo {{ $company->name }}" />
            @else
                <div class="w-16 h-16 rounded-xl bg-base-200 flex items-center justify-center shadow shrink-0">
                    <x-heroicon-o-building-office-2 class="w-8 h-8 opacity-30" />
                </div>
            @endif

            {{-- Datos --}}
            <div>
                <div class="flex flex-wrap items-center gap-2">
                    <h2 class="font-bold text-xl leading-tight">{{ $company->name }}</h2>
                    @if($company->apodo)
                        <span class="text-gray-400 font-normal text-base">"{{ $company->apodo }}"</span>
                    @endif
                    {{-- Tipo --}}
                    @php
                        $typeBadge = match($company->type) {
                            'owner'         => ['badge-success',  __('Owner')],
                            'constructor'   => ['badge-primary',  __('Constructor')],
                            'subcontractor' => ['badge-secondary',__('Subcontractor')],
                            'consultant'    => ['badge-info',     __('Consultant')],
                            'supplier'      => ['badge-warning',  __('Supplier')],
                            default         => ['badge-ghost',    __('Other')],
                        };
                    @endphp
                    <span class="badge {{ $typeBadge[0] }}">{{ $typeBadge[1] }}</span>
                </div>

                {{-- NIF --}}
                @if($company->tax_id)
                    <p class="text-xs text-gray-400 mt-0.5">NIF/CIF: {{ $company->tax_id }}</p>
                @endif

                {{-- Contacto inline --}}
                <div class="flex flex-wrap items-center gap-x-4 gap-y-0.5 mt-1.5 text-sm text-gray-500">
                    @if($company->email)
                        <span class="flex items-center gap-1">
                            <x-heroicon-o-envelope class="w-3.5 h-3.5 opacity-60 shrink-0" />
                            {{ $company->email }}
                        </span>
                    @endif
                    @if($company->phone)
                        <span class="flex items-center gap-1">
                            <x-heroicon-o-phone class="w-3.5 h-3.5 opacity-60 shrink-0" />
                            {{ $company->phone }}
                        </span>
                    @endif
                    @if($company->address)
                        <span class="flex items-center gap-1 max-w-xs">
                            <x-heroicon-o-map-pin class="w-3.5 h-3.5 opacity-60 shrink-0" />
                            <span class="truncate">{{ $company->address }}</span>
                        </span>
                    @endif
                    @if($company->website)
                        <a href="{{ $company->website }}" target="_blank" rel="noopener"
                           class="flex items-center gap-1 text-primary hover:underline">
                            <x-heroicon-o-globe-alt class="w-3.5 h-3.5 shrink-0" />
                            {{ parse_url($company->website, PHP_URL_HOST) ?? $company->website }}
                        </a>
                    @endif
                </div>
            </div>
        </div>

        {{-- Derecha: estado + botones --}}
        <div class="flex flex-col items-end gap-2">
            {{-- Estado --}}
            @php
                $estadoBadge = match($company->estado ?? 'activo') {
                    'activo'     => ['badge-success', __('Active')],
                    'inactivo'   => ['badge-ghost',   __('Inactive')],
                    'suspendido' => ['badge-error',   __('Suspended')],
                    default      => ['badge-ghost',   ucfirst($company->estado ?? '')],
                };
            @endphp
            <span class="badge {{ $estadoBadge[0] }} badge-md">{{ $estadoBadge[1] }}</span>

            {{-- Botones --}}
            <div class="flex gap-2 mt-1">
                <a href="{{ route('companies.edit', $company) }}"
                   class="btn btn-outline btn-sm gap-1" wire:navigate>
                    <x-heroicon-o-pencil class="w-4 h-4" />
                    {{ __('Edit') }}
                </a>
                <a href="{{ route('companies.manage') }}"
                   class="btn btn-ghost btn-sm gap-1" wire:navigate>
                    <x-heroicon-o-arrow-left class="w-4 h-4" />
                    {{ __('Back') }}
                </a>
            </div>
        </div>

    </div>

</x-slot>

{{-- ── Contenido principal ──────────────────────────────────────────────── --}}
<div class="py-6">
<div class="max-w-5xl mx-auto sm:px-6 lg:px-8 space-y-4">

    <!-- Tabs --}}
        <div role="tablist" class="tabs tabs-bordered">
            <button role="tab" wire:click="setTab('summary')"
                    class="tab gap-2 {{ $activeTab === 'summary' ? 'tab-active font-semibold' : '' }}">
                <x-heroicon-o-chart-bar class="w-4 h-4" />
                {{ __('Summary') }}
            </button>
            <button role="tab" wire:click="setTab('people')"
                    class="tab gap-2 {{ $activeTab === 'people' ? 'tab-active font-semibold' : '' }}">
                <x-heroicon-o-users class="w-4 h-4" />
                {{ __('People') }}
                <span class="badge badge-sm badge-outline">{{ $usersCount }}</span>
            </button>
            <button role="tab" wire:click="setTab('projects')"
                    class="tab gap-2 {{ $activeTab === 'projects' ? 'tab-active font-semibold' : '' }}">
                <x-heroicon-o-folder-open class="w-4 h-4" />
                {{ __('Projects') }}
                <span class="badge badge-sm badge-outline">{{ $projectsCount }}</span>
            </button>
            <button role="tab" wire:click="setTab('notes')"
                    class="tab gap-2 {{ $activeTab === 'notes' ? 'tab-active font-semibold' : '' }}">
                <x-heroicon-o-document-text class="w-4 h-4" />
                {{ __('Notes') }}
                @if($company->notes)
                    <span class="badge badge-sm badge-primary">•</span>
                @endif
            </button>
        </div>

    {{-- ════════════════════════════════════════════════════════════════════
             TAB: SUMMARY
    ════════════════════════════════════════════════════════════════════ --}}
        @if($activeTab === 'summary')
        <div class="space-y-4">

            {{-- KPIs --}}
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">

                <div class="card bg-base-100 shadow">
                    <div class="card-body p-4 items-center text-center">
                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mb-1">
                            <x-heroicon-o-users class="w-5 h-5 text-blue-600" />
                        </div>
                        <p class="text-3xl font-bold">{{ $usersCount }}</p>
                        <p class="text-xs text-gray-500 mt-0.5">{{ __('People') }}</p>
                    </div>
                </div>

                <div class="card bg-base-100 shadow">
                    <div class="card-body p-4 items-center text-center">
                        <div class="w-10 h-10 rounded-full bg-indigo-100 flex items-center justify-center mb-1">
                            <x-heroicon-o-folder-open class="w-5 h-5 text-indigo-600" />
                        </div>
                        <p class="text-3xl font-bold">{{ $projectsCount }}</p>
                        <p class="text-xs text-gray-500 mt-0.5">{{ __('Projects') }}</p>
                    </div>
                </div>

                <div class="card bg-base-100 shadow">
                    <div class="card-body p-4 items-center text-center">
                        <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center mb-1">
                            <x-heroicon-o-arrow-trending-up class="w-5 h-5 text-green-600" />
                        </div>
                        <p class="text-3xl font-bold">{{ $avgProgress }}<span class="text-lg font-normal text-gray-400">%</span></p>
                        <p class="text-xs text-gray-500 mt-0.5">{{ __('Average progress') }}</p>
                        @if($projectsCount > 0)
                            <progress class="progress progress-success w-full h-1 mt-1"
                                      value="{{ $avgProgress }}" max="100"></progress>
                        @endif
                    </div>
                </div>

                <div class="card bg-base-100 shadow">
                    <div class="card-body p-4 items-center text-center">
                        <div class="w-10 h-10 rounded-full bg-orange-100 flex items-center justify-center mb-1">
                            <x-heroicon-o-exclamation-triangle class="w-5 h-5 text-orange-500" />
                        </div>
                        <p class="text-3xl font-bold {{ $openIssues > 0 ? 'text-warning' : '' }}">{{ $openIssues }}</p>
                        <p class="text-xs text-gray-500 mt-0.5">{{ __('Open issues') }}</p>
                    </div>
                </div>

            </div>

            {{-- Projects with progress --}}
            @if($company->projects->isNotEmpty())
            <div class="card bg-base-100 shadow">
                <div class="card-body p-5">
                    <h3 class="font-semibold text-sm mb-3 flex items-center gap-2">
                        <x-heroicon-o-chart-bar-square class="w-4 h-4 text-primary" />
                        {{ __('Projects status') }}
                    </h3>
                    <div class="space-y-3">
                        @foreach($company->projects as $p)
                            @php
                                $avg = $p->phases->avg('progress_percent') ?? 0;
                                $pStatusBadge = match($p->status) {
                                    'in_progress' => ['badge-primary',  __('In progress')],
                                    'completed'   => ['badge-success',  __('Completed')],
                                    'paused'      => ['badge-warning',  __('Paused')],
                                    'planning'    => ['badge-ghost',    __('Planning')],
                                    default       => ['badge-ghost',    ucfirst($p->status)],
                                };
                            @endphp
                            <div class="flex items-center gap-3">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-0.5">
                                        <a href="{{ route('projects.dashboard', $p) }}"
                                           class="font-medium text-sm hover:text-primary transition-colors truncate" wire:navigate>
                                            {{ $p->name }}
                                        </a>
                                        <span class="badge badge-xs {{ $pStatusBadge[0] }} shrink-0">{{ $pStatusBadge[1] }}</span>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <progress class="progress progress-primary flex-1 h-1.5"
                                                  value="{{ round($avg) }}" max="100"></progress>
                                        <span class="text-xs text-gray-400 shrink-0 w-8 text-right">{{ round($avg) }}%</span>
                                    </div>
                                </div>
                                @if($p->pivot->role_in_project)
                                    <span class="badge badge-sm badge-outline shrink-0">{{ $p->pivot->role_in_project }}</span>
                                @endif
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
            @endif

            {{-- Company card --}}
            <div class="card bg-base-100 shadow">
                <div class="card-body p-5">
                    <h3 class="font-semibold text-sm mb-3 flex items-center gap-2">
                        <x-heroicon-o-identification class="w-4 h-4 text-primary" />
                        {{ __('Company details') }}
                    </h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-8 gap-y-2 text-sm">
                        @foreach([
                            [__('Tax ID'),     $company->tax_id],
                            [__('Type'),       $typeBadge[1]],
                            [__('Status'),     $estadoBadge[1]],
                            [__('Phone'),      $company->phone],
                            [__('Email'),      $company->email],
                            [__('Address'),    $company->address],
                            [__('Website'),    $company->website],
                        ] as [$label, $val])
                            @if($val)
                                <div class="flex gap-2 py-1.5 border-b border-base-200">
                                    <span class="text-gray-400 w-24 shrink-0">{{ $label }}</span>
                                    @if($label === __('Website'))
                                        <a href="{{ $val }}" target="_blank" rel="noopener"
                                           class="text-primary hover:underline truncate">{{ $val }}</a>
                                    @else
                                        <span class="font-medium truncate">{{ $val }}</span>
                                    @endif
                                </div>
                            @endif
                        @endforeach
                    </div>
                </div>
            </div>

        </div>
        @endif

    {{-- ════════════════════════════════════════════════════════════════════
         TAB: PERSONAS
    ════════════════════════════════════════════════════════════════════ --}}
    @if($activeTab === 'people')
    <div class="space-y-4">

        {{-- Acciones --}}
        <div class="flex flex-wrap gap-3">
            {{-- Crear nuevo usuario --}}
            <a href="{{ route('admin.users.create') }}"
               class="btn btn-primary btn-sm gap-1" wire:navigate>
                <x-heroicon-o-user-plus class="w-4 h-4" />
                Crear nuevo usuario
            </a>

            {{-- Asignar existente --}}
            @if($assignableUsers->isNotEmpty())
            <div class="flex items-center gap-2"
                 x-data="{ open: false }">
                <button @click="open = !open" class="btn btn-outline btn-sm gap-1">
                    <x-heroicon-o-link class="w-4 h-4" />
                    Asignar usuario existente
                </button>
                <div x-show="open" x-cloak class="flex items-center gap-2 flex-wrap">
                    <select wire:model="assignUserId" class="select select-bordered select-sm min-w-[200px]">
                        <option value="">— Seleccionar —</option>
                        @foreach($assignableUsers as $u)
                            <option value="{{ $u->id }}">
                                {{ $u->name }}
                                @if($u->company) (actual: {{ $u->company->apodo ?: $u->company->name }}) @endif
                            </option>
                        @endforeach
                    </select>
                    <button wire:click="assignUser" class="btn btn-primary btn-sm gap-1">
                        <x-heroicon-o-check class="w-4 h-4" />
                        Asignar
                    </button>
                    @error('assignUserId')
                        <p class="text-error text-xs">{{ $message }}</p>
                    @enderror
                </div>
            </div>
            @endif
        </div>

        {{-- Lista personas --}}
        @if($company->users->isEmpty())
            <div class="card bg-base-100 shadow">
                <div class="card-body items-center text-center py-10 text-gray-400">
                    <x-heroicon-o-users class="w-10 h-10 opacity-25 mb-2" />
                    <p class="text-sm">Ninguna persona asociada a esta empresa.</p>
                </div>
            </div>
        @else
            <div class="card bg-base-100 shadow overflow-x-auto">
                <table class="table table-zebra w-full">
                    <thead>
                        <tr>
                            <th>Persona</th>
                            <th>Rol</th>
                            <th>Estado</th>
                            <th>Contacto</th>
                            <th class="w-20"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($company->users as $u)
                            @php
                                $uStatusBadge = match($u->status ?? 'active') {
                                    'active'    => ['badge-success', 'Activo'],
                                    'inactive'  => ['badge-ghost',   'Inactivo'],
                                    'suspended' => ['badge-error',   'Suspendido'],
                                    default     => ['badge-ghost',   ucfirst($u->status ?? '')],
                                };
                            @endphp
                            <tr wire:key="user-{{ $u->id }}">
                                <td>
                                    <div class="flex items-center gap-3">
                                        <div class="avatar placeholder shrink-0">
                                            <div class="bg-neutral text-neutral-content rounded-full w-8">
                                                <span class="text-xs">
                                                    {{ strtoupper(substr($u->first_name ?: $u->name, 0, 1)) }}{{ strtoupper(substr($u->last_name ?: '', 0, 1)) }}
                                                </span>
                                            </div>
                                        </div>
                                        <div>
                                            <p class="font-semibold text-sm">
                                                @if($u->title) <span class="text-gray-400 font-normal">{{ $u->title }}</span> @endif
                                                {{ $u->first_name && $u->last_name
                                                    ? $u->first_name . ' ' . $u->last_name
                                                    : $u->name }}
                                            </p>
                                            <p class="text-xs text-gray-400">{{ $u->email }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="flex flex-wrap gap-1">
                                        @foreach($u->roles as $role)
                                            <span class="badge badge-xs {{ $role->name === 'Admin' ? 'badge-error' : 'badge-primary' }}">
                                                {{ $role->name }}
                                            </span>
                                        @endforeach
                                        @if($u->roles->isEmpty())
                                            <span class="badge badge-xs badge-ghost">Sin rol</span>
                                        @endif
                                    </div>
                                </td>
                                <td>
                                    <span class="badge badge-sm {{ $uStatusBadge[0] }}">{{ $uStatusBadge[1] }}</span>
                                </td>
                                <td class="text-xs text-gray-500">
                                    @if($u->phone) <div>{{ $u->phone }}</div> @endif
                                </td>
                                <td>
                                    <div class="flex justify-end gap-1">
                                        <a href="{{ route('admin.users.show', $u) }}"
                                           class="btn btn-xs btn-outline" title="Ver" wire:navigate>
                                            <x-heroicon-o-eye class="w-3.5 h-3.5" />
                                        </a>
                                        <button wire:click="removeUser({{ $u->id }})"
                                                wire:confirm="¿Desvincular a {{ $u->name }} de esta empresa?"
                                                class="btn btn-xs btn-outline btn-warning" title="Desvincular">
                                            <x-heroicon-o-link-slash class="w-3.5 h-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif

    </div>
    @endif

    {{-- ════════════════════════════════════════════════════════════════════
         TAB: PROYECTOS
    ════════════════════════════════════════════════════════════════════ --}}
    @if($activeTab === 'projects')
    <div class="space-y-4">

        {{-- Formulario asignar --}}
        <div class="card bg-base-100 shadow">
            <div class="card-body p-5">
                <h3 class="font-semibold text-sm mb-3 flex items-center gap-2">
                    <x-heroicon-o-plus-circle class="w-4 h-4 text-primary" />
                    Vincular a proyecto
                </h3>
                @if($availableProjects->isEmpty())
                    <p class="text-sm text-gray-400">La empresa ya está vinculada a todos los proyectos.</p>
                @else
                    <div class="flex flex-wrap items-end gap-3">
                        <div class="form-control flex-1 min-w-[200px]">
                            <label class="label-text text-xs mb-1">Proyecto</label>
                            <select wire:model="addProjectId" class="select select-bordered select-sm w-full">
                                <option value="">— Seleccionar —</option>
                                @foreach($availableProjects as $p)
                                    <option value="{{ $p->id }}">{{ $p->name }}</option>
                                @endforeach
                            </select>
                            @error('addProjectId') <p class="text-error text-xs mt-0.5">{{ $message }}</p> @enderror
                        </div>
                        <div class="form-control flex-1 min-w-[180px]">
                            <label class="label-text text-xs mb-1">
                                Rol en el proyecto <span class="text-error">*</span>
                            </label>
                            <input type="text" wire:model="addProjectRole"
                                   class="input input-bordered input-sm w-full"
                                   placeholder="ej: Constructor principal" />
                            @error('addProjectRole') <p class="text-error text-xs mt-0.5">{{ $message }}</p> @enderror
                        </div>
                        <button wire:click="assignProject" class="btn btn-primary btn-sm gap-1 shrink-0">
                            <x-heroicon-o-plus class="w-4 h-4" />
                            Vincular
                        </button>
                    </div>
                @endif
            </div>
        </div>

        {{-- Lista proyectos --}}
        @if($company->projects->isEmpty())
            <div class="card bg-base-100 shadow">
                <div class="card-body items-center text-center py-10 text-gray-400">
                    <x-heroicon-o-folder-open class="w-10 h-10 opacity-25 mb-2" />
                    <p class="text-sm">Sin proyectos vinculados.</p>
                </div>
            </div>
        @else
            <div class="card bg-base-100 shadow overflow-x-auto">
                <table class="table table-zebra w-full">
                    <thead>
                        <tr>
                            <th>Proyecto</th>
                            <th>Rol de la empresa</th>
                            <th>Estado</th>
                            <th>Progreso</th>
                            <th class="w-16"></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($company->projects as $project)
                            @php
                                $avg = $project->phases->avg('progress_percent') ?? 0;
                                $psCfg = match($project->status) {
                                    'in_progress' => ['badge-primary',  'En progreso'],
                                    'completed'   => ['badge-success',  'Completado'],
                                    'paused'      => ['badge-warning',  'Pausado'],
                                    'planning'    => ['badge-ghost',    'Planificación'],
                                    default       => ['badge-ghost',    ucfirst($project->status)],
                                };
                            @endphp
                            <tr wire:key="proj-{{ $project->id }}">
                                <td>
                                    <a href="{{ route('projects.dashboard', $project) }}"
                                       class="font-medium hover:text-primary transition-colors" wire:navigate>
                                        {{ $project->name }}
                                    </a>
                                    @if($project->address)
                                        <p class="text-xs text-gray-400 truncate max-w-[200px]">{{ $project->address }}</p>
                                    @endif
                                </td>
                                <td>
                                    <span class="badge badge-sm badge-outline">
                                        {{ $project->pivot->role_in_project }}
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-sm {{ $psCfg[0] }}">{{ $psCfg[1] }}</span>
                                </td>
                                <td>
                                    <div class="flex items-center gap-2">
                                        <progress class="progress progress-primary w-20 h-1.5"
                                                  value="{{ round($avg) }}" max="100"></progress>
                                        <span class="text-xs text-gray-500">{{ round($avg) }}%</span>
                                    </div>
                                </td>
                                <td>
                                    <button wire:click="removeProject({{ $project->id }})"
                                            wire:confirm="¿Desvincular a '{{ $company->name }}' del proyecto '{{ $project->name }}'?"
                                            class="btn btn-xs btn-outline btn-error" title="Desvincular">
                                        <x-heroicon-o-x-mark class="w-3.5 h-3.5" />
                                    </button>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @endif

    </div>
    @endif

    {{-- ════════════════════════════════════════════════════════════════════
         TAB: NOTAS
    ════════════════════════════════════════════════════════════════════ --}}
    @if($activeTab === 'notes')
    <div class="card bg-base-100 shadow max-w-2xl">
        <div class="card-body p-6">
            <div class="flex items-center justify-between mb-4">
                <h3 class="font-semibold text-base flex items-center gap-2">
                    <x-heroicon-o-document-text class="w-5 h-5 text-primary" />
                    Notas internas
                </h3>
                @if(!$editingNotes)
                    <button wire:click="$set('editingNotes', true)"
                            class="btn btn-sm btn-outline gap-1">
                        <x-heroicon-o-pencil class="w-3.5 h-3.5" />
                        Editar
                    </button>
                @endif
            </div>

            @if($editingNotes)
                <textarea wire:model="notes" rows="10"
                          class="textarea textarea-bordered w-full text-sm"
                          placeholder="Añade notas, historial de relación, condiciones contractuales, observaciones…"
                          autofocus></textarea>
                <div class="flex justify-end gap-2 mt-3">
                    <button wire:click="$set('editingNotes', false)"
                            class="btn btn-outline btn-sm">Cancelar</button>
                    <button wire:click="saveNotes"
                            class="btn btn-primary btn-sm gap-1">
                        <x-heroicon-o-check class="w-4 h-4" />
                        Guardar
                    </button>
                </div>
            @else
                @if($company->notes)
                    <div class="prose prose-sm max-w-none text-gray-700 whitespace-pre-line bg-base-200 rounded-lg p-4 min-h-[120px]">
                        {{ $company->notes }}
                    </div>
                @else
                    <div class="text-center py-12 text-gray-400">
                        <x-heroicon-o-document-text class="w-10 h-10 mx-auto opacity-25 mb-2" />
                        <p class="text-sm">Sin notas.</p>
                        <button wire:click="$set('editingNotes', true)"
                                class="btn btn-sm btn-outline mt-3 gap-1">
                            <x-heroicon-o-plus class="w-4 h-4" />
                            Añadir nota
                        </button>
                    </div>
                @endif
            @endif
        </div>
    </div>
    @endif

</div>
</div>
</div>
