<template>
    <Head title="Profile" />

    <AppLayout>
        <div class="profile-card">
            <h2 class="profile-card-title">Profile photo</h2>
            <div class="profile-photo-row">
                <div class="profile-avatar">
                    <img v-if="photoPreview" :src="photoPreview" alt="Photo preview">
                    <img v-else-if="user.profile_photo_url" :src="user.profile_photo_url" :alt="user.name">
                    <span v-else>{{ initials }}</span>
                </div>
                <div>
                    <div class="profile-photo-title">Upload your photo …</div>
                    <div class="profile-photo-hint">Photo should be at least 300px × 300px</div>
                    <div class="profile-photo-actions">
                        <input ref="photoInput" type="file" accept="image/*" class="profile-hidden-input" @change="onPhotoSelected">
                        <button type="button" class="btn btn-outline btn-sm" @click="photoInput.click()">Upload Photo</button>
                        <button v-if="user.profile_photo_url && !photoPreview" type="button" class="btn btn-ghost btn-sm text-danger" @click="removePhoto" title="Delete Photo">
                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" style="width:16px;height:16px;color:#ef4444">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
                            </svg>
                        </button>
                    </div>
                    <p v-if="infoForm.errors.photo" class="profile-error">{{ infoForm.errors.photo }}</p>
                </div>
            </div>
        </div>

        <div class="profile-columns">
            <div class="profile-card">
                <h2 class="profile-card-title">Basic information</h2>

                <div class="profile-field">
                    <label>Username</label>
                    <input type="text" :value="infoForm.username" disabled title="Username can't be changed after registration">
                    <p class="profile-photo-hint" style="margin-top:6px">Your username is permanent and can't be changed.</p>
                </div>

                <div class="profile-field">
                    <label>First name</label>
                    <input type="text" v-model="infoForm.first_name" placeholder="First name">
                    <p v-if="infoForm.errors.first_name" class="profile-error">{{ infoForm.errors.first_name }}</p>
                </div>

                <div class="profile-field">
                    <label>Last name</label>
                    <input type="text" v-model="infoForm.last_name" placeholder="Last name">
                    <p v-if="infoForm.errors.last_name" class="profile-error">{{ infoForm.errors.last_name }}</p>
                </div>

                <div class="profile-field">
                    <label>Email address</label>
                    <input type="email" v-model="infoForm.email" placeholder="you@example.com">
                    <p v-if="infoForm.errors.email" class="profile-error">{{ infoForm.errors.email }}</p>
                </div>

                <div class="profile-field">
                    <label>Website</label>
                    <input type="text" v-model="infoForm.website" placeholder="https://example.com">
                    <p v-if="infoForm.errors.website" class="profile-error">{{ infoForm.errors.website }}</p>
                </div>

                <button class="btn btn-primary" :disabled="infoForm.processing" @click="updateProfileInformation">
                    {{ infoForm.processing ? 'Updating…' : 'Update' }}
                </button>
                <p v-if="infoSaved" class="profile-saved">Saved.</p>
            </div>

            <div class="profile-card">
                <h2 class="profile-card-title">Change password</h2>

                <div class="profile-field">
                    <div class="profile-field-label-row">
                        <label>Verify current password</label>
                        <button type="button" class="profile-toggle" @click="showCurrent = !showCurrent">{{ showCurrent ? 'Hide' : 'Show' }}</button>
                    </div>
                    <input :type="showCurrent ? 'text' : 'password'" v-model="passwordForm.current_password" autocomplete="current-password">
                    <p v-if="passwordForm.errors.current_password" class="profile-error">{{ passwordForm.errors.current_password }}</p>
                </div>

                <div class="profile-field">
                    <div class="profile-field-label-row">
                        <label>New password</label>
                        <button type="button" class="profile-toggle" @click="showNew = !showNew">{{ showNew ? 'Hide' : 'Show' }}</button>
                    </div>
                    <input :type="showNew ? 'text' : 'password'" v-model="passwordForm.password" autocomplete="new-password">
                    <p v-if="passwordForm.errors.password" class="profile-error">{{ passwordForm.errors.password }}</p>
                </div>

                <button type="button" class="profile-generate-link" @click="generatePassword">Generate strong password</button>

                <div class="profile-checklist">
                    <div class="profile-checklist-col">
                        <div class="profile-check" :class="{ 'is-met': checks.lower }"><span class="profile-check-dot"></span>One lowercase character</div>
                        <div class="profile-check" :class="{ 'is-met': checks.upper }"><span class="profile-check-dot"></span>One uppercase character</div>
                        <div class="profile-check" :class="{ 'is-met': checks.number }"><span class="profile-check-dot"></span>One number</div>
                    </div>
                    <div class="profile-checklist-col">
                        <div class="profile-check" :class="{ 'is-met': checks.symbol }"><span class="profile-check-dot"></span>One special character</div>
                        <div class="profile-check" :class="{ 'is-met': checks.length }"><span class="profile-check-dot"></span>8 characters minimum</div>
                        <div class="profile-check" :class="{ 'is-met': checks.noUsername }"><span class="profile-check-dot"></span>Must not contain username</div>
                    </div>
                </div>

                <div class="profile-field" style="margin-top:16px">
                    <div class="profile-field-label-row">
                        <label>Confirm new password</label>
                        <button type="button" class="profile-toggle" @click="showConfirm = !showConfirm">{{ showConfirm ? 'Hide' : 'Show' }}</button>
                    </div>
                    <input :type="showConfirm ? 'text' : 'password'" v-model="passwordForm.password_confirmation" autocomplete="new-password">
                </div>

                <button class="btn btn-primary" :disabled="passwordForm.processing" @click="updatePassword">
                    {{ passwordForm.processing ? 'Updating…' : 'Update' }}
                </button>
                <p v-if="passwordSaved" class="profile-saved">Saved.</p>
            </div>
        </div>
    </AppLayout>
</template>

<script setup>
import { computed, ref } from 'vue';
import { Head, router, useForm, usePage } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';

defineProps({
    sessions: Array,
    confirmsTwoFactorAuthentication: Boolean,
});

const page = usePage();
const user = computed(() => page.props.auth.user);

const initials = computed(() => {
    const name = user.value?.name || '?';
    return name.split(/\s+/).slice(0, 2).map((w) => w[0]?.toUpperCase() ?? '').join('');
});

// ── Basic information + photo (one combined form, matching Jetstream's
// standard pattern  the profile-info endpoint validates/saves both) ──
const infoForm = useForm({
    _method: 'PUT',
    first_name: user.value?.first_name ?? '',
    last_name: user.value?.last_name ?? '',
    username: user.value?.username ?? '',
    email: user.value?.email ?? '',
    website: user.value?.website ?? '',
    photo: null,
});
const infoSaved = ref(false);

function updateProfileInformation() {
    infoSaved.value = false;
    infoForm.post(route('user-profile-information.update'), {
        errorBag: 'updateProfileInformation',
        preserveScroll: true,
        onSuccess: () => {
            infoSaved.value = true;
            setTimeout(() => { infoSaved.value = false; }, 3000);
        },
    });
}

const photoInput = ref(null);
const photoPreview = ref(null);

function onPhotoSelected() {
    const photo = photoInput.value.files[0];
    if (!photo) return;

    const reader = new FileReader();
    reader.onload = (e) => { photoPreview.value = e.target.result; };
    reader.readAsDataURL(photo);

    infoForm.photo = photo;
    updateProfileInformation();
}

function removePhoto() {
    router.delete(route('current-user-photo.destroy'), {
        preserveScroll: true,
        onSuccess: () => { photoPreview.value = null; },
    });
}

// ── Change password ──
const passwordForm = useForm({
    current_password: '',
    password: '',
    password_confirmation: '',
});
const passwordSaved = ref(false);
const showCurrent = ref(false);
const showNew = ref(false);
const showConfirm = ref(false);

function updatePassword() {
    passwordSaved.value = false;
    passwordForm.put(route('user-password.update'), {
        errorBag: 'updatePassword',
        preserveScroll: true,
        onSuccess: () => {
            passwordSaved.value = true;
            passwordForm.reset();
            setTimeout(() => { passwordSaved.value = false; }, 3000);
        },
        onError: () => {
            if (passwordForm.errors.password) {
                passwordForm.reset('password', 'password_confirmation');
            }
            if (passwordForm.errors.current_password) {
                passwordForm.reset('current_password');
            }
        },
    });
}

const checks = computed(() => {
    const pw = passwordForm.password || '';
    const username = (infoForm.username || '').toLowerCase();
    return {
        lower:      /[a-z]/.test(pw),
        upper:      /[A-Z]/.test(pw),
        number:     /[0-9]/.test(pw),
        symbol:     /[^A-Za-z0-9]/.test(pw),
        length:     pw.length >= 8,
        noUsername: username === '' || !pw.toLowerCase().includes(username),
    };
});

function generatePassword() {
    const lower   = 'abcdefghijkmnpqrstuvwxyz';
    const upper   = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    const numbers = '23456789';
    const symbols = '!@#$%^&*-_=+';
    const all     = lower + upper + numbers + symbols;

    const required = [
        lower[Math.floor(Math.random() * lower.length)],
        upper[Math.floor(Math.random() * upper.length)],
        numbers[Math.floor(Math.random() * numbers.length)],
        symbols[Math.floor(Math.random() * symbols.length)],
    ];
    for (let i = 0; i < 12; i++) {
        required.push(all[Math.floor(Math.random() * all.length)]);
    }

    const pw = required.sort(() => Math.random() - 0.5).join('');
    passwordForm.password = pw;
    passwordForm.password_confirmation = pw;
    showNew.value = true;
    showConfirm.value = true;
}
</script>

<style scoped>
.profile-card {
    background: var(--bg-surface);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 24px;
    margin-bottom: 24px;
}
.profile-card-title {
    font-size: 18px;
    font-weight: 700;
    color: var(--text-primary);
    margin: 0 0 18px;
}

.profile-columns {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    align-items: start;
}
@media (max-width: 900px) {
    .profile-columns { grid-template-columns: 1fr; }
}

.profile-photo-row { display: flex; align-items: center; gap: 20px; }
.profile-avatar {
    width: 84px;
    height: 84px;
    border-radius: 50%;
    background: var(--bg-hover);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    font-weight: 600;
    color: var(--text-secondary);
    overflow: hidden;
    flex-shrink: 0;
}
.profile-avatar img { width: 100%; height: 100%; object-fit: cover; }
.profile-photo-title { font-size: 15px; font-weight: 600; color: var(--text-primary); }
.profile-photo-hint { font-size: 12px; color: var(--text-muted); margin: 2px 0 10px; }
.profile-photo-actions { display: flex; gap: 8px; }
.profile-hidden-input { display: none; }

.profile-field { margin-bottom: 16px; max-width: 420px; }
.profile-field label {
    display: block;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: 6px;
}
.profile-field input {
    width: 100%;
    height: 38px;
    padding: 0 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 13px;
    color: var(--text-primary);
    background: var(--bg-surface);
    box-sizing: border-box;
    font-family: inherit;
}
.profile-field input:focus {
    outline: none;
    border-color: #93c5fd;
    box-shadow: 0 0 0 3px rgba(66, 133, 244, 0.15);
}
.profile-field input:disabled {
    background: var(--bg-page);
    color: var(--text-muted);
    cursor: not-allowed;
}
.profile-field-label-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
.profile-field-label-row label { margin-bottom: 0; }
.profile-toggle {
    background: none;
    border: none;
    cursor: pointer;
    font-size: 12px;
    color: #2563eb;
    padding: 0;
}

.profile-error { font-size: 12px; color: #dc2626; margin: 6px 0 0; }
.profile-saved { font-size: 12px; color: #16a34a; margin: 10px 0 0; }

.profile-generate-link {
    display: inline-block;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 13px;
    font-weight: 500;
    color: #2563eb;
    padding: 0;
    margin-bottom: 14px;
}

.profile-checklist {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 6px 16px;
    margin-bottom: 4px;
}
.profile-check {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    color: var(--text-muted);
}
.profile-check-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: var(--text-muted);
    flex-shrink: 0;
}
.profile-check.is-met { color: #16a34a; }
.profile-check.is-met .profile-check-dot { background: #16a34a; }
</style>
