@extends('clientarea.profile.layout')

@section('profile-content')
<div class="card">
    <div class="card-header">
        <h5 class="mb-0">{{ __('store.clientarea_profile_navigation_authorized_accounts') }}</h5>
    </div>
    <div class="card-body">
        <div class="row mb-4">
            <div class="col-md-8">
                <p class="text-muted mb-0">{{ __('store.clientarea_profile_authorized_accounts_description') }}</p>
            </div>
            <div class="col-md-4 text-end">
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#inviteModal">
                    <i class="fas fa-plus me-2"></i>{{ __('store.clientarea_profile_authorized_accounts_invite_user') }}
                </button>
            </div>
        </div>

        @if($authorizedAccounts && $authorizedAccounts->count() > 0)
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>{{ __('store.clientarea_profile_authorized_accounts_user') }}</th>
                            <th>{{ __('store.clientarea_profile_authorized_accounts_permissions') }}</th>
                            <th>{{ __('store.clientarea_profile_authorized_accounts_status') }}</th>
                            <th>{{ __('store.clientarea_profile_authorized_accounts_invited_date') }}</th>
                            <th width="100">{{ __('store.buttons_actions') }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($authorizedAccounts as $account)
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm bg-primary rounded-circle d-flex align-items-center justify-content-center text-white me-3">
                                            {{ strtoupper(substr($account->email, 0, 1)) }}
                                        </div>
                                        <div>
                                            <div class="fw-medium">{{ $account->name ?? $account->email }}</div>
                                            <small class="text-muted">{{ $account->email }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    @foreach($account->permissions ?? [] as $permission)
                                        @php
                                            $permissionkey = $permission;
                                            $permissionid = null;
                                            if (preg_match('/^(.*)_(\d+)$/', $permission, $matches)) {
                                                $permissionkey = $matches[1];
                                                $permissionid = $matches[2];
                                            }
                                        @endphp

                                        <span class="badge bg-info text-dark me-1">
                                            {{ __('store.clientarea_profile_authorized_accounts_' . $permissionkey) }}
                                            @if($permissionid > 0) #{{ $permissionid }} @endif
                                        </span>
                                    @endforeach

                                </td>
                                <td>
                                    @if($account->status === 'active')
                                        <span class="badge bg-success">{{ __('store.clientarea_profile_authorized_accounts_active') }}</span>
                                    @elseif($account->status === 'pending')
                                        <span class="badge bg-warning">{{ __('store.clientarea_profile_authorized_accounts_pending') }}</span>
                                    @else
                                        <span class="badge bg-secondary">{{ __('store.clientarea_profile_authorized_accounts_inactive') }}</span>
                                    @endif
                                </td>
                                <td>{{ $account->created_at?->format($dateFormat) }}</td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                                            <i class="fas fa-ellipsis-v"></i>
                                        </button>
                                        <ul class="dropdown-menu">
                                            @if($account->status === 'active')
                                            <li>
                                                <button class="dropdown-item" onclick="editAccountPermissions({{ $account->id }}, {{ json_encode($account->permissions ?? []) }}, '{{ $account->name ?? $account->email }}')">
                                                    <i class="fas fa-edit me-2"></i>{{ __('store.buttons_edit') }}
                                                </button>
                                            </li>
                                            <li>
                                                <button class="dropdown-item" onclick="editAccountEmailPrefs({{ $account->id }}, {{ json_encode($account->email_preferences ?? []) }}, '{{ $account->name ?? $account->email }}')">
                                                    <i class="fas fa-envelope me-2"></i>{{ __('store.authorized_email_preferences_edit') }}
                                                </button>
                                            </li>
                                            @endif
                                            <li>
                                                <button class="dropdown-item text-danger" onclick="removeAccount({{ $account->id }})">
                                                    <i class="fas fa-trash me-2"></i>{{ __('store.buttons_remove') }}
                                                </button>
                                            </li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @else
            <div class="text-center py-5">
                <i class="fas fa-users-slash fa-3x text-muted mb-3"></i>
                <h5>{{ __('store.clientarea_profile_authorized_accounts_no_accounts') }}</h5>
                <p class="text-muted">{{ __('store.clientarea_profile_authorized_accounts_no_accounts_description') }}</p>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#inviteModal">
                    <i class="fas fa-plus me-2"></i>{{ __('store.clientarea_profile_authorized_accounts_invite_first_user') }}
                </button>
            </div>
        @endif
    </div>
</div>

<!-- Invite Modal -->
<div class="modal fade" id="inviteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" action="{{ route('store.auth.profile.authorized-accounts.invite') }}">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title">{{ __('store.clientarea_profile_authorized_accounts_invite_user') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="email" class="form-label">{{ __('store.auth_email') }} <span class="text-danger">*</span></label>
                        <input type="email" class="form-control @error('email') is-invalid @enderror" id="email" name="email" required>
                        @error('email')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>

                    
                    <div class="mb-3" data-preset-scope="invite">
                        <label class="form-label small text-muted">{{ __('store.authorized_preset_title') }}</label>
                        <div class="btn-group btn-group-sm d-flex flex-wrap" role="group">
                            @foreach(\App\Enums\ClientPermissionPreset::all() as $preset)
                                <button type="button"
                                        class="btn btn-outline-primary apply-preset"
                                        data-preset="{{ $preset }}"
                                        data-scope="invite"
                                        title="{{ \App\Enums\ClientPermissionPreset::getDescription($preset) }}">
                                    {{ \App\Enums\ClientPermissionPreset::getLabel($preset) }}
                                </button>
                            @endforeach
                        </div>
                        <small class="text-muted d-block mt-1">{{ __('store.authorized_preset_hint') }}</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{{ __('store.clientarea_profile_authorized_accounts_permissions') }} <span class="text-danger">*</span></label>

                        <!-- Navigation Tabs -->
                        <ul class="nav nav-tabs mb-3" id="permissionTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="basic-tab" data-bs-toggle="tab" data-bs-target="#basic-permissions" type="button" role="tab">
                                    <i class="fas fa-list-ul me-1"></i>Temel Yetkiler
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="granular-tab" data-bs-toggle="tab" data-bs-target="#granular-permissions" type="button" role="tab">
                                    <i class="fas fa-cogs me-1"></i>Detaylı Yetkiler
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content" id="permissionTabContent">
                            <!-- Basic Permissions Tab -->
                            <div class="tab-pane fade show active" id="basic-permissions" role="tabpanel">
                                @php
                                    $permissionGroups = \App\Enums\ClientPermission::getPermissionGroups();
                                @endphp

                                @foreach($permissionGroups as $groupKey => $group)
                                    <div class="card border-0  mb-3">
                                        <div class="card-body py-2">
                                            <h6 class="card-title mb-2">{{ $group['label'] }}</h6>
                                            @foreach($group['permissions'] as $permission => $label)
                                                <div class="form-check">
                                                    <input class="form-check-input basic-permission" type="checkbox" name="permissions[]"
                                                           value="{{ $permission }}" id="perm_{{ $permission }}"
                                                           @if($permission === 'view_dashboard') checked disabled @endif>
                                                    <label class="form-check-label" for="perm_{{ $permission }}">
                                                        {{ $label }}
                                                        @if($permission === 'view_dashboard')
                                                            <small class="text-muted">(Otomatik dahil)</small>
                                                        @endif
                                                    </label>
                                                </div>
                                            @endforeach
                                        </div>
                                    </div>
                                @endforeach
                            </div>

                            <!-- Granular Permissions Tab -->
                            <div class="tab-pane fade" id="granular-permissions" role="tabpanel">
                                @php
                                    $availablePermissions = \App\Enums\ClientPermissionGranular::getAvailablePermissions(auth('client')->id());
                                @endphp

                                @if(!empty($availablePermissions['services']))
                                <div class="card border-0  mb-3">
                                    <div class="card-body">
                                        <h6 class="card-title">
                                            <i class="fas fa-server me-2"></i>Ürünler/Hizmetler - Spesifik Yetkiler
                                        </h6>
                                        <div class="row">
                                            @foreach($availablePermissions['services'] as $service)
                                            <div class="col-md-6 mb-3">
                                                <div class="border rounded p-3">
                                                    <h6 class="mb-2">{{ $service['name'] }}</h6>
                                                    <small class="text-muted d-block mb-2">{{ $service['description'] }}</small>

                                                    <div class="form-check">
                                                        <input class="form-check-input granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $service['view_permission'] }}"
                                                               id="perm_{{ $service['view_permission'] }}">
                                                        <label class="form-check-label" for="perm_{{ $service['view_permission'] }}">
                                                            <i class="fas fa-eye me-1"></i>Görüntüle
                                                        </label>
                                                    </div>

                                                    <div class="form-check">
                                                        <input class="form-check-input granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $service['manage_permission'] }}"
                                                               id="perm_{{ $service['manage_permission'] }}">
                                                        <label class="form-check-label" for="perm_{{ $service['manage_permission'] }}">
                                                            <i class="fas fa-cog me-1"></i>Yönet
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                                @endif

                                @if(!empty($availablePermissions['domains']))
                                <div class="card border-0  mb-3">
                                    <div class="card-body">
                                        <h6 class="card-title">
                                            <i class="fas fa-globe me-2"></i>Domainler - Spesifik Yetkiler
                                        </h6>
                                        <div class="row">
                                            @foreach($availablePermissions['domains'] as $domain)
                                            <div class="col-md-6 mb-3">
                                                <div class="border rounded p-3">
                                                    <h6 class="mb-2">{{ $domain['name'] }}</h6>
                                                    <small class="text-muted d-block mb-2">{{ $domain['description'] }}</small>

                                                    <div class="form-check">
                                                        <input class="form-check-input granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $domain['view_permission'] }}"
                                                               id="perm_{{ $domain['view_permission'] }}">
                                                        <label class="form-check-label" for="perm_{{ $domain['view_permission'] }}">
                                                            <i class="fas fa-eye me-1"></i>Görüntüle
                                                        </label>
                                                    </div>

                                                    <div class="form-check">
                                                        <input class="form-check-input granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $domain['manage_permission'] }}"
                                                               id="perm_{{ $domain['manage_permission'] }}">
                                                        <label class="form-check-label" for="perm_{{ $domain['manage_permission'] }}">
                                                            <i class="fas fa-cog me-1"></i>Yönet
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                                @endif

                                @if(empty($availablePermissions['services']) && empty($availablePermissions['domains']))
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    Bu hesapta henüz ürün veya domain bulunmuyor. Detaylı yetkiler için önce sipariş oluşturmanız gerekiyor.
                                </div>
                                @endif
                            </div>
                        </div>

                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>{{ __('store.clientarea_profile_important') }}:</strong>
                            <ul class="mb-0 mt-2">
                                <li><strong>{{ __('store.clientarea_profile_basic_permissions') }}:</strong> {{ __('store.clientarea_profile_all_products_domains') }}</li>
                                <li><strong>{{ __('store.clientarea_profile_detailed_permissions') }}:</strong> {{ __('store.clientarea_profile_selected_only') }}</li>
                                <li><strong>{{ __('store.clientarea_profile_profile_edit_order') }}</strong> {{ __('store.clientarea_profile_auto_restricted') }}</li>
                            </ul>
                        </div>

                        @error('permissions')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                        @enderror
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('store.buttons_cancel') }}</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-paper-plane me-2"></i>{{ __('store.clientarea_profile_authorized_accounts_send_invitation') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Permissions Modal -->
<div class="modal fade" id="editPermissionsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="editPermissionsForm">
                @csrf
                @method('PUT')
                <div class="modal-header">
                    <h5 class="modal-title">{{ __('store.clientarea_profile_authorized_accounts_edit_permissions') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">{{ __('store.clientarea_profile_authorized_accounts_user') }}</label>
                        <input type="text" class="form-control" id="editUserName" readonly>
                    </div>

                    
                    <div class="mb-3" data-preset-scope="edit">
                        <label class="form-label small text-muted">{{ __('store.authorized_preset_title') }}</label>
                        <div class="btn-group btn-group-sm d-flex flex-wrap" role="group">
                            @foreach(\App\Enums\ClientPermissionPreset::all() as $preset)
                                <button type="button"
                                        class="btn btn-outline-primary apply-preset"
                                        data-preset="{{ $preset }}"
                                        data-scope="edit"
                                        title="{{ \App\Enums\ClientPermissionPreset::getDescription($preset) }}">
                                    {{ \App\Enums\ClientPermissionPreset::getLabel($preset) }}
                                </button>
                            @endforeach
                        </div>
                        <small class="text-muted d-block mt-1">{{ __('store.authorized_preset_hint') }}</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">{{ __('store.clientarea_profile_authorized_accounts_permissions') }} <span class="text-danger">*</span></label>

                        <!-- Navigation Tabs -->
                        <ul class="nav nav-tabs mb-3" id="editPermissionTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="edit-basic-tab" data-bs-toggle="tab" data-bs-target="#edit-basic-permissions" type="button" role="tab">
                                    <i class="fas fa-list-ul me-1"></i>Temel Yetkiler
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="edit-granular-tab" data-bs-toggle="tab" data-bs-target="#edit-granular-permissions" type="button" role="tab">
                                    <i class="fas fa-cogs me-1"></i>Detaylı Yetkiler
                                </button>
                            </li>
                        </ul>

                        <div class="tab-content" id="editPermissionTabContent">
                            <!-- Basic Permissions Tab -->
                            <div class="tab-pane fade show active" id="edit-basic-permissions" role="tabpanel">
                                @php
                                    $permissionGroups = \App\Enums\ClientPermission::getPermissionGroups();
                                @endphp

                                @foreach($permissionGroups as $groupKey => $group)
                                    <div class="card border-0 mb-3">
                                        <div class="card-body py-2">
                                            <h6 class="card-title mb-2">{{ $group['label'] }}</h6>
                                            @foreach($group['permissions'] as $permission => $label)
                                                <div class="form-check">
                                                    <input class="form-check-input edit-basic-permission" type="checkbox" name="permissions[]"
                                                           value="{{ $permission }}" id="edit_perm_{{ $permission }}"
                                                           @if($permission === 'view_dashboard') checked disabled @endif>
                                                    <label class="form-check-label" for="edit_perm_{{ $permission }}">
                                                        {{ $label }}
                                                        @if($permission === 'view_dashboard')
                                                            <small class="text-muted">(Otomatik dahil)</small>
                                                        @endif
                                                    </label>
                                                </div>
                                            @endforeach
                                        </div>
                                    </div>
                                @endforeach
                            </div>

                            <!-- Granular Permissions Tab -->
                            <div class="tab-pane fade" id="edit-granular-permissions" role="tabpanel">
                                @php
                                    $availablePermissions = \App\Enums\ClientPermissionGranular::getAvailablePermissions(auth('client')->id());
                                @endphp

                                @if(!empty($availablePermissions['services']))
                                <div class="card border-0 mb-3">
                                    <div class="card-body">
                                        <h6 class="card-title">
                                            <i class="fas fa-server me-2"></i>Ürünler/Hizmetler - Spesifik Yetkiler
                                        </h6>
                                        <div class="row">
                                            @foreach($availablePermissions['services'] as $service)
                                            <div class="col-md-6 mb-3">
                                                <div class="border rounded p-3">
                                                    <h6 class="mb-2">{{ $service['name'] }}</h6>
                                                    <small class="text-muted d-block mb-2">{{ $service['description'] }}</small>

                                                    <div class="form-check">
                                                        <input class="form-check-input edit-granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $service['view_permission'] }}"
                                                               id="edit_perm_{{ $service['view_permission'] }}">
                                                        <label class="form-check-label" for="edit_perm_{{ $service['view_permission'] }}">
                                                            <i class="fas fa-eye me-1"></i>Görüntüle
                                                        </label>
                                                    </div>

                                                    <div class="form-check">
                                                        <input class="form-check-input edit-granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $service['manage_permission'] }}"
                                                               id="edit_perm_{{ $service['manage_permission'] }}">
                                                        <label class="form-check-label" for="edit_perm_{{ $service['manage_permission'] }}">
                                                            <i class="fas fa-cog me-1"></i>Yönet
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                                @endif

                                @if(!empty($availablePermissions['domains']))
                                <div class="card border-0 mb-3">
                                    <div class="card-body">
                                        <h6 class="card-title">
                                            <i class="fas fa-globe me-2"></i>Domainler - Spesifik Yetkiler
                                        </h6>
                                        <div class="row">
                                            @foreach($availablePermissions['domains'] as $domain)
                                            <div class="col-md-6 mb-3">
                                                <div class="border rounded p-3">
                                                    <h6 class="mb-2">{{ $domain['name'] }}</h6>
                                                    <small class="text-muted d-block mb-2">{{ $domain['description'] }}</small>

                                                    <div class="form-check">
                                                        <input class="form-check-input edit-granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $domain['view_permission'] }}"
                                                               id="edit_perm_{{ $domain['view_permission'] }}">
                                                        <label class="form-check-label" for="edit_perm_{{ $domain['view_permission'] }}">
                                                            <i class="fas fa-eye me-1"></i>Görüntüle
                                                        </label>
                                                    </div>

                                                    <div class="form-check">
                                                        <input class="form-check-input edit-granular-permission" type="checkbox"
                                                               name="permissions[]" value="{{ $domain['manage_permission'] }}"
                                                               id="edit_perm_{{ $domain['manage_permission'] }}">
                                                        <label class="form-check-label" for="edit_perm_{{ $domain['manage_permission'] }}">
                                                            <i class="fas fa-cog me-1"></i>Yönet
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                                @endif

                                @if(empty($availablePermissions['services']) && empty($availablePermissions['domains']))
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    Bu hesapta henüz ürün veya domain bulunmuyor. Detaylı yetkiler için önce sipariş oluşturmanız gerekiyor.
                                </div>
                                @endif
                            </div>
                        </div>

                        <div class="alert alert-warning mt-3">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <strong>{{ __('store.clientarea_profile_important') }}:</strong>
                            <ul class="mb-0 mt-2">
                                <li><strong>{{ __('store.clientarea_profile_basic_permissions') }}:</strong> {{ __('store.clientarea_profile_all_products_domains') }}</li>
                                <li><strong>{{ __('store.clientarea_profile_detailed_permissions') }}:</strong> {{ __('store.clientarea_profile_selected_only') }}</li>
                                <li><strong>{{ __('store.clientarea_profile_profile_edit_order') }}</strong> {{ __('store.clientarea_profile_auto_restricted') }}</li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('store.buttons_cancel') }}</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>{{ __('store.buttons_save') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>


<div class="modal fade" id="emailPrefsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST" id="emailPrefsForm">
                @csrf
                @method('PUT')
                <div class="modal-header">
                    <h5 class="modal-title">{{ __('store.authorized_email_preferences_title') }}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">{{ __('store.clientarea_profile_authorized_accounts_user') }}</label>
                        <input type="text" class="form-control" id="emailPrefsUserName" readonly>
                    </div>

                    <p class="text-muted small mb-3" id="emailPrefsDescription">
                        {{ __('store.authorized_email_preferences_description') }}
                    </p>

                    @foreach(config('authorized_notifications.user_editable_categories', []) as $category)
                        <div class="form-check mb-2">
                            <input class="form-check-input email-pref-checkbox"
                                   type="checkbox"
                                   name="preferences[{{ $category }}]"
                                   id="pref_{{ $category }}"
                                   value="1"
                                   data-category="{{ $category }}">
                            <label class="form-check-label" for="pref_{{ $category }}">
                                <strong>{{ __('store.authorized_email_category_' . $category) }}</strong>
                                <small class="d-block text-muted">{{ __('store.authorized_email_category_' . $category . '_desc') }}</small>
                            </label>
                        </div>
                    @endforeach
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{{ __('store.buttons_cancel') }}</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>{{ __('store.authorized_email_preferences_save') }}
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('profile-scripts')
<script>
window.permissionPresets = @json(\App\Enums\ClientPermissionPreset::forJs());
</script>
@vite('resources/js/store/authorized-accounts-presets.js')
<script>
function removeAccount(accountId) {
    if (confirm('{{ __("store.clientarea_profile_authorized_accounts_confirm_remove") }}')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `{{ route('store.auth.profile.authorized-accounts.remove', ':id') }}`.replace(':id', accountId);

        const csrfToken = document.createElement('input');
        csrfToken.type = 'hidden';
        csrfToken.name = '_token';
        csrfToken.value = '{{ csrf_token() }}';

        const methodInput = document.createElement('input');
        methodInput.type = 'hidden';
        methodInput.name = '_method';
        methodInput.value = 'DELETE';

        form.appendChild(csrfToken);
        form.appendChild(methodInput);
        document.body.appendChild(form);
        form.submit();
    }
}

function editAccountPermissions(accountId, currentPermissions, userName) {
    // Set form action
    const form = document.getElementById('editPermissionsForm');
    form.action = `{{ route('store.auth.profile.authorized-accounts.update-permissions', ':id') }}`.replace(':id', accountId);

    // Set user name
    document.getElementById('editUserName').value = userName;

    // Uncheck all permissions first
    document.querySelectorAll('.edit-basic-permission:not([disabled])').forEach(checkbox => {
        checkbox.checked = false;
    });
    document.querySelectorAll('.edit-granular-permission').forEach(checkbox => {
        checkbox.checked = false;
    });

    // Check current permissions
    currentPermissions.forEach(permission => {
        const checkbox = document.getElementById('edit_perm_' + permission);
        if (checkbox && !checkbox.disabled) {
            checkbox.checked = true;
        }
    });

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('editPermissionsModal'));
    modal.show();
}

/**
 * Open the owner-side email preferences modal.
 */
function editAccountEmailPrefs(authorizationId, currentPrefs, userName) {
    const form = document.getElementById('emailPrefsForm');
    form.action = `{{ route('store.auth.profile.authorized-accounts.email-preferences', ':id') }}`.replace(':id', authorizationId);

    document.getElementById('emailPrefsUserName').value = userName;
    document.getElementById('emailPrefsDescription').textContent = `{{ __('store.authorized_email_preferences_description') }}`;

    document.querySelectorAll('.email-pref-checkbox').forEach(cb => {
        const cat = cb.getAttribute('data-category');
        cb.checked = currentPrefs && currentPrefs[cat] === true;
    });

    const modal = new bootstrap.Modal(document.getElementById('emailPrefsModal'));
    modal.show();
}
</script>
@endpush
