<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;

new class extends Component {
    use WithFileUploads;
    public $photo; // ✅ Optional: if using wire:model="photo"
    public $user;

    public function mount()
    {
        $this->user = Auth::user();
    }

    // 1️⃣ Define rules
    protected $rules = [
        'photo' => 'required|image|max:10240|mimes:jpg,jpeg,png,webp',
    ];

    // 2️⃣ Define custom messages
    protected $messages = [
        'photo.required' => 'Please upload a photo.',
        'photo.image' => 'The uploaded file must be an image.type: jpg, jpeg, png, webp',
        'photo.max' => 'The photo must not be larger than 10 MB.',
        'photo.mimes' => 'The photo must be a file of type: jpg, jpeg, png, webp.',
    ];

    public function updateProfilePhoto()
    {
        $this->validate();
        $user = Auth::user();
        $profile = $user->profile ?? $user->profile()->create([]);

        // Delete old photo if exists
        if ($profile->profile_photo && Storage::disk('public')->exists($profile->profile_photo)) {
            Storage::disk('public')->delete($profile->profile_photo);
        }

        // Store new photo
        $path = $this->photo->store('avatars', 'public');

        $profile->update([
            'profile_photo' => $path,
        ]);

        $publicUrl = Storage::disk('public')->url($path) . '?t=' . time();

        $this->dispatch('profile-image-updated', name: $this->user->name, photoUrl: $publicUrl . '?t=' . time());
        $this->dispatch('profile-updated', name: $user->name, photoUrl: $publicUrl . '?t=' . time());
        $this->dispatch('showToast', message: 'Profile image updated successfully.', type: 'success');

        $this->reset('photo');
    }
};
?>

<div x-cloak x-data="{
    photoPreview: null,
    showSaveButton: false,
    description: 'Choose a photo to update your profile',
    originalDescription: 'Choose a photo to update your profile',
    uploadProgress: 0,
    uploading: false,

    init() {
        // Start upload
        this.$el.addEventListener('livewire-upload-start', () => {
            this.uploading = true;
            this.uploadProgress = 0;
            this.description = 'Uploading... 0%';
            this.showSaveButton = false;
        });

        // Progress
        this.$el.addEventListener('livewire-upload-progress', event => {
            this.uploadProgress = event.detail.progress;
            this.description = 'Uploading... ' + this.uploadProgress + '%';
        });

        // Upload finished
        this.$el.addEventListener('livewire-upload-finish', () => {
            this.uploading = false;
            this.description = this.originalDescription;
            this.showSaveButton = true;
        });

        // Upload error
        this.$el.addEventListener('livewire-upload-error', () => {
            this.uploading = false;
            this.description = 'Upload failed. Try again.';
            this.showSaveButton = false;
        });

        // Profile updated
        window.addEventListener('profile-image-updated', e => {
            this.photoPreview = e.detail.photoUrl;
            this.showSaveButton = false;
            this.description = this.originalDescription;
        });
    },

    handleFileChange(event) {
        const file = event.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = e => this.photoPreview = e.target.result;
            reader.readAsDataURL(file);

            // Do NOT show Save button yet — will show after upload finish
            this.showSaveButton = false;
        } else {
            this.photoPreview = null;
            this.showSaveButton = false;
        }
    }
}" class="flex flex-col items-center space-y-2">

    <div class="relative group cursor-pointer" @click="$refs.photoInput.click()">
        <div class="h-28 w-28 rounded-full overflow-hidden border-4 border-sky-500 shadow relative">
            <template x-if="photoPreview">
                <img :src="photoPreview" class="h-full w-full object-cover" />
            </template>
            <template x-if="!photoPreview">
                <img src="<?php echo e(optional($user->profile)->profile_photo
                    ? Storage::disk('public')->url($user->profile->profile_photo)
                    : 'https://ui-avatars.com/api/?name=' . urlencode($user->name)); ?>"
                    alt="<?php echo e($user->name); ?>’s profile photo"
                    class="h-full w-full object-cover transition-opacity duration-300" alt="Profile Photo">
            </template>

            <div x-show="uploading"
                class="absolute inset-0 bg-black/50 flex flex-col items-center justify-center text-white text-xs font-medium transition">
                Uploading... <span x-text="uploadProgress + '%'"></span>
            </div>
        </div>

        <div
            class="absolute inset-0 bg-black/50 flex items-center justify-center text-white text-xs font-medium opacity-0 group-hover:opacity-100 transition rounded-full">
            Change Photo
        </div>
    </div>
    <p class="text-xs text-gray-500" x-text="description"></p>

    <!-- File Input -->
    <!-- File Input -->
    <input type="file" x-ref="photoInput" wire:model="photo" class="hidden" @change="handleFileChange($event)" />

    <!-- Display validation error -->
    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php $__errorArgs = ['photo'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
        <p class="text-xs text-red-500 mt-1"><?php echo e($message); ?></p>
    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

    <!-- Save Button -->
    <button x-show="showSaveButton" x-cloak x-transition wire:click="updateProfilePhoto" wire:loading.attr="disabled"
        class="text-xs text-sky-600 hover:underline flex items-center gap-2" :disabled="uploading">
        <span wire:loading.remove>Save Photo</span>
        <span wire:loading>
            <svg class="animate-spin h-4 w-4 text-sky-600" xmlns="http://www.w3.org/2000/svg" fill="none"
                viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
                </circle>
                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
            </svg>
            Saving...
        </span>
    </button>
</div>
<?php /**PATH /Users/macuser/Herd/Novabank/resources/views/components/⚡userphoto.blade.php ENDPATH**/ ?>