<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/Profile/Index.vue
//  Location: resources/js/Pages/Member/Profile/Index.vue
//
//  Member profile & settings — 5 section cards:
//    1. Profile Identity
//    2. Hub Membership
//    3. Privacy
//    4. Notifications
//    5. Security (change password)
//
//  All saves are PATCH via fetch — no page reloads.
// ══════════════════════════════════════════════════════════════════

import { ref, computed, reactive } from 'vue'
import AppLayout                   from '@/Layouts/AppLayout.vue'
import { useAuthStore }            from '@/Stores/useAuthStore'

const props = defineProps({
    user: { type: Object, required: true },
    allHubs: { type: Array, default: () => [] },
})

const authStore = useAuthStore()
const locale    = computed(() => authStore.locale)
const ar        = computed(() => locale.value === 'ar')

// ── CSRF helper ───────────────────────────────────────────────
function csrf() {
    return document.querySelector('meta[name="csrf-token"]')?.content ?? ''
}

// ── Toast ─────────────────────────────────────────────────────
const toast      = ref(null)   // { type: 'success'|'error', msg: string }
let toastTimer   = null

function showToast(type, msg) {
    clearTimeout(toastTimer)
    toast.value  = { type, msg }
    toastTimer   = setTimeout(() => toast.value = null, 3000)
}

// ══════════════════════════════════════════════════════════════
//  SECTION 1 — Profile Identity
// ══════════════════════════════════════════════════════════════
const profile = reactive({
    name:             props.user.name,
    nickname:         props.user.nickname,
    profession:       props.user.profession       ?? '',
    experience_level: props.user.experience_level ?? '',
    sector:           props.user.sector           ?? '',
    bio:              props.user.bio              ?? '',
})
const profileErrors  = ref({})
const profileSaving  = ref(false)

async function saveProfile() {
    profileSaving.value  = true
    profileErrors.value  = {}
    try {
        const res = await fetch(route('member.profile.update'), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf() },
            body: JSON.stringify(profile),
        })
        const data = await res.json()
        if (!res.ok) {
            profileErrors.value = data.errors ?? {}
            showToast('error', ar.value ? 'تعذر الحفظ. تحقق من الحقول.' : 'Could not save. Check the fields.')
        } else {
            showToast('success', ar.value ? 'تم حفظ الملف الشخصي.' : 'Profile saved.')
            // Sync nickname in the auth store so the header updates
            authStore.user.nickname = profile.nickname
        }
    } catch {
        showToast('error', ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } finally {
        profileSaving.value = false
    }
}

const experienceLevels = [
    { value: 'student',   en: 'Student',            ar: 'طالب' },
    { value: 'fresh',     en: 'Fresh Graduate',      ar: 'خريج حديث' },
    { value: 'junior',    en: 'Junior (1–3 yrs)',    ar: 'مبتدئ (1-3 سنوات)' },
    { value: 'mid',       en: 'Mid-Level (3–5 yrs)', ar: 'متوسط (3-5 سنوات)' },
    { value: 'senior',    en: 'Senior (5–10 yrs)',   ar: 'خبير (5-10 سنوات)' },
    { value: 'senior_10', en: '10–15 Years',         ar: '10-15 سنة' },
    { value: 'senior_15', en: '15–20 Years',         ar: '15-20 سنة' },
    { value: 'senior_20', en: '20+ Years',           ar: 'أكثر من 20 سنة' },
]

// Badge helpers
const caseBadge = computed(() => {
    const n = props.user.highly_rated_solutions_count
    if (n >= 25) return { en: 'Top Contributor', ar: 'أفضل مساهم', color: '#E8A020' }
    if (n >= 10) return { en: 'Sharp Mind',      ar: 'عقل حاد',    color: '#378ADD' }
    if (n >= 3)  return { en: 'Rising Voice',    ar: 'صوت صاعد',   color: '#1D9E75' }
    return null
})

const forumBadge = computed(() => {
    const n = props.user.highly_rated_replies_count
    if (n >= 25) return { en: 'Field Expert',    ar: 'خبير ميداني', color: '#E8A020' }
    if (n >= 10) return { en: 'Trusted Advisor', ar: 'مستشار موثوق', color: '#378ADD' }
    if (n >= 3)  return { en: 'Helpful Voice',   ar: 'صوت مفيد',    color: '#1D9E75' }
    return null
})

// ══════════════════════════════════════════════════════════════
//  SECTION 2 — Hub Membership
// ══════════════════════════════════════════════════════════════
const selectedHubIds = ref(props.user.hubs.map(h => h.id))
const hubsSaving     = ref(false)

function toggleHub(hubId) {
    const idx = selectedHubIds.value.indexOf(hubId)
    if (idx === -1) {
        selectedHubIds.value.push(hubId)
    } else {
        if (selectedHubIds.value.length > 1) {
            selectedHubIds.value.splice(idx, 1)
        }
    }
}

function hubColor(hub) {
    const colors = { finance: '#1D9E75', marketing: '#378ADD', sales: '#D85A30' }
    return colors[hub.slug] ?? 'var(--color-primary)'
}

async function saveHubs() {
    hubsSaving.value = true
    try {
        const res = await fetch(route('member.profile.hubs'), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf() },
            body: JSON.stringify({ hub_ids: selectedHubIds.value }),
        })
        if (res.ok) showToast('success', ar.value ? 'تم تحديث المجالات.' : 'Hubs updated.')
        else        showToast('error',   ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } catch {
        showToast('error', ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } finally {
        hubsSaving.value = false
    }
}

// ══════════════════════════════════════════════════════════════
//  SECTION 3 — Privacy
// ══════════════════════════════════════════════════════════════
const showRealName   = ref(props.user.show_real_name)
const privacySaving  = ref(false)

async function savePrivacy() {
    privacySaving.value = true
    try {
        const res = await fetch(route('member.profile.privacy'), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf() },
            body: JSON.stringify({ show_real_name: showRealName.value }),
        })
        if (res.ok) showToast('success', ar.value ? 'تم حفظ الخصوصية.' : 'Privacy settings saved.')
        else        showToast('error',   ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } catch {
        showToast('error', ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } finally {
        privacySaving.value = false
    }
}

// ══════════════════════════════════════════════════════════════
//  SECTION 4 — Notifications
// ══════════════════════════════════════════════════════════════
const notifs = reactive({
    notify_jobs:      props.user.notify_jobs,
    notify_freelance: props.user.notify_freelance,
    notify_forum:     props.user.notify_forum,
    notify_surveys:   props.user.notify_surveys,
    notify_documents: props.user.notify_documents,
})
const notifSaving = ref(false)

async function saveNotifications() {
    notifSaving.value = true
    try {
        const res = await fetch(route('member.profile.notifications'), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf() },
            body: JSON.stringify(notifs),
        })
        if (res.ok) showToast('success', ar.value ? 'تم حفظ الإشعارات.' : 'Notifications saved.')
        else        showToast('error',   ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } catch {
        showToast('error', ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } finally {
        notifSaving.value = false
    }
}

const notifList = computed(() => [
    { key: 'notify_jobs',      en: 'Job matches',         ar: 'تطابقات الوظائف' },
    { key: 'notify_freelance', en: 'Freelance interest',  ar: 'اهتمام المستقلين' },
    { key: 'notify_forum',     en: 'Forum replies',       ar: 'ردود المنتدى' },
    { key: 'notify_surveys',   en: 'New surveys',         ar: 'استطلاعات جديدة' },
    { key: 'notify_documents', en: 'New documents',       ar: 'مستندات جديدة' },
])

// ══════════════════════════════════════════════════════════════
//  SECTION 5 — Security
// ══════════════════════════════════════════════════════════════
const passwords = reactive({
    current_password:        '',
    password:                '',
    password_confirmation:   '',
})
const passwordErrors  = ref({})
const passwordSaving  = ref(false)
const showCurrentPw   = ref(false)
const showNewPw       = ref(false)

async function savePassword() {
    passwordSaving.value = true
    passwordErrors.value = {}
    try {
        const res = await fetch(route('member.profile.password'), {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrf() },
            body: JSON.stringify(passwords),
        })
        const data = await res.json()
        if (!res.ok) {
            if (data.errors) passwordErrors.value = data.errors
            else showToast('error', data.error ?? (ar.value ? 'حدث خطأ.' : 'Something went wrong.'))
        } else {
            showToast('success', ar.value ? 'تم تغيير كلمة المرور.' : 'Password changed.')
            passwords.current_password       = ''
            passwords.password               = ''
            passwords.password_confirmation  = ''
        }
    } catch {
        showToast('error', ar.value ? 'حدث خطأ.' : 'Something went wrong.')
    } finally {
        passwordSaving.value = false
    }
}
</script>

<template>
    <AppLayout>
        <div class="create-page">

            <!-- ══ HERO BANNER ════════════════════════════════════ -->
            <div class="create-hero">
                <div class="create-hero__icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                        <circle cx="12" cy="7" r="4"/>
                    </svg>
                </div>
                <div class="create-hero__text">
                    <h1 class="create-hero__title">
                        {{ ar ? 'ملفي الشخصي والإعدادات' : 'My Profile & Settings' }}
                    </h1>
                    <p class="create-hero__sub">
                        {{ ar
                            ? `@${user.nickname}  •  انضم ${user.joined_at}`
                            : `@${user.nickname}  •  Joined ${user.joined_at}` }}
                    </p>
                </div>
                <!-- Badges strip -->
                <div class="create-hero__steps" v-if="caseBadge || forumBadge">
                    <span v-if="caseBadge" class="hero-badge" :style="{ background: caseBadge.color + '20', color: caseBadge.color, border: `1px solid ${caseBadge.color}40` }">
                        ★ {{ ar ? caseBadge.ar : caseBadge.en }}
                    </span>
                    <span v-if="forumBadge" class="hero-badge" :style="{ background: forumBadge.color + '20', color: forumBadge.color, border: `1px solid ${forumBadge.color}40` }">
                        ★ {{ ar ? forumBadge.ar : forumBadge.en }}
                    </span>
                </div>
            </div>

            <!-- ══ SECTION 1 — Profile Identity ══════════════════ -->
            <div class="form-section">
                <div class="form-section__header">
                    <div class="form-section__icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                            <circle cx="12" cy="7" r="4"/>
                        </svg>
                    </div>
                    <div>
                        <div class="form-section__title">{{ ar ? 'هوية الملف الشخصي' : 'Profile Identity' }}</div>
                        <div class="form-section__sub">{{ ar ? 'اسمك، الاسم المستعار، المهنة، والنبذة' : 'Your name, nickname, profession, and bio' }}</div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'الاسم الكامل' : 'Full Name' }} <span class="form-required">*</span></label>
                        <input v-model="profile.name" class="form-input" :class="{ 'form-input--error': profileErrors.name }" :placeholder="ar ? 'اسمك الكامل' : 'Your full name'" />
                        <div v-if="profileErrors.name" class="form-error">{{ profileErrors.name[0] }}</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'الاسم المستعار' : 'Nickname' }} <span class="form-required">*</span></label>
                        <div class="input-prefix-wrap">
                            <span class="input-prefix">@</span>
                            <input v-model="profile.nickname" class="form-input form-input--prefix" :class="{ 'form-input--error': profileErrors.nickname }" placeholder="your_nickname" />
                        </div>
                        <p class="form-hint">{{ ar ? 'يظهر هذا للعموم بدلاً من اسمك الحقيقي' : 'This appears publicly instead of your real name' }}</p>
                        <div v-if="profileErrors.nickname" class="form-error">{{ profileErrors.nickname[0] }}</div>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'المسمى الوظيفي' : 'Profession' }}</label>
                        <input v-model="profile.profession" class="form-input" :placeholder="ar ? 'مثال: محلل مالي' : 'e.g. Financial Analyst'" maxlength="100" />
                    </div>
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'مستوى الخبرة' : 'Experience Level' }}</label>
                        <div class="type-chips">
                            <button
                                v-for="lvl in experienceLevels"
                                :key="lvl.value"
                                type="button"
                                class="type-chip"
                                :class="{ 'type-chip--active': profile.experience_level === lvl.value }"
                                @click="profile.experience_level = lvl.value"
                            >{{ ar ? lvl.ar : lvl.en }}</button>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">{{ ar ? 'القطاع' : 'Sector' }}</label>
                    <input v-model="profile.sector" class="form-input" :placeholder="ar ? 'مثال: تصنيع، خدمات مالية' : 'e.g. Manufacturing, Financial Services'" maxlength="100" />
                </div>

                <div class="form-group" style="margin-bottom:0">
                    <label class="form-label">{{ ar ? 'نبذة قصيرة' : 'Bio' }}</label>
                    <textarea v-model="profile.bio" class="form-input form-textarea" rows="3" maxlength="500" :placeholder="ar ? 'نبذة مختصرة عنك…' : 'A short description about yourself…'" ></textarea>
                    <p class="form-hint">{{ profile.bio.length }}/500</p>
                </div>

                <div class="section-footer">
                    <button class="submit-btn" :disabled="profileSaving" @click="saveProfile">
                        <svg v-if="!profileSaving" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                        {{ profileSaving ? (ar ? 'جارٍ الحفظ…' : 'Saving…') : (ar ? 'حفظ الملف' : 'Save Profile') }}
                    </button>
                </div>
            </div>

            <!-- ══ SECTION 2 — Hub Membership ════════════════════ -->
            <div class="form-section">
                <div class="form-section__header">
                    <div class="form-section__icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
                        </svg>
                    </div>
                    <div>
                        <div class="form-section__title">{{ ar ? 'انتماء المجال' : 'Hub Membership' }}</div>
                        <div class="form-section__sub">{{ ar ? 'انضم إلى مجال أو أكثر — يجب أن تبقى في مجال واحد على الأقل' : 'Join one or more hubs — you must keep at least one' }}</div>
                    </div>
                </div>

                <div class="hub-chips">
                    <button
                        v-for="hub in allHubs"
                        :key="hub.id"
                        type="button"
                        class="hub-chip"
                        :class="{ 'hub-chip--active': selectedHubIds.includes(hub.id) }"
                        :style="selectedHubIds.includes(hub.id)
                            ? `border-color:${hubColor(hub)};color:${hubColor(hub)};background:${hubColor(hub)}15`
                            : ''"
                        @click="toggleHub(hub.id)"
                    >
                        <span class="hub-chip__dot" :style="{ background: hubColor(hub) }"></span>
                        {{ ar ? hub.name_ar : hub.name_en }}
                        <svg v-if="selectedHubIds.includes(hub.id)" xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                    </button>
                </div>

                <div class="section-footer">
                    <button class="submit-btn" :disabled="hubsSaving" @click="saveHubs">
                        <svg v-if="!hubsSaving" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                        {{ hubsSaving ? (ar ? 'جارٍ الحفظ…' : 'Saving…') : (ar ? 'حفظ المجالات' : 'Save Hubs') }}
                    </button>
                </div>
            </div>

            <!-- ══ SECTION 3 — Privacy ════════════════════════════ -->
            <div class="form-section">
                <div class="form-section__header">
                    <div class="form-section__icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                        </svg>
                    </div>
                    <div>
                        <div class="form-section__title">{{ ar ? 'الخصوصية' : 'Privacy' }}</div>
                        <div class="form-section__sub">{{ ar ? 'تحكم في ما يراه الأعضاء الآخرون من بياناتك' : 'Control what other members see about you' }}</div>
                    </div>
                </div>

                <div class="toggle-row">
                    <div class="toggle-info">
                        <div class="toggle-label">{{ ar ? 'عرض الاسم الحقيقي' : 'Show Real Name' }}</div>
                        <div class="toggle-desc">{{ ar
                            ? `إذا كان مفعلاً، يظهر اسمك "${user.name}" للعموم. إذا كان معطلاً، يظهر اسمك المستعار "@${user.nickname}" فقط.`
                            : `When on, your name "${user.name}" appears publicly. When off, only "@${user.nickname}" is shown.` }}
                        </div>
                    </div>
                    <button
                        type="button"
                        class="toggle-switch"
                        :class="{ 'toggle-switch--on': showRealName }"
                        @click="showRealName = !showRealName"
                        :aria-label="ar ? 'تبديل عرض الاسم الحقيقي' : 'Toggle real name visibility'"
                    >
                        <span class="toggle-thumb"></span>
                    </button>
                </div>

                <div class="section-footer">
                    <button class="submit-btn" :disabled="privacySaving" @click="savePrivacy">
                        <svg v-if="!privacySaving" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                        {{ privacySaving ? (ar ? 'جارٍ الحفظ…' : 'Saving…') : (ar ? 'حفظ الخصوصية' : 'Save Privacy') }}
                    </button>
                </div>
            </div>

            <!-- ══ SECTION 4 — Notifications ══════════════════════ -->
            <div class="form-section">
                <div class="form-section__header">
                    <div class="form-section__icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>
                        </svg>
                    </div>
                    <div>
                        <div class="form-section__title">{{ ar ? 'تفضيلات الإشعارات' : 'Notification Preferences' }}</div>
                        <div class="form-section__sub">{{ ar ? 'اختر الإشعارات التي تريد تلقيها' : 'Choose which notifications you want to receive' }}</div>
                    </div>
                </div>

                <div class="notif-list">
                    <div v-for="n in notifList" :key="n.key" class="toggle-row">
                        <div class="toggle-info">
                            <div class="toggle-label">{{ ar ? n.ar : n.en }}</div>
                        </div>
                        <button
                            type="button"
                            class="toggle-switch"
                            :class="{ 'toggle-switch--on': notifs[n.key] }"
                            @click="notifs[n.key] = !notifs[n.key]"
                        >
                            <span class="toggle-thumb"></span>
                        </button>
                    </div>
                </div>

                <div class="section-footer">
                    <button class="submit-btn" :disabled="notifSaving" @click="saveNotifications">
                        <svg v-if="!notifSaving" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                        {{ notifSaving ? (ar ? 'جارٍ الحفظ…' : 'Saving…') : (ar ? 'حفظ الإشعارات' : 'Save Notifications') }}
                    </button>
                </div>
            </div>

            <!-- ══ SECTION 5 — Security ═══════════════════════════ -->
            <div class="form-section">
                <div class="form-section__header">
                    <div class="form-section__icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                        </svg>
                    </div>
                    <div>
                        <div class="form-section__title">{{ ar ? 'الأمان' : 'Security' }}</div>
                        <div class="form-section__sub">{{ ar ? 'تغيير كلمة المرور' : 'Change your password' }}</div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">{{ ar ? 'كلمة المرور الحالية' : 'Current Password' }} <span class="form-required">*</span></label>
                    <div class="input-eye-wrap">
                        <input
                            v-model="passwords.current_password"
                            :type="showCurrentPw ? 'text' : 'password'"
                            class="form-input form-input--eye"
                            :class="{ 'form-input--error': passwordErrors.current_password }"
                            :placeholder="ar ? 'كلمة مرورك الحالية' : 'Your current password'"
                        />
                        <button type="button" class="eye-btn" @click="showCurrentPw = !showCurrentPw">
                            <svg v-if="!showCurrentPw" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                            <svg v-else xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                        </button>
                    </div>
                    <div v-if="passwordErrors.current_password" class="form-error">{{ passwordErrors.current_password[0] }}</div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'كلمة المرور الجديدة' : 'New Password' }} <span class="form-required">*</span></label>
                        <div class="input-eye-wrap">
                            <input
                                v-model="passwords.password"
                                :type="showNewPw ? 'text' : 'password'"
                                class="form-input form-input--eye"
                                :class="{ 'form-input--error': passwordErrors.password }"
                                :placeholder="ar ? '8 أحرف على الأقل' : 'At least 8 characters'"
                            />
                            <button type="button" class="eye-btn" @click="showNewPw = !showNewPw">
                                <svg v-if="!showNewPw" xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                                <svg v-else xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                            </button>
                        </div>
                        <div v-if="passwordErrors.password" class="form-error">{{ passwordErrors.password[0] }}</div>
                    </div>
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'تأكيد كلمة المرور' : 'Confirm New Password' }} <span class="form-required">*</span></label>
                        <input
                            v-model="passwords.password_confirmation"
                            type="password"
                            class="form-input"
                            :placeholder="ar ? 'أعد كتابة كلمة المرور الجديدة' : 'Repeat new password'"
                        />
                    </div>
                </div>

                <div class="section-footer">
                    <button class="submit-btn submit-btn--danger" :disabled="passwordSaving" @click="savePassword">
                        <svg v-if="!passwordSaving" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                        <svg v-else xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
                        {{ passwordSaving ? (ar ? 'جارٍ التغيير…' : 'Changing…') : (ar ? 'تغيير كلمة المرور' : 'Change Password') }}
                    </button>
                </div>
            </div>

        </div><!-- /create-page -->

        <!-- ══ TOAST ══════════════════════════════════════════════ -->
        <Transition name="toast-fade">
            <div v-if="toast" class="toast" :class="`toast--${toast.type}`">
                <svg v-if="toast.type === 'success'" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
                <svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                {{ toast.msg }}
            </div>
        </Transition>

    </AppLayout>
</template>

<style scoped>
.create-page {
    padding: 16px 16px 120px;
    max-width: 1250px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

/* ══ Hero ════════════════════════════════════════════════════════ */
.create-hero {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    border-top: 3px solid var(--color-primary);
    padding: 20px;
    box-shadow: var(--shadow-card);
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.create-hero__icon {
    width: 48px; height: 48px;
    border-radius: var(--radius-md);
    background: rgba(29, 158, 117, 0.1);
    color: var(--color-primary);
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
}

.create-hero__text { display: flex; flex-direction: column; gap: 4px; }

.create-hero__title {
    font-size: 18px; font-weight: 700;
    color: var(--color-text-primary);
    line-height: 1.3; margin: 0;
}

.create-hero__sub {
    font-size: 12px; color: var(--color-text-muted);
    line-height: 1.6; margin: 0;
}

.create-hero__steps {
    display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
    padding-top: 4px; border-top: 1px solid var(--color-border);
}

.hero-badge {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 3px 10px; border-radius: var(--radius-pill);
    font-size: 11px; font-weight: 600;
}

/* ══ Section cards ═══════════════════════════════════════════════ */
.form-section {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    border-inline-start: 3px solid var(--color-primary);
    padding: 18px 18px 20px;
    box-shadow: var(--shadow-card);
    display: flex; flex-direction: column; gap: 14px;
}

.form-section__header {
    display: flex; align-items: flex-start; gap: 10px;
    padding-bottom: 12px; border-bottom: 1px solid var(--color-border);
}

.form-section__icon {
    width: 28px; height: 28px;
    border-radius: var(--radius-sm);
    background: rgba(29, 158, 117, 0.1);
    color: var(--color-primary);
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0; margin-top: 1px;
}

.form-section__title { font-size: 13px; font-weight: 700; color: var(--color-text-primary); }
.form-section__sub   { font-size: 11px; color: var(--color-text-muted); margin-top: 2px; }

/* ══ Form primitives ═════════════════════════════════════════════ */
.form-row   { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.form-group { display: flex; flex-direction: column; gap: 5px; margin-bottom: 4px; }

.form-label    { font-size: 12px; font-weight: 600; color: var(--color-text-secondary); }
.form-required { color: var(--color-primary); }
.form-hint     { font-size: 11px; color: var(--color-text-muted); margin-top: 2px; }
.form-error    { font-size: 11px; color: #e53e3e; margin-top: 2px; }

.form-input {
    background: var(--color-bg);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 9px 12px;
    font-size: 13px; color: var(--color-text-primary);
    outline: none; width: 100%; font-family: inherit; box-sizing: border-box;
    transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}

.form-input:focus {
    border-color: var(--color-primary);
    box-shadow: 0 0 0 3px rgba(29, 158, 117, 0.1);
}

.form-input--error  { border-color: #e53e3e; }
.form-textarea      { resize: vertical; min-height: 80px; }

/* @ prefix input */
.input-prefix-wrap { position: relative; }
.input-prefix {
    position: absolute; inset-inline-start: 11px; top: 50%;
    transform: translateY(-50%);
    font-size: 13px; font-weight: 600; color: var(--color-primary);
    pointer-events: none;
}
.form-input--prefix { padding-inline-start: 26px; }

/* Eye toggle input */
.input-eye-wrap { position: relative; }
.form-input--eye { padding-inline-end: 40px; }
.eye-btn {
    position: absolute; inset-inline-end: 10px; top: 50%;
    transform: translateY(-50%);
    background: none; border: none; cursor: pointer;
    color: var(--color-text-muted); padding: 0;
    display: flex; align-items: center;
}
.eye-btn:hover { color: var(--color-primary); }

/* ══ Type chips ══════════════════════════════════════════════════ */
.type-chips { display: flex; gap: 6px; flex-wrap: wrap; }

.type-chip {
    padding: 5px 12px; border-radius: 20px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-secondary);
    font-size: 12px; font-weight: 500; cursor: pointer;
    transition: all var(--transition-fast); font-family: inherit;
}

.type-chip:hover { border-color: var(--color-primary); color: var(--color-primary); }

.type-chip--active {
    border-color: var(--color-primary); color: var(--color-primary);
    background: rgba(29, 158, 117, 0.08); font-weight: 600;
}

/* ══ Hub chips ═══════════════════════════════════════════════════ */
.hub-chips { display: flex; gap: 8px; flex-wrap: wrap; }

.hub-chip {
    display: inline-flex; align-items: center; gap: 7px;
    padding: 7px 16px; border-radius: 20px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-secondary);
    font-size: 13px; font-weight: 500; cursor: pointer;
    transition: all var(--transition-fast); font-family: inherit;
}

.hub-chip:hover { border-color: var(--color-primary); color: var(--color-primary); }
.hub-chip--active { font-weight: 600; }

.hub-chip__dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }

/* ══ Toggle switch ═══════════════════════════════════════════════ */
.toggle-row {
    display: flex; align-items: center; justify-content: space-between;
    gap: 16px; padding: 10px 0;
    border-bottom: 1px solid var(--color-border-light);
}

.toggle-row:last-child { border-bottom: none; padding-bottom: 0; }

.toggle-info { flex: 1; min-width: 0; }

.toggle-label {
    font-size: 13px; font-weight: 600;
    color: var(--color-text-primary);
}

.toggle-desc {
    font-size: 11px; color: var(--color-text-muted);
    margin-top: 2px; line-height: 1.5;
}

.toggle-switch {
    position: relative; width: 44px; height: 24px;
    border-radius: 12px; border: none; cursor: pointer;
    background: var(--color-border); flex-shrink: 0;
    transition: background var(--transition-base);
}

.toggle-switch--on { background: var(--color-primary); }

.toggle-thumb {
    position: absolute; top: 3px; inset-inline-start: 3px;
    width: 18px; height: 18px; border-radius: 50%;
    background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.2);
    transition: inset-inline-start var(--transition-base);
}

.toggle-switch--on .toggle-thumb { inset-inline-start: 23px; }

.notif-list { display: flex; flex-direction: column; }

/* ══ Section footer (save button row) ═══════════════════════════ */
.section-footer {
    display: flex; padding-top: 4px;
    border-top: 1px solid var(--color-border-light);
}

.submit-btn {
    display: inline-flex; align-items: center; gap: 7px;
    padding: 10px 20px;
    background: var(--color-primary); color: #fff;
    border: none; border-radius: var(--radius-md);
    font-size: 13px; font-weight: 600; cursor: pointer;
    font-family: inherit;
    transition: background var(--transition-fast), box-shadow var(--transition-fast);
    box-shadow: var(--shadow-button);
}

.submit-btn:hover:not(:disabled) {
    background: var(--color-primary-light);
    box-shadow: 0 4px 14px rgba(29, 158, 117, 0.35);
}

.submit-btn:disabled { opacity: 0.6; cursor: not-allowed; }

.submit-btn--danger { background: var(--color-danger); box-shadow: none; }
.submit-btn--danger:hover:not(:disabled) {
    background: #c0392b;
    box-shadow: 0 4px 14px rgba(216, 90, 48, 0.35);
}

/* ══ Toast ═══════════════════════════════════════════════════════ */
.toast {
    position: fixed; bottom: 80px; left: 50%; transform: translateX(-50%);
    z-index: var(--z-toast);
    display: inline-flex; align-items: center; gap: 8px;
    padding: 10px 18px;
    border-radius: var(--radius-lg);
    font-size: 13px; font-weight: 600;
    box-shadow: var(--shadow-float);
    white-space: nowrap;
}

.toast--success { background: var(--color-success); color: #fff; }
.toast--error   { background: var(--color-danger);  color: #fff; }

.toast-fade-enter-active { transition: opacity 0.2s ease, transform 0.2s ease; }
.toast-fade-leave-active { transition: opacity 0.3s ease, transform 0.3s ease; }
.toast-fade-enter-from   { opacity: 0; transform: translateX(-50%) translateY(10px); }
.toast-fade-leave-to     { opacity: 0; transform: translateX(-50%) translateY(-6px); }

@keyframes spin { to { transform: rotate(360deg); } }
.spin { animation: spin 0.8s linear infinite; }

/* ══ Desktop ══════════════════════════════════════════════════════ */
@media (min-width: 768px) {
    .create-page { padding: 24px 32px 60px; }

    .create-hero {
        flex-direction: row; flex-wrap: wrap;
        align-items: flex-start; gap: 16px;
    }

    .create-hero__icon { margin-top: 2px; }
    .create-hero__text { flex: 1; min-width: 0; }
    .create-hero__steps { width: 100%; padding-top: 12px; }

    .toast { bottom: 32px; }
}

@media (max-width: 519px) {
    .form-row { grid-template-columns: 1fr; }
}
</style>
