@extends('layouts.app')

@section('title', 'Add role')
@section('heading', 'Create custom role')

@section('content')
    <div
        class="space-y-6"
        x-data="{
            search: '',
            permVisible(p) {
                const q = (this.search || '').trim().toLowerCase();
                if (!q) return true;
                return (p.name || '').toLowerCase().includes(q) || (p.d || '').toLowerCase().includes(q);
            },
            groupVisible(items) {
                if (!this.search.trim()) return true;
                return items.some(p => this.permVisible(p));
            },
            setAll(root, on) {
                if (!root) return;
                root.querySelectorAll('input[name=\'permission_ids[]\']').forEach(c => { c.checked = on; });
            },
            countSelected(root) {
                if (!root) return 0;
                return root.querySelectorAll('input[name=\'permission_ids[]\']:checked').length;
            },
            countAll(root) {
                if (!root) return 0;
                return root.querySelectorAll('input[name=\'permission_ids[]\']').length;
            }
        }"
    >
        <div class="flex flex-wrap items-center justify-between gap-3">
            <a href="{{ route('tenant-roles.index') }}" class="inline-flex items-center gap-2 text-sm font-medium text-slate-600 hover:text-slate-900">
                <i class="bi bi-arrow-left"></i>
                Back to roles
            </a>
        </div>

        <form method="post" action="{{ route('tenant-roles.store') }}" class="space-y-6">
            @csrf

            <x-card>
                <div class="mb-6 border-b border-slate-100 pb-4">
                    <h2 class="text-lg font-semibold text-slate-900">Role details</h2>
                    <p class="mt-1 text-sm text-slate-500">Give this role a clear name. The slug is a short code used in the app; the display name is what people see when assigning a role to employees.</p>
                </div>
                <div class="grid gap-6 sm:grid-cols-2">
                    <div class="sm:col-span-2">
                        <label class="mb-1.5 flex items-center gap-2 text-sm font-medium text-slate-800">
                            <i class="bi bi-person-badge text-slate-500"></i>
                            Display name
                            <span class="text-red-500" title="Required">*</span>
                        </label>
                        <input
                            type="text"
                            name="display_name"
                            value="{{ old('display_name') }}"
                            required
                            placeholder="e.g. Team lead, Store manager"
                            class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-sm shadow-sm focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-200"
                        />
                        @error('display_name')<p class="mt-1.5 text-sm text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div>
                        <label class="mb-1.5 flex items-center gap-2 text-sm font-medium text-slate-800">
                            <i class="bi bi-code-slash text-slate-500"></i>
                            Slug
                            <span class="text-red-500">*</span>
                        </label>
                        <input
                            type="text"
                            name="name"
                            value="{{ old('name') }}"
                            required
                            pattern="[a-z0-9]([a-z0-9_-]*[a-z0-9])?"
                            title="Use lowercase letters, numbers, single hyphens or underscores"
                            placeholder="e.g. team_lead"
                            class="w-full rounded-xl border border-slate-200 px-4 py-2.5 font-mono text-sm shadow-sm focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-200"
                        />
                        <p class="mt-1.5 text-xs text-slate-500">No spaces. These names are reserved: <span class="font-mono text-slate-700">admin</span>, <span class="font-mono text-slate-700">hr</span>, <span class="font-mono text-slate-700">manager</span>, <span class="font-mono text-slate-700">employee</span>.</p>
                        @error('name')<p class="mt-1.5 text-sm text-red-600">{{ $message }}</p>@enderror
                    </div>
                    <div>
                        <label class="mb-1.5 flex items-center gap-2 text-sm font-medium text-slate-800">
                            <i class="bi bi-card-text text-slate-500"></i>
                            Description
                            <span class="text-xs font-normal text-slate-400">(optional)</span>
                        </label>
                        <input
                            type="text"
                            name="description"
                            value="{{ old('description') }}"
                            placeholder="What is this role for?"
                            class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-sm shadow-sm focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-200"
                        />
                    </div>
                </div>
            </x-card>

            <x-card>
                <div class="mb-4 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
                    <div>
                        <h2 class="text-lg font-semibold text-slate-900">What can this role do?</h2>
                        <p class="mt-1 text-sm text-slate-500">Tick the actions this role is allowed to perform. Search filters the list; empty groups hide while searching.</p>
                    </div>
                    <div class="relative w-full sm:max-w-sm">
                        <i class="bi bi-search pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"></i>
                        <input
                            type="search"
                            x-model="search"
                            placeholder="Search permissions…"
                            class="w-full rounded-xl border border-slate-200 py-2.5 pl-10 pr-3 text-sm shadow-sm focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-200"
                            autocomplete="off"
                        />
                    </div>
                </div>

                <p class="mb-4 flex gap-2 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-950">
                    <i class="bi bi-lightbulb mt-0.5 shrink-0 text-amber-600"></i>
                    <span>Tip: subscription plans can still block a module, even if you grant permission here. Users only need the access that matches their job.</span>
                </p>

                <div class="space-y-3">
                    @foreach($roleGroups as $g)
                        <div
                            class="overflow-hidden rounded-xl border border-slate-200 bg-slate-50/40 shadow-sm"
                            x-show="groupVisible(@js($g['items']))"
                        >
                            <div class="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200/80 bg-white px-4 py-3 sm:px-4">
                                <div class="flex min-w-0 items-center gap-2.5">
                                    <span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-indigo-100 text-indigo-700">
                                        <i class="bi {{ $g['icon'] }} text-lg"></i>
                                    </span>
                                    <div class="min-w-0">
                                        <h3 class="text-sm font-semibold text-slate-900">{{ $g['label'] }}</h3>
                                        <p class="text-xs text-slate-500" x-show="!search.trim()">{{ count($g['items']) }} permission(s)</p>
                                    </div>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span class="hidden text-xs text-slate-500 sm:inline" x-show="!search.trim()" x-text="countSelected($refs.pg_{{ $g['key'] }}) + ' / ' + countAll($refs.pg_{{ $g['key'] }}) + ' selected'"></span>
                                    <button
                                        type="button"
                                        class="rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-800 hover:bg-slate-50"
                                        @click="setAll($refs.pg_{{ $g['key'] }}, true)"
                                    >All</button>
                                    <button
                                        type="button"
                                        class="rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-800 hover:bg-slate-50"
                                        @click="setAll($refs.pg_{{ $g['key'] }}, false)"
                                    >None</button>
                                </div>
                            </div>
                            <div class="bg-white p-3 sm:p-4" x-ref="pg_{{ $g['key'] }}">
                                <ul class="grid gap-0.5 sm:grid-cols-2">
                                    @foreach($g['items'] as $item)
                                        <li
                                            class="list-none"
                                            x-show="permVisible(@js($item))"
                                        >
                                            <label class="flex cursor-pointer items-start gap-3 rounded-lg p-2.5 transition hover:bg-slate-50 has-[:checked]:bg-indigo-50/80">
                                                <input
                                                    type="checkbox"
                                                    name="permission_ids[]"
                                                    value="{{ $item['id'] }}"
                                                    @checked(in_array($item['id'], old('permission_ids', []), true))
                                                    class="mt-0.5 h-4 w-4 rounded border-slate-300 text-indigo-600 focus:ring-indigo-500"
                                                />
                                                <span class="min-w-0">
                                                    <span class="block text-sm font-medium text-slate-900">{{ $item['d'] }}</span>
                                                    <span class="mt-0.5 block break-all font-mono text-xs text-slate-500">{{ $item['name'] }}</span>
                                                </span>
                                            </label>
                                        </li>
                                    @endforeach
                                </ul>
                            </div>
                        </div>
                    @endforeach
                </div>
            </x-card>

            <div class="flex flex-wrap items-center gap-3 border-t border-slate-200 pt-2">
                <button type="submit" class="inline-flex items-center gap-2 rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800">
                    <i class="bi bi-check-lg"></i>
                    Create role
                </button>
                <a href="{{ route('tenant-roles.index') }}" class="rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-sm font-medium text-slate-800 hover:bg-slate-50">Cancel</a>
            </div>
        </form>
    </div>
@endsection
