@extends('layouts.app') {{-- Assuming 'layouts.app' is your main layout --}}
@php($prefix = auth()->user()->role === 'admin' ? 'admin.' : 'user.')

@section('content')
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('Devices') }}
        </h2>
    </x-slot>

    <section class="p-4 md:p-6">
        <div class="flex flex-col md:flex-row w-full justify-between items-start md:items-center mb-6">
            <div class="mb-4 md:mb-0">
                <h1 class="text-2xl font-bold text-gray-800 dark:text-gray-100">Your Devices</h1>
            </div>
            <div class="w-full md:w-auto flex flex-col md:flex-row gap-2">
                <button x-data="" x-on:click.prevent="$dispatch('open-modal', 'confirm-device-add')" class="inline-flex items-center px-4 py-2 bg-gray-800 dark:bg-gray-200 border border-transparent rounded-md font-semibold text-xs text-white dark:text-gray-800 uppercase tracking-widest hover:bg-gray-700 dark:hover:bg-white focus:bg-gray-700 dark:focus:bg-white active:bg-gray-900 dark:active:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                    <span class="fas fa-plus mr-2"></span>
                    {{ __('Add new Device') }}
                </button>
            </div>
        </div>

        @if (session('success'))
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline">{{ session('success') }}</span>
            </div>
        @endif
        @if (session('error'))
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline">{{ session('error') }}</span>
            </div>
        @endif

        <div class="grid grid-cols-1 gap-6">
            @forelse($devices as $device)
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4">
                    <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                        <div class="flex-grow">
                            <div class="flex items-center gap-3">
                                <span class="text-blue-500 dark:text-blue-400 text-lg font-semibold">{{ $device->name }}</span>
                                <small
                                    class="bg-green-100 text-green-800 text-xs font-medium px-2 py-0.5 rounded-full dark:bg-green-900/50 dark:text-green-300">Active</small>
                            </div>
                            <div class="mt-2 flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400">
                                <span>{{ $device->device_type ?? 'Unknown Device' }}</span>
                                <span>&bull;</span>
                                <span>{{ $device->name ?? 'Unknown Browser' }}</span>
                                <span>&bull;</span>
                                <span>Last activity: {{ $device->last_activity ? $device->last_activity->diffForHumans() : 'N/A' }}</span>
                            </div>
                            <div class="flex mt-3">
                                <input readonly type="text" id="device-token-{{$device->id}}"
                                    class="flex-grow px-3 py-2 border border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-900 text-gray-900 dark:text-gray-300 rounded-l-md text-to-clipboard"
                                    value="{{ $device->session_id }}">
                                <button
                                    class="bg-gray-100 dark:bg-gray-700 border border-l-0 border-gray-300 dark:border-gray-600 rounded-r-md px-3 py-2 my-copy-btn cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
                                    data-copy-target="#device-token-{{$device->id}}">
                                    <i class="fas fa-copy text-gray-600 dark:text-gray-300"></i>
                                </button>
                            </div>
                        </div>
                        <div class="mt-4 md:mt-0 md:ml-6 flex-shrink-0">
                            <form action="{{ route($prefix . 'devices.revoke', $device->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to revoke this device?');">
                                @csrf
                                @method('DELETE')
                                <x-danger-button type="submit">
                                    <i class="fas fa-trash-alt mr-2"></i>
                                    Revoke
                                </x-danger-button>
                            </form>
                        </div>
                    </div>
                </div>
            @empty
                <div
                    class="col-span-full bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-4 text-center">
                    <p class="text-gray-600 dark:text-gray-400">You haven't registered any devices yet.</p>
                </div>
            @endforelse
        </div>
    </section>

    <!-- Toast notification (hidden by default) -->
    <div id="toast" class="hidden fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded-md shadow-lg z-50">
        Device Key Copied Successfully
    </div>

    <x-modal name="confirm-device-add" focusable>
        <form method="post" action="{{ route($prefix . 'devices.add') }}" class="p-6">
            @csrf
            <input type="hidden" name="force_create" value="1">

            <h2 class="text-lg font-medium text-gray-900 dark:text-gray-100">
                {{ __('Register a name for this device') }}
            </h2>

            <p class="mt-1 text-sm text-gray-600 dark:text-gray-400">
                {{ __('Give your current device a recognizable name to easily manage it later.') }}
            </p>

            <div class="mt-6">
                <x-input-label for="device_name" value="{{ __('Device Name') }}" class="sr-only" />

                <x-text-input id="device_name" name="device_name" class="mt-1 block w-3/4"
                    placeholder="{{ __('e.g. My Jadu PC') }}" />

                <x-input-error :messages="$errors->get('device_name')" class="mt-2" />
            </div>

            <div class="mt-6 flex justify-end">
                <x-secondary-button x-on:click="$dispatch('close')">
                    {{ __('Cancel') }}
                </x-secondary-button>

                <x-primary-button class="ml-3">
                    {{ __('Register Device') }}
                </x-primary-button>
            </div>
        </form>
    </x-modal>

    @push('scripts')
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                // Copy to clipboard functionality
                document.querySelectorAll('.my-copy-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        // Determine the target input for copying
                        let input;
                        if (this.dataset.copyTarget) {
                            input = document.querySelector(this.dataset.copyTarget);
                        } else {
                            // Fallback for existing device list items
                            input = this.previousElementSibling;
                        }
                        const value = input.value;

                        // Copy to clipboard
                        navigator.clipboard.writeText(value).then(() => {
                            // Show toast notification
                            const toast = document.getElementById('toast');
                            toast.classList.remove('hidden');

                            // Hide toast after 3 seconds
                            setTimeout(() => {
                                toast.classList.add('hidden');
                            }, 3000);
                        }).catch(err => {
                            console.error('Failed to copy: ', err);
                        });
                    });
                });
            });
        </script>
    @endpush
@endsection
