<script setup>
import { ref, computed } from 'vue'
import { useForm, Link } from '@inertiajs/vue3'
import AppLayout from '@/Layouts/AppLayout.vue'
import { useAuthStore } from '@/Stores/useAuthStore'

const auth   = useAuthStore()
const locale = computed(() => auth.locale)
const t      = (en, ar) => locale.value === 'ar' ? ar : en

const props = defineProps({
    hubs:      { type: Array,  default: () => [] },
    myProfile: { type: Object, required: true },    // always present on edit
})

// ── Services dynamic list — pre-filled ───────────────────────
const services = ref(
    props.myProfile.services?.length
        ? [...props.myProfile.services]
        : ['']
)
function addService()     { if (services.value.length < 10) services.value.push('') }
function removeService(i) { if (services.value.length > 1)  services.value.splice(i, 1) }

// ── Form — pre-filled with existing values ────────────────────
const form = useForm({
    hub_id:           props.myProfile.hub_id           ?? '',
    headline:         props.myProfile.headline          ?? '',
    description:      props.myProfile.description       ?? '',
    services:         props.myProfile.services          ?? [],
    sector_expertise: props.myProfile.sector_expertise  ?? [],
    experience_level: props.myProfile.experience_level  ?? '',
    availability:     props.myProfile.availability      ?? '',
    rate_min_egp:     props.myProfile.rate_min_egp      ?? '',
    rate_max_egp:     props.myProfile.rate_max_egp      ?? '',
    rate_is_visible:  props.myProfile.rate_is_visible   ?? true,
    linkedin_url:     props.myProfile.linkedin_url      ?? '',
})

function submit() {
    form.services = services.value.filter(s => s.trim() !== '')
    form.put(route('member.freelance.profile.update', props.myProfile.id))
}

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

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 سنة' },
]

// ── Toggle active state directly ──────────────────────────────
const toggling    = ref(false)
const isActive    = ref(props.myProfile.is_active)

async function toggleActive() {
    toggling.value = true
    try {
        const res = await fetch(
            route('member.freelance.profile.toggle', props.myProfile.id),
            {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                },
            }
        )
        const data = await res.json()
        isActive.value = data.is_active
    } finally {
        toggling.value = false
    }
}
</script>

<template>
    <AppLayout>
        <div class="fp-page">
            <div class="fp-container">

                <div class="fp-header">
                    <Link :href="route('member.freelance.index')" class="fp-back">
                        ← {{ t('Help & Earn', 'المساعدة والكسب') }}
                    </Link>
                    <div class="fp-header-row">
                        <h1 class="fp-title">{{ t('Edit Your Profile', 'تعديل ملفك الشخصي') }}</h1>
                        <!-- Active toggle — lives here, not in the form -->
                        <button
                            type="button"
                            class="fp-toggle"
                            :class="isActive ? 'fp-toggle--active' : 'fp-toggle--inactive'"
                            :disabled="toggling"
                            @click="toggleActive"
                        >
                            <span class="fp-toggle-dot"></span>
                            {{ isActive ? t('Live', 'نشط') : t('Hidden', 'مخفي') }}
                        </button>
                    </div>
                    <p class="fp-subtitle">
                        {{ t(
                            'Keep your profile accurate — seekers rely on it to decide whether to send you an interest.',
                            'احرص على دقة ملفك — يعتمد عليه الباحثون لاتخاذ قرار إرسال الاهتمام إليك.'
                        ) }}
                    </p>
                    <!-- View public profile link -->
                    <Link
                        :href="route('member.freelance.profile.show', myProfile.id)"
                        class="fp-view-link"
                    >
                        {{ t('View your public profile →', 'عرض ملفك العام →') }}
                    </Link>
                </div>

                <form @submit.prevent="submit" class="fp-form">

                    <!-- ── Hub ─────────────────────────────── -->
                    <div class="fp-field">
                        <label class="fp-label">
                            {{ t('Professional Hub', 'المجال المهني') }}
                            <span class="fp-required">*</span>
                        </label>
                        <div class="fp-hub-grid">
                            <button
                                v-for="hub in hubs"
                                :key="hub.id"
                                type="button"
                                class="fp-hub-btn"
                                :class="{ 'fp-hub-btn--active': String(form.hub_id) === String(hub.id) }"
                                :style="String(form.hub_id) === String(hub.id)
                                    ? { borderColor: hubColor(hub.slug), background: hubColor(hub.slug) + '18', color: hubColor(hub.slug) }
                                    : {}"
                                @click="form.hub_id = hub.id"
                            >
                                <span class="fp-hub-dot" :style="{ background: hubColor(hub.slug) }"></span>
                                {{ locale === 'ar' ? hub.name_ar : hub.name_en }}
                            </button>
                        </div>
                        <p v-if="form.errors.hub_id" class="fp-error">{{ form.errors.hub_id }}</p>
                    </div>

                    <!-- ── Headline ───────────────────────── -->
                    <div class="fp-field">
                        <label class="fp-label">
                            {{ t('Professional Headline', 'العنوان المهني') }}
                            <span class="fp-required">*</span>
                        </label>
                        <input
                            v-model="form.headline"
                            type="text"
                            class="fp-input"
                            :placeholder="t(
                                'e.g. Financial Modelling & Feasibility Studies',
                                'مثال: النمذجة المالية ودراسات الجدوى'
                            )"
                            maxlength="120"
                        />
                        <p class="fp-hint">{{ form.headline.length }}/120</p>
                        <p v-if="form.errors.headline" class="fp-error">{{ form.errors.headline }}</p>
                    </div>

                    <!-- ── Description ────────────────────── -->
                    <div class="fp-field">
                        <label class="fp-label">
                            {{ t('About Your Services', 'نبذة عن خدماتك') }}
                            <span class="fp-required">*</span>
                        </label>
                        <textarea
                            v-model="form.description"
                            class="fp-textarea"
                            rows="5"
                            maxlength="1000"
                            :placeholder="t(
                                'Describe what you do, your experience, and the type of work you are looking for…',
                                'صف ما تفعله وخبرتك ونوع العمل الذي تبحث عنه…'
                            )"
                        ></textarea>
                        <p class="fp-hint">{{ form.description.length }}/1000</p>
                        <p v-if="form.errors.description" class="fp-error">{{ form.errors.description }}</p>
                    </div>

                    <!-- ── Services list ──────────────────── -->
                    <div class="fp-field">
                        <label class="fp-label">
                            {{ t('Specific Services You Offer', 'الخدمات المحددة التي تقدمها') }}
                            <span class="fp-required">*</span>
                        </label>
                        <p class="fp-hint">{{ t('Add up to 10 specific services', 'أضف حتى 10 خدمات محددة') }}</p>
                        <div class="fp-services-list">
                            <div v-for="(service, i) in services" :key="i" class="fp-service-row">
                                <input
                                    v-model="services[i]"
                                    type="text"
                                    class="fp-input"
                                    :placeholder="t('e.g. Cash flow modelling', 'مثال: نمذجة التدفق النقدي')"
                                    maxlength="80"
                                />
                                <button
                                    v-if="services.length > 1"
                                    type="button"
                                    class="fp-remove-btn"
                                    @click="removeService(i)"
                                >✕</button>
                            </div>
                        </div>
                        <button
                            v-if="services.length < 10"
                            type="button"
                            class="fp-add-btn"
                            @click="addService"
                        >+ {{ t('Add Service', 'إضافة خدمة') }}</button>
                        <p v-if="form.errors.services" class="fp-error">{{ form.errors.services }}</p>
                    </div>

                    <!-- ── Experience + Availability ──────── -->
                    <div class="fp-row-two">
                        <div class="fp-field">
                            <label class="fp-label">
                                {{ t('Experience Level', 'مستوى الخبرة') }}
                                <span class="fp-required">*</span>
                            </label>
                            <div class="fp-chips">
                                <button
                                    v-for="lvl in experienceLevels"
                                    :key="lvl.value"
                                    type="button"
                                    class="fp-chip"
                                    :class="{ 'fp-chip--active': form.experience_level === lvl.value }"
                                    @click="form.experience_level = lvl.value"
                                >{{ locale === 'ar' ? lvl.ar : lvl.en }}</button>
                            </div>
                            <p v-if="form.errors.experience_level" class="fp-error">{{ form.errors.experience_level }}</p>
                        </div>
                        <div class="fp-field">
                            <label class="fp-label">
                                {{ t('Availability', 'التوفر') }}
                                <span class="fp-required">*</span>
                            </label>
                            <select v-model="form.availability" class="fp-select">
                                <option value="">{{ t('Select…', 'اختر…') }}</option>
                                <option value="weekends">{{ t('Weekends only', 'الإجازات فقط') }}</option>
                                <option value="evenings">{{ t('Evenings after work', 'المساءات بعد العمل') }}</option>
                                <option value="full">{{ t('Fully available', 'متفرغ كامل') }}</option>
                                <option value="unavailable">{{ t('Unavailable now', 'غير متاح الآن') }}</option>
                            </select>
                            <p v-if="form.errors.availability" class="fp-error">{{ form.errors.availability }}</p>
                        </div>
                    </div>

                    <!-- ── Rate range ─────────────────────── -->
                    <div class="fp-field">
                        <label class="fp-label">{{ t('Day Rate Range (EGP) — Optional', 'نطاق الأجر اليومي (جنيه) — اختياري') }}</label>
                        <div class="fp-rate-row">
                            <input v-model="form.rate_min_egp" type="number" class="fp-input" :placeholder="t('Min', 'الأدنى')" min="0" />
                            <span class="fp-rate-sep">–</span>
                            <input v-model="form.rate_max_egp" type="number" class="fp-input" :placeholder="t('Max', 'الأقصى')" min="0" />
                        </div>
                        <label class="fp-check-label">
                            <input v-model="form.rate_is_visible" type="checkbox" class="fp-check" />
                            {{ t('Show rate on my profile', 'عرض الأجر على ملفي') }}
                        </label>
                        <p v-if="form.errors.rate_max_egp" class="fp-error">{{ form.errors.rate_max_egp }}</p>
                    </div>

                    <!-- ── LinkedIn URL ────────────────────── -->
                    <div class="fp-field">
                        <label class="fp-label">
                            {{ t('LinkedIn Profile URL — Optional', 'رابط ملف LinkedIn — اختياري') }}
                        </label>
                        <p class="fp-hint">
                            {{ t(
                                'A LinkedIn link builds trust before you have any reviews.',
                                'رابط LinkedIn يبني الثقة قبل أن تحصل على تقييمات.'
                            ) }}
                        </p>
                        <input
                            v-model="form.linkedin_url"
                            type="url"
                            class="fp-input"
                            placeholder="https://www.linkedin.com/in/your-name"
                        />
                        <p v-if="form.errors.linkedin_url" class="fp-error">{{ form.errors.linkedin_url }}</p>
                    </div>

                    <!-- ── Actions ────────────────────────── -->
                    <div class="fp-actions">
                        <Link :href="route('member.freelance.index')" class="fp-cancel">
                            {{ t('Cancel', 'إلغاء') }}
                        </Link>
                        <button type="submit" class="fp-submit" :disabled="form.processing">
                            {{ form.processing ? t('Saving…', 'جارٍ الحفظ…') : t('Save Changes', 'حفظ التغييرات') }}
                        </button>
                    </div>

                </form>
            </div>
        </div>
    </AppLayout>
</template>

<style scoped>
.fp-page      { padding: 16px; }
.fp-container { max-width: 720px; margin: 0 auto; }
.fp-back      { font-size: 13px; color: var(--color-primary); text-decoration: none; display: inline-block; margin-bottom: 12px; }
.fp-header-row { display: flex; align-items: center; gap: 12px; margin-bottom: 6px; }
.fp-title     { font-size: 22px; font-weight: 800; color: var(--color-text); margin: 0; }
.fp-subtitle  { font-size: 13px; color: var(--color-text-muted); margin: 0 0 8px; line-height: 1.6; }
.fp-view-link { font-size: 13px; color: var(--color-primary); text-decoration: none; display: inline-block; margin-bottom: 24px; font-weight: 600; }

/* Active toggle */
.fp-toggle {
    display: flex; align-items: center; gap: 7px;
    padding: 6px 14px; border-radius: 20px;
    border: 2px solid; font-size: 12px; font-weight: 700;
    cursor: pointer; transition: all 0.2s; margin-inline-start: auto;
    flex-shrink: 0;
}
.fp-toggle--active   { border-color: #1D9E75; background: #1D9E7522; color: #1D9E75; }
.fp-toggle--inactive { border-color: var(--color-border); background: var(--color-surface); color: var(--color-text-muted); }
.fp-toggle-dot {
    width: 8px; height: 8px; border-radius: 50%;
    background: currentColor;
}
.fp-toggle:disabled { opacity: 0.6; cursor: not-allowed; }

.fp-form  { display: flex; flex-direction: column; gap: 20px; }
.fp-field { display: flex; flex-direction: column; gap: 6px; }
.fp-label { font-size: 13px; font-weight: 700; color: var(--color-text); }
.fp-required { color: #e53e3e; margin-inline-start: 2px; }
.fp-hint  { font-size: 11px; color: var(--color-text-muted); margin: 0; }
.fp-error { font-size: 12px; color: #e53e3e; margin: 0; }

.fp-input, .fp-textarea, .fp-select {
    padding: 10px 12px;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: 8px; font-size: 13px;
    color: var(--color-text); width: 100%; box-sizing: border-box;
}
.fp-input::placeholder, .fp-textarea::placeholder { color: var(--color-text-muted); }
.fp-input:focus, .fp-textarea:focus, .fp-select:focus {
    outline: none; border-color: var(--color-primary);
    box-shadow: 0 0 0 3px rgba(29,158,117,0.12);
}
.fp-textarea { resize: vertical; }

.fp-chips { display: flex; gap: 6px; flex-wrap: wrap; }
.fp-chip {
    padding: 6px 12px; border-radius: 20px;
    border: 1.5px solid var(--color-border);
    background: transparent; color: var(--color-text-muted);
    font-size: 12px; font-weight: 500; cursor: pointer;
    transition: all 0.15s; font-family: inherit;
}
.fp-chip:hover { border-color: var(--color-primary); color: var(--color-primary); }
.fp-chip--active {
    border-color: var(--color-primary); color: var(--color-primary);
    background: rgba(29,158,117,0.08); font-weight: 600;
}

.fp-hub-grid { display: flex; gap: 8px; flex-wrap: wrap; }
.fp-hub-btn {
    display: flex; align-items: center; gap: 8px;
    padding: 9px 16px; border-radius: 10px;
    border: 2px solid var(--color-border);
    background: var(--color-surface);
    font-size: 13px; font-weight: 600;
    color: var(--color-text-muted); cursor: pointer; transition: all 0.15s;
}
.fp-hub-dot { width: 10px; height: 10px; border-radius: 50%; }

.fp-services-list { display: flex; flex-direction: column; gap: 8px; }
.fp-service-row   { display: flex; gap: 8px; align-items: center; }
.fp-service-row .fp-input { flex: 1; }
.fp-remove-btn {
    width: 32px; height: 38px;
    border: 1px solid var(--color-border);
    background: var(--color-surface); color: var(--color-text-muted);
    border-radius: 8px; cursor: pointer; font-size: 12px; flex-shrink: 0;
}
.fp-add-btn {
    align-self: flex-start; padding: 7px 14px;
    border: 1px dashed var(--color-primary);
    background: transparent; color: var(--color-primary);
    border-radius: 8px; font-size: 13px; font-weight: 600;
    cursor: pointer; margin-top: 4px;
}

.fp-row-two { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }

.fp-rate-row { display: flex; align-items: center; gap: 10px; }
.fp-rate-row .fp-input { flex: 1; }
.fp-rate-sep { color: var(--color-text-muted); font-weight: 700; flex-shrink: 0; }

.fp-check-label {
    display: flex; align-items: center; gap: 8px;
    font-size: 13px; color: var(--color-text-muted);
    cursor: pointer; margin-top: 6px;
}
.fp-check { width: 16px; height: 16px; accent-color: var(--color-primary); }

.fp-actions { display: flex; gap: 10px; padding-top: 8px; }
.fp-cancel {
    padding: 11px 20px; border: 1px solid var(--color-border);
    border-radius: 10px; color: var(--color-text-muted);
    font-size: 14px; font-weight: 600;
    text-decoration: none; text-align: center; white-space: nowrap;
}
.fp-submit {
    flex: 1; padding: 11px 24px;
    background: var(--color-primary); color: #fff;
    border: none; border-radius: 10px;
    font-size: 14px; font-weight: 700; cursor: pointer;
}
.fp-submit:disabled { opacity: 0.6; cursor: not-allowed; }

@media (min-width: 768px) {
    .fp-page    { padding: 32px 24px; }
    .fp-title   { font-size: 26px; }
    .fp-submit  { flex: unset; min-width: 200px; }
}
</style>