<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/JobClub/CvPool/MyProfile.vue
//  Location: resources/js/Pages/Member/JobClub/CvPool/MyProfile.vue
//
//  The member's own CV profile — create or edit.
//  Visibility toggle to show/hide from the pool.
//
//  MOBILE  (<768px): Single column form, sticky save button
//  DESKTOP (≥768px): Two-column — form left, preview card right
//
//  Rules:
//    - Zero DB calls — all data from CvService via Inertia props
//    - No hardcoded hex — all var(--color-*) tokens
//    - Both themes automatic via CSS variables
//    - Personal info (name, email, phone) never on this page
// ══════════════════════════════════════════════════════════════════

import { ref, computed }        from 'vue';
import { Head, useForm, router } from '@inertiajs/vue3';
import { useAuthStore }          from '@/Stores/useAuthStore';
import AppLayout                 from '@/Layouts/AppLayout.vue';

const props = defineProps({
    profile:    { type: Object,  default: null },
    allHubs:    { type: Array,   required: true },
    hasProfile: { type: Boolean, default: false },
});

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

// ── Form ──────────────────────────────────────────────────────────
const form = useForm({
    job_title:           props.profile?.job_title           ?? '',
    current_industry:    props.profile?.current_industry    ?? '',
    years_experience:    props.profile?.years_experience    ?? 0,
    experience_level:    props.profile?.experience_level    ?? 'fresh',
    skills:              props.profile?.skills              ?? [],
    hub_ids:             props.profile?.hub_ids             ?? [],
    education_level:     props.profile?.education_level     ?? 'bachelor',
    education_field:     props.profile?.education_field     ?? '',
    location_country:    props.profile?.location_country    ?? 'Egypt',
    location_city:       props.profile?.location_city       ?? '',
    summary:             props.profile?.summary             ?? '',
    preferred_sectors:   props.profile?.preferred_sectors   ?? [],
    job_type_preference: props.profile?.job_type_preference ?? null,
    open_to_relocation:  props.profile?.open_to_relocation  ?? false,
    is_visible:          props.profile?.is_visible          ?? true,
});

// ── Skills input ──────────────────────────────────────────────────
const skillInput = ref('');

function addSkill() {
    const s = skillInput.value.trim();
    if (s && !form.skills.includes(s) && form.skills.length < 20) {
        form.skills.push(s);
    }
    skillInput.value = '';
}

function removeSkill(i) {
    form.skills.splice(i, 1);
}

function onSkillKeydown(e) {
    if (e.key === 'Enter' || e.key === ',') {
        e.preventDefault();
        addSkill();
    }
}

// ── Hub selection ─────────────────────────────────────────────────
function toggleHub(id) {
    const idx = form.hub_ids.indexOf(id);
    if (idx === -1) {
        form.hub_ids.push(id);
    } else {
        form.hub_ids.splice(idx, 1);
    }
}

// ── Visibility toggle ─────────────────────────────────────────────
const isVisible    = ref(props.profile?.is_visible ?? true);
const togglingVis  = ref(false);

async function toggleVisibility() {
    if (togglingVis.value) return;
    togglingVis.value = true;
    try {
        const res = await fetch(route('member.cv.toggle'), {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
        });
        const data = await res.json();
        isVisible.value = data.is_visible;
    } finally {
        togglingVis.value = false;
    }
}

// ── Save ──────────────────────────────────────────────────────────
function save() {
    form.post(route('member.cv.save'));
}

// ── Helpers ───────────────────────────────────────────────────────
const experienceLevels = [
    { value: 'student', en: 'Student',    ar: 'طالب' },
    { value: 'fresh',   en: 'Fresh',      ar: 'خريج جديد' },
    { value: 'junior',  en: 'Junior',     ar: 'مبتدئ' },
    { value: 'mid',     en: 'Mid-level',  ar: 'متوسط' },
    { value: 'senior',  en: 'Senior',     ar: 'خبير' },
];

const educationLevels = [
    { value: 'diploma',  en: 'Diploma',  ar: 'دبلوم' },
    { value: 'bachelor', en: 'Bachelor', ar: 'بكالوريوس' },
    { value: 'master',   en: 'Master',   ar: 'ماجستير' },
    { value: 'phd',      en: 'PhD',      ar: 'دكتوراه' },
];

const jobTypes = [
    { value: 'full_time',  en: 'Full Time',  ar: 'دوام كامل' },
    { value: 'part_time',  en: 'Part Time',  ar: 'دوام جزئي' },
    { value: 'both',       en: 'Both',       ar: 'كلاهما' },
];

function hubColor(hub) {
    return hub.color ?? 'var(--color-primary)';
}
</script>

<template>
    <Head :title="ar ? 'سيرتي الذاتية' : 'My CV'" />

    <AppLayout>
        <div class="mycv-page">

            <!-- ── Page header ──────────────────────────────────── -->
            <div class="mycv-header">
                <div class="mycv-header-text">
                    <h1 class="mycv-title">{{ ar ? 'سيرتي الذاتية' : 'My CV' }}</h1>
                    <p class="mycv-sub">
                        {{ ar
                            ? 'ملفك مجهول في المجمع — أصحاب العمل يرون المهارات فقط، ليس اسمك'
                            : 'Your profile is anonymous in the pool — employers see skills only, not your name' }}
                    </p>
                </div>

                <!-- Visibility badge -->
                <div v-if="hasProfile"
                     class="vis-badge"
                     :class="isVisible ? 'vis-badge--on' : 'vis-badge--off'"
                     @click="toggleVisibility">
                    <i :class="isVisible ? 'ti ti-eye' : 'ti ti-eye-off'"></i>
                    <span>{{ isVisible
                        ? (ar ? 'ظاهر في المجمع' : 'Visible in Pool')
                        : (ar ? 'مخفي من المجمع' : 'Hidden from Pool') }}</span>
                    <span v-if="togglingVis" class="vis-spinner"></span>
                </div>
            </div>

            <!-- ── Two-column on desktop ────────────────────────── -->
            <div class="mycv-body">

                <!-- ── Form ──────────────────────────────────────── -->
                <div class="mycv-form-col">

                    <!-- Job title + Industry -->
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'المسمى الوظيفي' : 'Job Title' }}</label>
                            <input v-model="form.job_title"
                                   class="form-input"
                                   :placeholder="ar ? 'مثال: محلل مالي' : 'e.g. Financial Analyst'" />
                            <div v-if="form.errors.job_title" class="form-error">{{ form.errors.job_title }}</div>
                        </div>

                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'القطاع الحالي' : 'Current Industry' }}</label>
                            <input v-model="form.current_industry"
                                   class="form-input"
                                   :placeholder="ar ? 'مثال: التصنيع' : 'e.g. Manufacturing'" />
                        </div>
                    </div>

                    <!-- Experience -->
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'سنوات الخبرة' : 'Years of Experience' }}</label>
                            <input v-model.number="form.years_experience"
                                   type="number" min="0" max="50"
                                   class="form-input" />
                        </div>

                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'مستوى الخبرة' : 'Experience Level' }}</label>
                            <select v-model="form.experience_level" class="form-input">
                                <option v-for="lvl in experienceLevels"
                                        :key="lvl.value"
                                        :value="lvl.value">
                                    {{ ar ? lvl.ar : lvl.en }}
                                </option>
                            </select>
                        </div>
                    </div>

                    <!-- Education -->
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'المؤهل التعليمي' : 'Education Level' }}</label>
                            <select v-model="form.education_level" class="form-input">
                                <option v-for="edu in educationLevels"
                                        :key="edu.value"
                                        :value="edu.value">
                                    {{ ar ? edu.ar : edu.en }}
                                </option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'مجال الدراسة' : 'Field of Study' }}</label>
                            <input v-model="form.education_field"
                                   class="form-input"
                                   :placeholder="ar ? 'مثال: محاسبة' : 'e.g. Accounting'" />
                        </div>
                    </div>

                    <!-- Location -->
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'الدولة' : 'Country' }}</label>
                            <input v-model="form.location_country"
                                   class="form-input"
                                   :placeholder="ar ? 'مصر' : 'Egypt'" />
                        </div>

                        <div class="form-group">
                            <label class="form-label">{{ ar ? 'المدينة' : 'City' }}</label>
                            <input v-model="form.location_city"
                                   class="form-input"
                                   :placeholder="ar ? 'القاهرة' : 'Cairo'" />
                        </div>
                    </div>

                    <!-- Job type preference -->
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'نوع الوظيفة المفضل' : 'Preferred Job Type' }}</label>
                        <select v-model="form.job_type_preference" class="form-input">
                            <option :value="null">{{ ar ? 'غير محدد' : 'Not specified' }}</option>
                            <option v-for="jt in jobTypes"
                                    :key="jt.value"
                                    :value="jt.value">
                                {{ ar ? jt.ar : jt.en }}
                            </option>
                        </select>
                    </div>

                    <!-- Open to relocation -->
                    <div class="form-check">
                        <input id="relocation"
                               v-model="form.open_to_relocation"
                               type="checkbox"
                               class="form-checkbox" />
                        <label for="relocation" class="form-check-label">
                            {{ ar ? 'منفتح على الانتقال' : 'Open to relocation' }}
                        </label>
                    </div>

                    <!-- Hubs -->
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'المجالات' : 'Hubs' }}</label>
                        <div class="hub-chips">
                            <button
                                v-for="hub in allHubs"
                                :key="hub.id"
                                type="button"
                                class="hub-chip"
                                :class="{ 'hub-chip--active': form.hub_ids.includes(hub.id) }"
                                :style="form.hub_ids.includes(hub.id) ? `border-color:${hubColor(hub)};color:${hubColor(hub)}` : ''"
                                @click="toggleHub(hub.id)">
                                {{ ar ? hub.name_ar : hub.name_en }}
                            </button>
                        </div>
                        <div v-if="form.errors.hub_ids" class="form-error">{{ form.errors.hub_ids }}</div>
                    </div>

                    <!-- Skills -->
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'المهارات' : 'Skills' }}</label>
                        <div class="skill-input-wrap">
                            <input v-model="skillInput"
                                   class="form-input"
                                   :placeholder="ar ? 'أضف مهارة واضغط Enter' : 'Add a skill and press Enter'"
                                   @keydown="onSkillKeydown" />
                            <button type="button" class="skill-add-btn" @click="addSkill">+</button>
                        </div>
                        <div class="skill-chips">
                            <span v-for="(s, i) in form.skills"
                                  :key="i"
                                  class="skill-chip">
                                {{ s }}
                                <button type="button" @click="removeSkill(i)" class="skill-remove">×</button>
                            </span>
                        </div>
                        <div v-if="form.errors.skills" class="form-error">{{ form.errors.skills }}</div>
                    </div>

                    <!-- Summary -->
                    <div class="form-group">
                        <label class="form-label">{{ ar ? 'نبذة مختصرة (اختياري)' : 'Summary (optional)' }}</label>
                        <textarea v-model="form.summary"
                                  class="form-input form-textarea"
                                  rows="3"
                                  maxlength="500"
                                  :placeholder="ar
                                      ? 'صف خبرتك المهنية بإيجاز...'
                                      : 'Briefly describe your professional background...'" />
                        <div class="form-char-count">{{ form.summary.length }} / 500</div>
                    </div>

                    <!-- Save -->
                    <button type="button"
                            class="save-btn"
                            :disabled="form.processing"
                            @click="save">
                        <span v-if="form.processing">{{ ar ? 'جاري الحفظ...' : 'Saving...' }}</span>
                        <span v-else>{{ ar ? 'حفظ الملف' : 'Save Profile' }}</span>
                    </button>

                </div><!-- /form-col -->

                <!-- ── Preview card (desktop only) ───────────────── -->
                <div class="mycv-preview-col">
                    <div class="preview-card">
                        <div class="preview-card__title">{{ ar ? 'معاينة كما يراها الآخرون' : 'Preview as others see it' }}</div>

                        <div class="preview-job">{{ form.job_title || (ar ? 'المسمى الوظيفي' : 'Job Title') }}</div>
                        <div class="preview-meta">
                            <span>{{ form.years_experience }} {{ ar ? 'سنة' : 'yrs' }}</span>
                            <span class="preview-dot">·</span>
                            <span>{{ form.location_city || form.location_country }}</span>
                        </div>

                        <div v-if="form.skills.length" class="preview-skills">
                            <span v-for="s in form.skills.slice(0,6)" :key="s" class="preview-skill">{{ s }}</span>
                        </div>

                        <div v-if="form.summary" class="preview-summary">{{ form.summary }}</div>

                        <div class="preview-anon-note">
                            <i class="ti ti-lock"></i>
                            {{ ar ? 'اسمك وبريدك وهاتفك مخفيون دائماً' : 'Your name, email and phone are always hidden' }}
                        </div>
                    </div>
                </div>

            </div><!-- /mycv-body -->

        </div><!-- /mycv-page -->
    </AppLayout>
</template>

<style scoped>
/* ── Page ──────────────────────────────────────────────────────── */
.mycv-page {
    padding: 20px 20px 80px;
}

/* ── Header ────────────────────────────────────────────────────── */
.mycv-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 20px;
    flex-wrap: wrap;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--color-border);
}

.mycv-title {
    font-size: 22px;
    font-weight: 700;
    color: var(--color-text-primary);
    margin: 0 0 4px;
}

.mycv-sub {
    font-size: 12px;
    color: var(--color-text-muted);
    margin: 0;
}

/* ── Visibility badge ──────────────────────────────────────────── */
.vis-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 7px 14px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    border: 1.5px solid;
    transition: all var(--transition-fast);
    white-space: nowrap;
    flex-shrink: 0;
}

.vis-badge--on  { color: var(--color-primary); border-color: var(--color-primary); }
.vis-badge--off { color: var(--color-text-muted); border-color: var(--color-border); }

.vis-spinner {
    width: 12px;
    height: 12px;
    border: 2px solid currentColor;
    border-top-color: transparent;
    border-radius: 50%;
    animation: spin 0.6s linear infinite;
    display: inline-block;
}

@keyframes spin { to { transform: rotate(360deg); } }

/* ── Body layout ───────────────────────────────────────────────── */
.mycv-body {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

/* ── Form column — the card that wraps the form ─────────────────── */
.mycv-form-col {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    padding: 20px;
    box-shadow: var(--shadow-card);
}

/* ── Section dividers inside the form ──────────────────────────── */
.form-section {
    padding-bottom: 16px;
    margin-bottom: 4px;
    border-bottom: 1px solid var(--color-border);
}

.form-section:last-of-type { border-bottom: none; }

/* ── Two-column rows ────────────────────────────────────────────── */
.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 14px;
}

/* ── Individual field ───────────────────────────────────────────── */
.form-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-bottom: 14px;
}

.form-group:last-child { margin-bottom: 0; }

.form-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--color-text-secondary);
    display: block;
}

.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;
    transition: border-color var(--transition-fast);
    width: 100%;
    font-family: inherit;
    box-sizing: border-box;
}

.form-input:focus { border-color: var(--color-primary); }

.form-textarea { resize: vertical; min-height: 80px; }

.form-char-count {
    font-size: 11px;
    color: var(--color-text-muted);
    text-align: end;
}

.form-error { font-size: 11px; color: #e53e3e; }

.form-check {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 14px;
}

.form-checkbox {
    width: 16px;
    height: 16px;
    accent-color: var(--color-primary);
    cursor: pointer;
    flex-shrink: 0;
}

.form-check-label {
    font-size: 13px;
    color: var(--color-text-secondary);
    cursor: pointer;
}

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

.hub-chip {
    padding: 5px 14px;
    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);
}

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

/* ── Skills ────────────────────────────────────────────────────── */
.skill-input-wrap { display: flex; gap: 8px; }

.skill-add-btn {
    background: var(--color-primary);
    color: #fff;
    border: none;
    border-radius: var(--radius-md);
    width: 38px;
    height: 38px;
    font-size: 20px;
    cursor: pointer;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
}

.skill-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }

.skill-chip {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    background: var(--color-bg);
    border: 1px solid var(--color-border);
    border-radius: 20px;
    padding: 3px 10px;
    font-size: 12px;
    color: var(--color-text-secondary);
}

.skill-remove {
    background: none;
    border: none;
    color: var(--color-text-muted);
    cursor: pointer;
    font-size: 14px;
    padding: 0;
    line-height: 1;
}

/* ── Save button ───────────────────────────────────────────────── */
.save-btn {
    background: var(--color-primary);
    color: #fff;
    border: none;
    border-radius: var(--radius-md);
    padding: 12px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    width: 100%;
    transition: background var(--transition-fast);
    box-shadow: var(--shadow-button);
    margin-top: 4px;
}

.save-btn:hover:not(:disabled) { background: var(--color-primary-light); }
.save-btn:disabled { opacity: 0.6; cursor: not-allowed; }

/* ── Preview card (hidden on mobile) ───────────────────────────── */
.mycv-preview-col { display: none; }

.preview-card {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    padding: 20px;
    box-shadow: var(--shadow-card);
    position: sticky;
    top: 76px;
}

.preview-card__title {
    font-size: 10px;
    font-weight: 700;
    color: var(--color-text-muted);
    text-transform: uppercase;
    letter-spacing: 0.07em;
    margin-bottom: 14px;
}

.preview-job {
    font-size: 15px;
    font-weight: 700;
    color: var(--color-text-primary);
    margin-bottom: 5px;
}

.preview-meta {
    font-size: 12px;
    color: var(--color-text-muted);
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 12px;
}

.preview-dot { opacity: 0.4; }

.preview-skills {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-bottom: 12px;
}

.preview-skill {
    background: var(--color-bg);
    border: 1px solid var(--color-border);
    border-radius: 20px;
    padding: 2px 9px;
    font-size: 11px;
    color: var(--color-text-secondary);
}

.preview-summary {
    font-size: 12px;
    color: var(--color-text-secondary);
    line-height: 1.6;
    margin-bottom: 14px;
}

.preview-anon-note {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 11px;
    color: var(--color-primary);
    background: rgba(29, 158, 117, 0.08);
    border-radius: var(--radius-sm);
    padding: 8px 10px;
}

/* ── Desktop ≥768px ────────────────────────────────────────────── */
@media (min-width: 768px) {
    .mycv-page { padding: 24px 28px 60px; }

    .mycv-body {
        flex-direction: row;
        align-items: flex-start;
        gap: 20px;
    }

    .mycv-form-col    { flex: 1; min-width: 0; }
    .mycv-preview-col { display: block; width: 220px; flex-shrink: 0; }
}
</style>