<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/JobClub/Jobs/Index.vue
//  Location: resources/js/Pages/Member/JobClub/Jobs/Index.vue
//
//  Redesigned to match Help & Earn quality and layout pattern.
//
//  MOBILE  (<768px): Cards, filter toggle
//  DESKTOP (≥768px): Filter bar top, 2-column card grid
// ══════════════════════════════════════════════════════════════════

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

const props = defineProps({
    listings: { type: Object, required: true },
    allHubs:  { type: Array,  required: true },
    filters:  { type: Object, default: () => ({}) },
});

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

// ── Filters ───────────────────────────────────────────────────────
const showFilters  = ref(false);
const filterHub    = ref(props.filters.hub_id   ?? '');
const filterType   = ref(props.filters.job_type ?? '');
const filterSearch = ref(props.filters.search   ?? '');

function applyFilters() {
    router.get(route('member.jobs.index'), {
        hub_id:   filterHub.value    || undefined,
        job_type: filterType.value   || undefined,
        search:   filterSearch.value || undefined,
    }, { preserveState: true, replace: true });
}

function clearFilters() {
    filterHub.value = '';
    filterType.value = '';
    filterSearch.value = '';
    router.get(route('member.jobs.index'), {}, { replace: true });
}

const hasActiveFilters = computed(() => filterHub.value || filterType.value || filterSearch.value);

// ── Helpers ───────────────────────────────────────────────────────
const jobTypes = [
    { value: 'full_time',   en: 'Full Time',   ar: 'دوام كامل' },
    { value: 'part_time',   en: 'Part Time',   ar: 'دوام جزئي' },
    { value: 'contract',    en: 'Contract',    ar: 'عقد' },
    { value: 'internship',  en: 'Internship',  ar: 'تدريب' },
];

function jobTypeLabel(value) {
    const found = jobTypes.find(j => j.value === value);
    return found ? (ar.value ? found.ar : found.en) : value;
}

function hubName(hub) {
    return ar.value ? hub.name_ar : hub.name_en;
}

function statusBadgeClass(status) {
    if (status === 'pending')   return 'status--pending';
    if (status === 'accepted')  return 'status--accepted';
    if (status === 'connected') return 'status--connected';
    if (status === 'declined')  return 'status--declined';
    return '';
}

function myStatusLabel(status) {
    if (!status) return null;
    const map = {
        pending:   ar.value ? 'تقدمت' : 'Applied',
        accepted:  ar.value ? 'مقبول' : 'Accepted',
        connected: ar.value ? 'متصل' : 'Connected',
        declined:  ar.value ? 'مرفوض' : 'Declined',
    };
    return map[status] ?? status;
}
</script>

<template>
    <Head :title="ar ? 'إعلانات الوظائف' : 'Job Listings'" />

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

            <!-- ── Entry Cards ──────────────────────────────────────── -->
            <div class="jobs-entry-grid">

                <!-- I'm Looking for Work -->
                <div class="jobs-entry-card">
                    <div class="jobs-entry-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
                        </svg>
                    </div>
                    <div class="jobs-entry-text">
                        <strong>{{ ar ? 'أبحث عن عمل' : 'I\'m Looking for Work' }}</strong>
                        <span>{{ ar ? 'تصفح الفرص وقدم طلبك مباشرة' : 'Browse open roles and apply directly' }}</span>
                    </div>
                    <a :href="route('member.cv.profile')" class="jobs-entry-secondary-btn">
                        {{ ar ? 'سيرتي الذاتية' : 'My CV' }}
                    </a>
                    <a :href="route('member.cv.pool')" class="jobs-entry-cta-btn">
                        {{ ar ? 'تصفح المجمع' : 'Browse CV Pool' }}
                    </a>
                </div>

                <!-- I'm Hiring -->
                <div class="jobs-entry-card">
                    <div class="jobs-entry-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
                            <rect x="2" y="7" width="20" height="14" rx="2" ry="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/>
                        </svg>
                    </div>
                    <div class="jobs-entry-text">
                        <strong>{{ ar ? 'أبحث عن موظف' : 'I\'m Hiring' }}</strong>
                        <span>{{ ar ? 'انشر وظيفتك وتواصل مع المرشحين' : 'Post a role and connect with qualified candidates' }}</span>
                    </div>
                    <a :href="route('member.jobs.my-listings')" class="jobs-entry-secondary-btn">
                        {{ ar ? 'إعلاناتي' : 'My Listings' }}
                    </a>
                    <a :href="route('member.jobs.create')" class="jobs-entry-cta-btn">
                        {{ ar ? 'نشر وظيفة' : 'Post a Job' }}
                    </a>
                </div>

            </div>

            <!-- ── Disclaimer ──────────────────────────────────────── -->
            <div class="jobs-disclaimer">
                <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" style="flex-shrink:0; margin-top:1px;">
                    <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>
                <span>{{ ar
                    ? 'InPractice تربط بين المهنيين فقط. لسنا مسؤولين عن طبيعة العقود أو جودة العمل. جميع الترتيبات بينك وبين الطرف الآخر مباشرة.'
                    : 'InPractice connects professionals only. We are not responsible for contract terms, payment, or quality of work. All arrangements are directly between you and the other party.' }}</span>
            </div>

            <!-- ── Tabs ────────────────────────────────────────────── -->
            <div class="jobs-tabs">
                <button class="jobs-tab jobs-tab--active">
                    {{ ar ? 'الوظائف' : 'Job Listings' }}
                    <span class="jobs-tab-count">{{ listings.total }}</span>
                </button>
                <a :href="route('member.cv.pool')" class="jobs-tab">
                    {{ ar ? 'مجمع السير الذاتية' : 'CV Pool' }}
                </a>
            </div>

            <!-- ── Filters ──────────────────────────────────────────── -->
            <div class="jobs-filters" :class="{ 'jobs-filters--open': showFilters }">
                <!-- Search -->
                <input v-model="filterSearch"
                       class="filter-input"
                       :placeholder="ar ? 'ابحث عن مسمى أو شركة...' : 'Search title or company...'"
                       @keydown.enter="applyFilters" />

                <!-- Hub -->
                <select v-model="filterHub" class="filter-select">
                    <option value="">{{ ar ? 'جميع المجالات' : 'All Hubs' }}</option>
                    <option v-for="hub in allHubs" :key="hub.id" :value="hub.id">
                        {{ hubName(hub) }}
                    </option>
                </select>

                <!-- Job type -->
                <select v-model="filterType" class="filter-select">
                    <option value="">{{ ar ? 'جميع الأنواع' : 'All Types' }}</option>
                    <option v-for="jt in jobTypes" :key="jt.value" :value="jt.value">
                        {{ ar ? jt.ar : jt.en }}
                    </option>
                </select>

                <button class="filter-apply-btn" @click="applyFilters">
                    {{ ar ? 'تطبيق' : 'Apply' }}
                </button>

                <button v-if="hasActiveFilters" class="filter-clear-btn" @click="clearFilters">
                    {{ ar ? 'إلغاء' : 'Clear' }}
                </button>

                <!-- Mobile filter toggle — inside filters bar on mobile -->
                <button class="jobs-filter-toggle desktop-hide"
                        @click="showFilters = !showFilters">
                    <i class="ti ti-adjustments-horizontal"></i>
                    <span v-if="hasActiveFilters" class="filter-dot"></span>
                </button>
            </div>

            <!-- Mobile filter toggle — sits outside filter bar, in count row -->
            <div class="jobs-count-row">
                <span class="jobs-count">
                    {{ listings.total }} {{ ar ? 'وظيفة' : 'listings' }}
                </span>
                <button class="jobs-filter-toggle desktop-hide"
                        @click="showFilters = !showFilters">
                    <i class="ti ti-adjustments-horizontal"></i>
                    <span v-if="hasActiveFilters" class="filter-dot"></span>
                </button>
            </div>

            <!-- ── Empty ─────────────────────────────────────────────── -->
            <div v-if="!listings.data.length" class="jobs-empty">
                <i class="ti ti-briefcase"></i>
                <p>{{ ar ? 'لا توجد وظائف مطابقة' : 'No listings match your filters' }}</p>
                <a :href="route('member.jobs.create')" class="empty-post-btn">
                    {{ ar ? 'أنشئ أول إعلان' : 'Post the first listing' }}
                </a>
            </div>

            <!-- ── Cards ────────────────────────────────────────────── -->
            <div v-else class="jobs-grid">
                <a v-for="listing in listings.data"
                   :key="listing.id"
                   :href="route('member.jobs.show', listing.id)"
                   class="job-card">

                    <!-- Hub color stripe -->
                    <div class="job-card__stripe"
                         :style="{ background: listing.hub?.color ?? 'var(--color-primary)' }">
                    </div>

                    <!-- Card body -->
                    <div class="job-card__body">

                        <!-- Title + type badge -->
                        <div class="job-card__top">
                            <span class="job-card__title">{{ listing.job_title }}</span>
                            <span class="job-type-badge">{{ jobTypeLabel(listing.job_type) }}</span>
                        </div>

                        <!-- Company + location -->
                        <div class="job-card__company">
                            <i class="ti ti-building"></i> {{ listing.company_name }}
                            <span v-if="listing.location_city" class="job-card__sep">·</span>
                            <span v-if="listing.location_city">
                                <i class="ti ti-map-pin"></i> {{ listing.location_city }}
                            </span>
                        </div>

                        <!-- Hub + meta -->
                        <div class="job-card__meta">
                            <span v-if="listing.hub"
                                  class="job-hub-badge"
                                  :style="{ color: listing.hub.color, borderColor: listing.hub.color + '40' }">
                                {{ hubName(listing.hub) }}
                            </span>
                            <span v-if="listing.min_experience_years > 0">
                                {{ listing.min_experience_years }}+ {{ ar ? 'سنة خبرة' : 'yrs exp' }}
                            </span>
                            <span v-if="listing.salary_range">{{ listing.salary_range }}</span>
                        </div>

                        <!-- Skills -->
                        <div v-if="listing.required_skills?.length" class="job-card__skills">
                            <span v-for="s in listing.required_skills.slice(0,4)" :key="s" class="job-skill">{{ s }}</span>
                            <span v-if="listing.required_skills.length > 4" class="job-skill job-skill--more">
                                +{{ listing.required_skills.length - 4 }}
                            </span>
                        </div>

                        <!-- Footer -->
                        <div class="job-card__footer">
                            <span v-if="listing.my_status"
                                  class="my-status-badge"
                                  :class="statusBadgeClass(listing.my_status)">
                                {{ myStatusLabel(listing.my_status) }}
                            </span>
                            <span v-else-if="listing.is_mine" class="mine-badge">
                                <i class="ti ti-pencil"></i> {{ ar ? 'إعلانك' : 'Your listing' }}
                            </span>

                            <span class="job-card__time">{{ listing.created_at }}</span>
                        </div>

                    </div>
                </a>
            </div>

            <!-- ── Pagination ────────────────────────────────────────── -->
            <div v-if="listings.last_page > 1" class="jobs-pagination">
                <a v-for="link in listings.links"
                   :key="link.label"
                   :href="link.url"
                   class="page-btn"
                   :class="{ 'page-btn--active': link.active, 'page-btn--disabled': !link.url }"
                   v-html="link.label" />
            </div>

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

<style scoped>
.jobs-page { padding: 16px 16px 100px; }

/* ══════════════════════════════════════════════════════════════
   ENTRY CARDS — matches Help & Earn layout exactly
══════════════════════════════════════════════════════════════ */
.jobs-entry-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 12px;
}

.jobs-entry-card {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    padding: 20px 18px 18px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    box-shadow: var(--shadow-card);
    transition: box-shadow var(--transition-fast);
}

.jobs-entry-card:hover {
    box-shadow: var(--shadow-card-hover);
}

.jobs-entry-icon {
    width: 44px;
    height: 44px;
    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;
}

.jobs-entry-text {
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex: 1;
}

.jobs-entry-text strong {
    font-size: 15px;
    font-weight: 700;
    color: var(--color-text-primary);
    line-height: 1.3;
}

.jobs-entry-text span {
    font-size: 12px;
    color: var(--color-text-muted);
    line-height: 1.5;
}

.jobs-entry-secondary-btn {
    display: block;
    text-align: center;
    padding: 8px 12px;
    border-radius: var(--radius-md);
    font-size: 12px;
    font-weight: 600;
    text-decoration: none;
    background: var(--color-bg);
    border: 1px solid var(--color-border);
    color: var(--color-text-secondary);
    transition: all var(--transition-fast);
}

.jobs-entry-secondary-btn:hover {
    border-color: var(--color-primary);
    color: var(--color-primary);
}

.jobs-entry-cta-btn {
    display: block;
    text-align: center;
    padding: 10px 12px;
    border-radius: var(--radius-md);
    font-size: 13px;
    font-weight: 600;
    text-decoration: none;
    background: var(--color-primary);
    color: #fff;
    transition: background var(--transition-fast);
}

.jobs-entry-cta-btn:hover {
    background: var(--color-primary-light);
}

/* ══════════════════════════════════════════════════════════════
   DISCLAIMER — matches Help & Earn disclaimer strip
══════════════════════════════════════════════════════════════ */
.jobs-disclaimer {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    background: rgba(29, 158, 117, 0.06);
    border: 1px solid rgba(29, 158, 117, 0.18);
    border-radius: var(--radius-md);
    padding: 10px 14px;
    font-size: 11.5px;
    color: var(--color-text-secondary);
    line-height: 1.55;
    margin-bottom: 16px;
}

.jobs-disclaimer svg {
    color: var(--color-primary);
}

/* ══════════════════════════════════════════════════════════════
   TABS — matches Help & Earn Freelancers / Open Briefs tabs
══════════════════════════════════════════════════════════════ */
.jobs-tabs {
    display: flex;
    gap: 0;
    border-bottom: 2px solid var(--color-border);
    margin-bottom: 16px;
}

.jobs-tab {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 10px 16px;
    font-size: 13px;
    font-weight: 600;
    color: var(--color-text-muted);
    background: none;
    border: none;
    border-bottom: 2px solid transparent;
    margin-bottom: -2px;
    cursor: pointer;
    text-decoration: none;
    transition: color var(--transition-fast), border-color var(--transition-fast);
}

.jobs-tab:hover {
    color: var(--color-text-primary);
}

.jobs-tab--active {
    color: var(--color-primary);
    border-bottom-color: var(--color-primary);
}

.jobs-tab-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 20px;
    height: 18px;
    padding: 0 5px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 700;
    background: rgba(29, 158, 117, 0.12);
    color: var(--color-primary);
}

/* ══════════════════════════════════════════════════════════════
   FILTERS
══════════════════════════════════════════════════════════════ */
.jobs-filters {
    display: none;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    padding: 12px;
}

.jobs-filters--open { display: flex; }

.filter-input, .filter-select {
    background: var(--color-bg);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm);
    padding: 7px 10px;
    font-size: 12px;
    color: var(--color-text-secondary);
    outline: none;
    flex: 1;
    min-width: 140px;
    font-family: inherit;
}

.filter-apply-btn {
    background: var(--color-primary);
    color: #fff;
    border: none;
    border-radius: var(--radius-sm);
    padding: 7px 14px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
}

.filter-clear-btn {
    background: none;
    border: 1px solid var(--color-border);
    border-radius: var(--radius-sm);
    padding: 7px 14px;
    font-size: 12px;
    color: var(--color-text-muted);
    cursor: pointer;
}

/* ── Count row ──────────────────────────────────────────────────── */
.jobs-count-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
}

.jobs-count { font-size: 12px; color: var(--color-text-muted); }

/* ── Filter toggle (mobile) ─────────────────────────────────────── */
.jobs-filter-toggle {
    padding: 7px 10px;
    border-radius: var(--radius-md);
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    color: var(--color-text-secondary);
    cursor: pointer;
    position: relative;
}

.filter-dot {
    width: 7px; height: 7px;
    background: var(--color-primary);
    border-radius: 50%;
    position: absolute;
    top: 4px; inset-inline-end: 4px;
}

/* ══════════════════════════════════════════════════════════════
   EMPTY STATE
══════════════════════════════════════════════════════════════ */
.jobs-empty {
    text-align: center;
    padding: 48px 16px;
    color: var(--color-text-muted);
}

.jobs-empty i { font-size: 36px; display: block; margin-bottom: 10px; }
.jobs-empty p { margin-bottom: 14px; font-size: 13px; }

.empty-post-btn {
    display: inline-block;
    background: var(--color-primary);
    color: #fff;
    border-radius: var(--radius-md);
    padding: 9px 20px;
    font-size: 12px;
    font-weight: 600;
    text-decoration: none;
}

/* ══════════════════════════════════════════════════════════════
   GRID
══════════════════════════════════════════════════════════════ */
.jobs-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
    margin-bottom: 24px;
}

/* ══════════════════════════════════════════════════════════════
   JOB CARD — unchanged
══════════════════════════════════════════════════════════════ */
.job-card {
    display: flex;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-card);
    overflow: hidden;
    text-decoration: none;
    transition: box-shadow var(--transition-fast);
}

.job-card:hover { box-shadow: var(--shadow-card-hover); }

.job-card__stripe {
    width: 4px;
    flex-shrink: 0;
}

.job-card__body {
    padding: 14px 16px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    flex: 1;
    min-width: 0;
}

.job-card__top {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 8px;
}

.job-card__title {
    font-size: 15px;
    font-weight: 700;
    color: var(--color-text-primary);
    line-height: 1.3;
}

.job-type-badge {
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
    background: rgba(29, 158, 117, 0.1);
    color: var(--color-primary);
    white-space: nowrap;
    flex-shrink: 0;
}

.job-card__company {
    font-size: 12px;
    color: var(--color-text-secondary);
    display: flex;
    align-items: center;
    gap: 4px;
    flex-wrap: wrap;
}

.job-card__sep { opacity: 0.4; }

.job-card__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    align-items: center;
    font-size: 11px;
    color: var(--color-text-muted);
}

.job-hub-badge {
    padding: 2px 8px;
    border-radius: 20px;
    border: 1px solid;
    font-size: 10px;
    font-weight: 600;
}

.job-card__skills {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
}

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

.job-skill--more { background: transparent; border-color: transparent; color: var(--color-text-muted); }

.job-card__footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    margin-top: 2px;
}

.job-card__time {
    font-size: 11px;
    color: var(--color-text-muted);
    margin-inline-start: auto;
}

.my-status-badge {
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
}

.status--pending  { background: rgba(247,181,0,0.12);  color: #b7860a; }
.status--accepted { background: rgba(29,158,117,0.12); color: var(--color-primary); }
.status--connected{ background: rgba(29,158,117,0.2);  color: var(--color-primary); }
.status--declined { background: rgba(220,53,69,0.1);   color: #dc3545; }

.mine-badge {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: var(--color-text-muted);
}

/* ══════════════════════════════════════════════════════════════
   PAGINATION
══════════════════════════════════════════════════════════════ */
.jobs-pagination { display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; }

.page-btn {
    padding: 6px 10px;
    border-radius: var(--radius-sm);
    font-size: 12px;
    border: 1px solid var(--color-border);
    background: var(--color-surface);
    color: var(--color-text-secondary);
    text-decoration: none;
}

.page-btn--active  { background: var(--color-primary); color: #fff; border-color: var(--color-primary); }
.page-btn--disabled { opacity: 0.4; pointer-events: none; }

/* ══════════════════════════════════════════════════════════════
   DESKTOP
══════════════════════════════════════════════════════════════ */
@media (min-width: 768px) {
    .jobs-page   { padding: 24px 32px 60px; }
    .jobs-filters { display: flex; }
    .desktop-hide { display: none; }
    .jobs-grid   { grid-template-columns: 1fr 1fr; }
}
</style>