<?php

use Livewire\Component;
use App\Models\User;
use App\Models\Account;
use App\Models\Profile;
use App\Models\Admin;
use App\Models\Transaction;
use App\Models\UserEmail;
use Livewire\WithFileUploads;
use App\Notifications\EmailUserNotification;
use App\Services\ImpersonationService;
use App\Notifications\UserPasswordResetNotification;
use Carbon\Carbon;

new class extends Component {
    use WithFileUploads;

    public User $user;
    public $accounts;
    public ?Account $selectedAccount = null;
    public ?int $selectedAccountId = null;
    public string $currencySymbol;

    // Account Limits
    public float $per_transaction_limit = 0;
    public float $daily_transaction_limit = 0;
    public float $monthly_transaction_limit = 0;

    // Email form
    public $subject;
    public $message;
    public $buttonUrl;
    public $attachments = [];

    // Wallet form
    public $walletAction = '';
    public $amount;
    public $walletNote;
    public $date;
    public bool $kycVerified;
    public array $stats = [];
    protected $listeners = [
        'clearEmailForm' => 'resetEmailForm',
    ];

    public function mount(User $user, array $stats, $accounts, ?int $selectedAccountId, ?Account $selectedAccount, string $currencySymbol)
    {
        $this->user = $user;
        $this->kycVerified = $user->kyc()->latestForUser($user->id)->first()?->isVerified() ?? false;
        // Email modal defaults
        $this->subject = '';
        $this->message = '';
        $this->buttonUrl = '';
        $this->accounts = $accounts;
        $this->selectedAccountId = $selectedAccountId;
        $this->selectedAccount = $selectedAccount;
        $this->currencySymbol = $currencySymbol;
        $this->stats = $stats;
        $this->loadAccountLimits();
    }

    public function updatedSelectedAccountId($value)
    {
        $this->selectedAccount = collect($this->accounts)->firstWhere('id', $value);
        $this->loadAccountLimits();
    }

    private function loadAccountLimits(): void
    {
        if (!$this->selectedAccount) {
            $this->per_transaction_limit = $this->daily_transaction_limit = $this->monthly_transaction_limit = 0;
            return;
        }

        $this->per_transaction_limit = (float) ($this->selectedAccount->per_transaction_limit ?? 0);
        $this->daily_transaction_limit = (float) ($this->selectedAccount->daily_transaction_limit ?? 0);
        $this->monthly_transaction_limit = (float) ($this->selectedAccount->monthly_transaction_limit ?? 0);
    }

    // === User Status ===
    public function suspendUser()
    {
        if ($this->user->profile->status !== Profile::STATUS_SUSPENDED) {
            $this->user->profile->status = Profile::STATUS_SUSPENDED;
            $this->user->profile->save();
            $this->dispatch('showToast', message: 'User suspended!', type: 'success');
        }
    }

    public function activateUser()
    {
        if ($this->user->profile->status === Profile::STATUS_SUSPENDED) {
            $this->user->profile->status = Profile::STATUS_ACTIVE;
            $this->user->profile->save();
            $this->dispatch('showToast', message: 'User activated!', type: 'success');
        }
    }

    // === Email ===
    public function updatedAttachments()
    {
        if (count($this->attachments) > 5) {
            $this->attachments = array_slice($this->attachments, 0, 5);
            $this->addError('attachments', 'You can upload a maximum of 5 attachments.');
        }
    }

    public function removeAttachment($index)
    {
        unset($this->attachments[$index]);
        $this->attachments = array_values($this->attachments); // reindex
    }
    public function resetEmailForm()
    {
        $this->reset(['subject', 'message', 'buttonUrl', 'attachments']);
        $this->resetErrorBag();
        $this->resetValidation();

        $this->dispatch('clear-trix');
    }

    public function sendEmail()
    {
        // Validate input
        $this->validate([
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
            'buttonUrl' => 'nullable|url',
            'attachments' => 'nullable|array|max:5',
            'attachments.*' => 'file|max:5120|mimes:jpg,jpeg,png,webp,pdf,doc,docx,xls,xlsx',
        ]);

        // Temporary paths array
        $paths = [];

        try {
            DB::transaction(function () use (&$paths) {
                // Store uploaded attachments **inside transaction**
                foreach ($this->attachments as $file) {
                    $paths[] = $file->store('email_attachments', 'public');
                }

                // Send notification to the user
                if ($this->user->profile) {
                    Notification::send($this->user, new EmailUserNotification($this->subject, $this->message, $this->buttonUrl, $paths));
                }

                // Optional: notify all admins
                $admins = Admin::all();
                Notification::send($admins, new EmailUserNotification($this->subject, $this->message, $this->buttonUrl, $paths));

                // Save record in UserEmail
                UserEmail::create([
                    'user_id' => $this->user->id,
                    'admin_id' => auth()->id(),
                    'subject' => $this->subject,
                    'message' => strip_tags($this->message), // plain text
                    'button_url' => $this->buttonUrl,
                    'attachments' => $paths,
                    'status' => UserEmail::STATUS_SENT,
                ]);
            });

            // Reset inputs and dispatch success
            $this->reset(['subject', 'message', 'buttonUrl', 'attachments']);
            $this->dispatch('success-email');
            $this->dispatch('notification-sent');
            $this->dispatch('showToast', message: 'Email sent and recorded successfully!', type: 'success');
        } catch (\Exception $e) {
            \Log::error('Failed to send email notification: ' . $e->getMessage());

            // Clean up uploaded files if transaction failed
            foreach ($paths as $path) {
                Storage::disk('public')->delete($path);
            }

            // Optionally save failed attempt **without attachments** to avoid orphan files
            UserEmail::create([
                'user_id' => $this->user->id,
                'admin_id' => auth()->id(),
                'subject' => $this->subject,
                'message' => $this->message,
                'button_url' => $this->buttonUrl,
                'attachments' => [], // no files saved
                'status' => UserEmail::STATUS_FAILED,
            ]);

            $this->dispatch('showToast', message: 'Failed to send email.', type: 'error');
        }
    }

    // === Wallet ===
    private function resetWalletForm(): void
    {
        $this->reset(['amount', 'walletNote', 'date', 'walletAction']);
        $this->resetErrorBag();
    }

    public function closeWallet(): void
    {
        $this->resetWalletForm();
        $this->dispatch('close-wallet-modal');
    }

    public function updateWallet()
    {
        $this->validate([
            'selectedAccountId' => 'required|exists:accounts,id',
            'walletAction' => 'required|in:credit,debit',
            'amount' => 'required|numeric|min:0.01',
            'date' => 'required|date_format:Y-m-d\TH:i|before_or_equal:now',
            'walletNote' => 'nullable|string|max:255',
        ]);

        $account = $this->accounts->firstWhere('id', $this->selectedAccountId);

        if (!$account) {
            $this->addError('selectedAccountId', 'Selected account not found.');
            return;
        }

        $amount = number_format((float) $this->amount, 2, '.', '');

        try {
            DB::transaction(function () use ($account, $amount) {
                // Lock account row for safe concurrent updates
                $account = Account::where('id', $account->id)->lockForUpdate()->first();
                $transactionDate = Carbon::parse($this->date);
                $currentBalance = (string) $account->balance;
                $availableBalance = (string) $account->available_balance;

                if ($this->walletAction === 'debit') {
                    // Check against AVAILABLE balance
                    if (bccomp($availableBalance, $amount, 2) === -1) {
                        throw new \Exception('Insufficient available balance.');
                    }
                    $newBalance = bcsub($currentBalance, $amount, 2);
                } else {
                    $newBalance = bcadd($currentBalance, $amount, 2);
                }

                $account->update([
                    'balance' => $newBalance,
                ]);

                // Log transaction
                $account->transactions()->create([
                    'type' => $this->walletAction === 'debit' ? 'withdrawal' : 'deposit',
                    'amount' => $amount,
                    'balance_after' => $newBalance,
                    'status' => Transaction::STATUS_APPROVED,
                    'description' => $this->walletNote,
                    'created_at' => $transactionDate,
                    'updated_at' => $transactionDate,
                    'method' => $this->walletAction === 'debit' ? 'withdrawal' : 'deposit',
                ]);
            });

            // Reset form and reload balances
            $this->resetWalletForm();
            $this->dispatch('updated');

            // Notify user and close modal
            $this->dispatch('showToast', message: 'Wallet updated successfully.', type: 'success');
            $this->dispatch('success');
            $this->dispatch('close-wallet-modal'); // <-- Close modal after success
        } catch (\Exception $e) {
            $this->addError('amount', $e->getMessage());
        }
    }

    // === Wallet Limits ===
    public function openLimitModal(): void
    {
        if ($this->selectedAccount) {
            $this->per_transaction_limit = (float) $this->selectedAccount->per_transaction_limit;
            $this->daily_transaction_limit = (float) $this->selectedAccount->daily_transaction_limit;
            $this->monthly_transaction_limit = (float) $this->selectedAccount->monthly_transaction_limit;
            $this->selectedAccountId = $this->selectedAccount->id;
        }

        $this->dispatch('open-limit-modal');
    }

    public function updateWalletLimits()
    {
        $this->validate([
            'selectedAccountId' => 'required|exists:accounts,id',
            'per_transaction_limit' => 'required|numeric|min:0',
            'daily_transaction_limit' => 'required|numeric|min:0',
            'monthly_transaction_limit' => 'required|numeric|min:0',
        ]);

        $account = collect($this->accounts)->firstWhere('id', $this->selectedAccountId);
        if (!$account) {
            $this->addError('selectedAccountId', 'Selected account not found.');
            return;
        }

        $account->update([
            'per_transaction_limit' => $this->per_transaction_limit,
            'daily_transaction_limit' => $this->daily_transaction_limit,
            'monthly_transaction_limit' => $this->monthly_transaction_limit,
        ]);

        $this->reset(['per_transaction_limit', 'daily_transaction_limit', 'monthly_transaction_limit', 'selectedAccountId']);
        $this->resetErrorBag();

        $this->dispatch('showToast', message: 'Wallet limits updated successfully!', type: 'success');
        $this->dispatch('close-wallet-limit');
    }

    public function closeLimit(): void
    {
        $this->resetErrorBag();
        $this->dispatch('close-wallet-limit'); // close modal
    }

    // === User Password ===
    public function resetPassword()
    {
        $newPassword = \Illuminate\Support\Str::random(12);
        $this->user->password = bcrypt($newPassword);
        $this->user->save();

        if ($this->user->email) {
            try {
                $this->user->notify(new UserPasswordResetNotification($newPassword));
            } catch (\Exception $e) {
                \Log::error('Failed to send password reset email: ' . $e->getMessage());
            }
        }

        $this->dispatch('showToast', message: "Password reset successfully! New password: $newPassword", type: 'success');
    }

    // === Force Logout User ===
    public function forceLogout()
    {
        // Check if user is currently active / has any sessions
        $sessions = \DB::table('sessions')->where('user_id', $this->user->id)->get();

        if ($sessions->isEmpty()) {
            $this->dispatch('showToast', message: 'User is not currently logged in.', type: 'warning');
            return;
        }

        try {
            // Delete all their sessions
            \DB::table('sessions')->where('user_id', $this->user->id)->delete();

            // Optional: Log this action for admin audit trail
            \Log::info('Admin ' . auth()->id() . " forced logout for user {$this->user->id}");

            $this->dispatch('showToast', message: 'User has been logged out from all devices.', type: 'success');
        } catch (\Exception $e) {
            \Log::error("Failed to force logout user {$this->user->id}: " . $e->getMessage());
            $this->dispatch('showToast', message: 'Failed to log out user.', type: 'error');
        }
    }

    // === Delete User ===
    public function deleteUser()
    {
        $this->user->delete();
        $this->dispatch('showToast', message: 'User successfully deleted.', type: 'success');
        return redirect()->route('admin.dashboard');
    }

    // === Login As User ===
    public function loginAsUser()
    {
        $admin = Auth::guard('admin')->user();

        if (!$admin instanceof Admin) {
            abort(403);
        }

        app(ImpersonationService::class)->loginAsUser($admin, $this->user);

        return redirect()->route('user.dashboard');
    }

    public function toggleKyc()
    {
        // Get the latest KYC record for this user
        $latestKyc = \App\Models\Kyc::latestForUser($this->user->id)->first();

        if (!$latestKyc) {
            // No KYC exists → create a verified placeholder (version 1)
            \App\Models\Kyc::create([
                'user_id' => $this->user->id,
                'status' => \App\Models\Kyc::STATUS_VERIFIED,
                'verified_at' => now(),
                'is_latest' => true,
                'version' => 1,
            ]);

            $this->kycVerified = true;
            $this->dispatch('showToast', message: 'KYC automatically verified!', type: 'success');
            return;
        }

        // Toggle the status
        $newStatus = $latestKyc->isVerified() ? \App\Models\Kyc::STATUS_PENDING : \App\Models\Kyc::STATUS_VERIFIED;

        // Increment minor version (e.g., 1 → 1.1 → 1.2 …)
        $newVersion = $latestKyc->version + 0.1;

        $latestKyc->update([
            'status' => $newStatus,
            'verified_at' => $newStatus === \App\Models\Kyc::STATUS_VERIFIED ? now() : null,
            'rejection_reason' => null,
            'version' => round($newVersion, 1), // keep one decimal
        ]);

        $this->kycVerified = $newStatus === \App\Models\Kyc::STATUS_VERIFIED;

        $message = $newStatus === \App\Models\Kyc::STATUS_VERIFIED ? 'KYC automatically verified!' : 'KYC status reverted to pending.';

        $this->dispatch('showToast', message: $message, type: $newStatus === \App\Models\Kyc::STATUS_VERIFIED ? 'success' : 'warning');

        $this->dispatch('profile-updated', userId: $this->user->id);
    }

    // In your component
    public function openEmailModal()
    {
        $this->dispatch('open-email-modal');
    }
    public function openWalletModal()
    {
        $this->dispatch('open-wallet-modal');
    }
};
?>
<div>

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

        <!-- Suspend / Activate User -->
        <x-flux::button :variant="$user->profile->status === Profile::STATUS_ACTIVE ? 'danger' : 'primary'" :color="$user->profile->status === Profile::STATUS_ACTIVE ? 'rose' : 'emerald'" icon="user"
            wire:click="{{ $user->profile->status === Profile::STATUS_ACTIVE ? 'suspendUser' : 'activateUser' }}">
            {{ $user->profile->status === Profile::STATUS_ACTIVE ? 'Suspend User' : 'Activate User' }}
        </x-flux::button>

        <!-- Delete User -->
        <x-flux::button
            onclick="confirm('Are you sure you want to delete this user?') || event.stopImmediatePropagation()"
            variant="danger" icon="trash" wire:click="deleteUser">
            Delete User
        </x-flux::button>

        <!-- Email User -->
        <x-flux::button variant="primary" color="sky" icon="envelope" wire:click="openEmailModal">
            Email User
        </x-flux::button>

        <!-- Login History -->
        <a href="{{ route('admin.users.login.history', $user) }}"
            class="inline-flex items-center justify-center w-full h-10 px-3 rounded-lg bg-blue-200 text-blue-800 hover:bg-blue-300 focus:outline-none focus:ring-2 focus:ring-blue-300 transition text-sm font-medium">
            <x-flux::icon.user-circle variant="solid" class="w-4 h-4 mr-2" /> Login History
        </a>

        <!-- Login As User -->
        <x-flux::button variant="primary" color="cyan" icon="exclamation-triangle" wire:click="loginAsUser">
            Login As User
        </x-flux::button>

        <!-- Credit / Debit User -->
        <x-flux::button variant="primary" color="teal" icon="credit-card" wire:click="openWalletModal">
            Credit / Debit User
        </x-flux::button>

        <!-- Update User Limit -->
        <x-flux::button variant="primary" color="emerald" icon="funnel" wire:click="openLimitModal">
            Update User Limit
        </x-flux::button>

        <!-- Reset Password -->
        <x-flux::button variant="primary" color="indigo" icon="key" wire:click="resetPassword">
            Reset Password
        </x-flux::button>

        <!-- User Transactions -->
        <a href="{{ route('admin.users.transactions', $user) }}"
            class="inline-flex items-center justify-center w-full h-10 px-3 rounded-lg bg-sky-200 text-sky-800 hover:bg-sky-300 transition text-sm font-medium">
            <x-flux::icon.user-circle variant="solid" class="w-4 h-4 mr-2" /> User Transactions
        </a>

        <!-- User Notifications -->
        <a href="{{ route('admin.users.notifications', $user) }}"
            class="inline-flex items-center justify-center w-full h-10 px-3 rounded-lg bg-teal-200 text-teal-800 hover:bg-teal-300 transition text-sm font-medium">
            <x-flux::icon.bell variant="solid" class="w-4 h-4 mr-2" /> User Notifications
        </a>
        <!-- KYC Toggle Button with Sliding Knob -->
        <x-flux::button :variant="'primary'" :color="$kycVerified ? 'emerald' : 'rose'" icon="check-circle" wire:click="toggleKyc"
            wire:loading.attr="disabled">
            {{ $kycVerified ? 'KYC Verified' : 'KYC Pending' }}
        </x-flux::button>
        <!-- Force Logout -->
        <x-flux::button variant="danger" color="red" icon="arrow-left-start-on-rectangle" wire:click="forceLogout">
            Force Logout
        </x-flux::button>
    </div>

    {{-- === Modals BEGIN --}}
    <div x-cloak x-data="{
        open: false,
        close() {
            this.open = false;
            $wire.resetEmailForm();
        }
    }" x-on:open-email-modal.window="open = true" x-on:success-email.window="close()"
        x-show="open" x-transition class="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 md:p-8"
        style="display: none;">

        <!-- Overlay -->
        <div class="absolute inset-0 bg-black/40 dark:bg-black/70 backdrop-blur-md" @click="close()"></div>

        <!-- Modal Container -->
        <div class="relative w-full max-w-3xl shadow-xl rounded-xl p-6
            max-h-[90vh] overflow-auto flex flex-col
            bg-white dark:bg-gray-900
            text-gray-800 dark:text-gray-100"
            @click.stop>

            <!-- Modal Header -->
            <div
                class="flex items-center justify-between gap-4 border-b pb-4 
                    border-gray-200 dark:border-gray-700">

                <h2 class="text-2xl font-bold text-gray-900 dark:text-white">
                    Email {{ $user->name }}
                </h2>

                <a href="{{ route('admin.users.emails.history', $user) }}"
                    class="text-sm text-sky-600 dark:text-sky-400 
                       hover:underline flex items-center gap-1 capitalize">
                    view Email history
                    <x-flux::icon.arrow-right class="w-3 h-3" />
                </a>
            </div>

            <form wire:submit.prevent="sendEmail" class="space-y-4 mt-4">

                <!-- Subject -->
                <div>
                    <x-input wire:model.defer="subject" label="Subject" placeholder="Email Subject" class="w-full" />
                </div>

                <!-- Attachments -->
                <div>
                    @include('partials.support-upload')
                </div>

                <!-- Message -->
                <div wire:ignore>
                    <label
                        class="block mb-2 text-sm font-medium 
                              text-gray-700 dark:text-gray-300">
                        Message Body
                    </label>

                    <input id="content-input" type="hidden" wire:model.defer="message">

                    <trix-editor id="trix-editor" input="content-input" class="trix-dark"
                        wire:trix-change="$set('message', $event.target.value)">
                    </trix-editor>
                </div>

                <!-- Button URL -->
                <div>
                    <x-input wire:model.defer="buttonUrl" label="Button URL (optional)"
                        placeholder="https://example.com" />
                </div>

                <!-- Buttons -->
                <div
                    class="flex gap-3 mt-4 flex-wrap justify-end border-t pt-4 
                        border-gray-200 dark:border-gray-700">

                    <!-- Send -->
                    <x-flux::button type="submit" variant="primary" color="green" icon="send">
                        Send Email
                    </x-flux::button>

                    <!-- Close -->
                    <x-flux::button type="button" variant="danger" color="gray" @click="close()">
                        Close
                    </x-flux::button>

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

    <x-modal maxWidth="max-w-2xl" @open-wallet-modal.window="openModal()" @close-wallet-modal.window="close()"
        x-on:success.window="close()">
        <!-- Content -->
        <div class="relative space-y-4">
            <!-- Header -->
            <div class="flex justify-between items-start">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight">
                        Update Wallet Balance
                    </h1>
                    <p class="text-sm text-gray-500 mt-1">
                        Credit or debit funds from the selected account.
                    </p>
                </div>
            </div>

            <form wire:submit.prevent="updateWallet" class="space-y-6">

                <div>
                    <x-select wire:model.defer="selectedAccountId" label="Select Account" placeholder="Choose Account">
                        @foreach ($accounts as $account)
                            <option value="{{ $account->id }}">
                                {{ $account->bank_account_type }}
                                • {{ $account->masked_account_number }}
                                • Balance: {{ $currencySymbol }}{{ number_format($account->available_balance, 2) }}
                            </option>
                        @endforeach
                    </x-select>
                </div>
                <div>
                    <x-select wire:model.defer="walletAction" label="Select Action" placeholder="Select Action">
                        <option value="credit">Credit (Add Funds)</option>
                        <option value="debit">Debit (Deduct Funds)</option>
                    </x-select>
                </div>
                <div>
                    <x-input wire:model.defer="amount" label="Enter Amount" type="number" step="0.01"
                        min="0.01" placeholder="Enter Amount" />
                </div>
                <div>
                    <x-input wire:model.defer="date" label="Transaction Date" type="datetime-local"
                        value="2025-06-12T19:30" />
                </div>
                <div>
                    <x-textarea wire:model.defer="walletNote" label="Note (optional)"
                        placeholder="Enter note for user" />
                </div>


                <x-button type="submit" class="w-full" icon="currency-dollar">
                    {{ __('Update Balance') }}</x-button>

                <x-button type="button" wire:click="closeWallet" variant="danger">
                    {{ __('Cancel') }}
                </x-button>

            </form>

        </div>
    </x-modal>

    <x-modal maxWidth="max-w-2xl" @open-limit-modal.window="openModal()" @close-wallet-limit.window="close()"
        x-on:success.window="close()">

        <!-- Content -->
        <div class="relative space-y-4">
            <!-- Header -->
            <div class="flex justify-between items-start">
                <div>
                    <h1 class="text-2xl font-bold tracking-tight">
                        Update Wallet Limits
                    </h1>
                    <p class="text-sm text-gray-500 mt-1">
                        Set per-transaction, daily, and monthly limits for the selected account.
                    </p>
                </div>
            </div>

            <form wire:submit.prevent="updateWalletLimits" class="space-y-6">

                <!-- Account Selector -->
                <div>
                    <x-select wire:model.live="selectedAccountId" label="Select Account"
                        placeholder="Choose Account">
                        @foreach ($accounts as $account)
                            <option value="{{ $account->id }}">
                                {{ $account->bank_account_type }}
                                • {{ $account->masked_account_number }}
                                • Balance: {{ $currencySymbol }}{{ number_format($account->available_balance, 2) }}
                            </option>
                        @endforeach
                    </x-select>
                </div>

                <!-- Per Transaction Limit -->
                <div>
                    <x-input wire:model.defer="per_transaction_limit" label="Limit Per Transaction" type="number"
                        step="0.01" min="0.01" placeholder="Enter maximum amount allowed per transaction" />
                </div>

                <!-- Daily Limit -->
                <div>
                    <x-input wire:model.defer="daily_transaction_limit" label="Daily Limit" type="number"
                        step="0.01" min="0.01" placeholder="Enter maximum total amount allowed per day" />
                </div>

                <!-- Monthly Limit -->
                <div>
                    <x-input wire:model.defer="monthly_transaction_limit" label="Monthly Limit" type="number"
                        step="0.01" min="0.01" placeholder="Enter maximum total amount allowed per month" />
                </div>

                <!-- Submit & Cancel Buttons -->
                <div class="flex gap-3 flex-wrap justify-end">
                    <x-button type="submit" class="w-full sm:w-auto" icon="currency-dollar" color="emerald">
                        Update Limits
                    </x-button>

                    <x-button type="button" wire:click="closeLimit" variant="danger" class="w-full sm:w-auto">
                        Cancel
                    </x-button>
                </div>

            </form>
        </div>
    </x-modal>



    <script>
        window.addEventListener('clear-trix', () => {
            const editor = document.querySelector("trix-editor");
            if (editor) {
                editor.editor.loadHTML('');
            }
        });

        document.addEventListener("trix-file-accept", function(event) {
            event.preventDefault();
            alert("Please use the Attachments field for files.");
        });

        document.addEventListener("trix-initialize", function(event) {
            const toolbar = event.target.toolbarElement;
            if (toolbar) {
                const fileTools = toolbar.querySelectorAll("button[data-trix-action='attachFiles']");
                fileTools.forEach(btn => btn.remove());
            }
        });
    </script>


    {{-- === END OF MODALS ==== --}}
</div>
