<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/JobClub/Jobs/MyListings.vue
//  Location: resources/js/Pages/Member/JobClub/Jobs/MyListings.vue
//
//  The poster's own listings — close, reopen, view applicant count.
//  No pagination (get all), sorted newest first from service.
// ══════════════════════════════════════════════════════════════════

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

const props = defineProps({
    myListings: { type: Array,  required: true },
    allHubs:    { type: Array,  required: true },
});

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

// Keep list reactive without page reload
const listings = ref(props.myListings.map(l => ({ ...l })));

// ── Summary stats ─────────────────────────────────────────────────
const totalListings   = computed(() => listings.value.length);
const activeListings  = computed(() => listings.value.filter(l => l.status === 'active').length);
const totalApplicants = computed(() => listings.value.reduce((sum, l) => sum + (l.applicant_count ?? 0), 0));

// ── Close / Reopen ────────────────────────────────────────────────
const togglingId = ref(null);

async function toggleClose(listing) {
    if (togglingId.value) return;
    togglingId.value = listing.id;

    const isActive = listing.status === 'active';
    const url      = isActive
        ? route('member.jobs.close',  listing.id)
        : route('member.jobs.reopen', listing.id);

    try {
        const res  = await fetch(url, {
            method: 'PATCH',
            headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content },
        });
        const data = await res.json();
        const item = listings.value.find(l => l.id === listing.id);
        if (item) item.status = data.status;
    } finally {
        togglingId.value = null;
    }
}

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

function jobTypeLabel(v) {
    return ar.value ? (jobTypes[v]?.ar ?? v) : (jobTypes[v]?.en ?? v);
}

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

<template>
    <Head :title="ar ? 'إعلاناتي' : 'My Listings'" />

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

            <!-- ══════════════════════════════════════════════════
                 BACK LINK
            ═══════════════════════════════════════════════════════ -->
            <a :href="route('member.jobs.index')" class="back-link">
                <svg 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 12H5M12 5l-7 7 7 7"/>
                </svg>
                {{ ar ? 'إعلانات الوظائف' : 'Job Listings' }}
            </a>

            <!-- ══════════════════════════════════════════════════
                 HERO BANNER
            ═══════════════════════════════════════════════════════ -->
            <div class="ml-hero">
                <!-- Left: icon + text -->
                <div class="ml-hero__left">
                    <div class="ml-hero__icon">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" 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>
                        <h1 class="ml-hero__title">
                            {{ ar ? 'إعلاناتي الوظيفية' : 'My Job Listings' }}
                        </h1>
                        <p class="ml-hero__sub">
                            {{ ar
                                ? 'جميع الوظائف التي نشرتها — أغلق أو أعد فتح في أي وقت'
                                : 'All listings you\'ve posted — close or reopen anytime' }}
                        </p>
                    </div>
                </div>

                <!-- Right: Post button -->
                <a :href="route('member.jobs.create')" class="ml-post-btn">
                    <svg 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">
                        <line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>
                    </svg>
                    {{ ar ? 'نشر وظيفة جديدة' : 'Post New Listing' }}
                </a>
            </div>

            <!-- ══════════════════════════════════════════════════
                 STATS STRIP — only shown when there are listings
            ═══════════════════════════════════════════════════════ -->
            <div v-if="listings.length" class="ml-stats">
                <div class="ml-stat-card">
                    <span class="ml-stat-card__value">{{ totalListings }}</span>
                    <span class="ml-stat-card__label">{{ ar ? 'إجمالي الإعلانات' : 'Total Listings' }}</span>
                </div>
                <div class="ml-stat-divider"></div>
                <div class="ml-stat-card">
                    <span class="ml-stat-card__value ml-stat-card__value--green">{{ activeListings }}</span>
                    <span class="ml-stat-card__label">{{ ar ? 'نشط الآن' : 'Active Now' }}</span>
                </div>
                <div class="ml-stat-divider"></div>
                <div class="ml-stat-card">
                    <span class="ml-stat-card__value">{{ totalApplicants }}</span>
                    <span class="ml-stat-card__label">{{ ar ? 'إجمالي المتقدمين' : 'Total Applicants' }}</span>
                </div>
            </div>

            <!-- ══════════════════════════════════════════════════
                 EMPTY STATE
            ═══════════════════════════════════════════════════════ -->
            <div v-if="!listings.length" class="ml-empty">
                <div class="ml-empty__icon">
                    <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" 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>
                <p class="ml-empty__title">{{ ar ? 'لم تنشر أي وظائف بعد' : 'No listings posted yet' }}</p>
                <p class="ml-empty__sub">{{ ar ? 'انشر أول وظيفة وابدأ في استقطاب المواهب' : 'Post your first role and start attracting talent' }}</p>
                <a :href="route('member.jobs.create')" class="ml-empty__cta">
                    {{ ar ? 'انشر أول وظيفة' : 'Post your first listing' }}
                </a>
            </div>

            <!-- ══════════════════════════════════════════════════
                 LISTINGS GRID
            ═══════════════════════════════════════════════════════ -->
            <div v-else class="ml-grid">
                <div v-for="listing in listings"
                     :key="listing.id"
                     class="ml-card"
                     :class="{ 'ml-card--closed': listing.status !== 'active' }">

                    <!-- Hub color stripe -->
                    <div class="ml-card__stripe"
                         :style="{ background: hubColor(listing) }">
                    </div>

                    <div class="ml-card__body">

                        <!-- ── Top row: title + status ──────────── -->
                        <div class="ml-card__head">
                            <a :href="route('member.jobs.show', listing.id)"
                               class="ml-card__title">
                                {{ listing.job_title }}
                            </a>
                            <span class="ml-status-pill"
                                  :class="listing.status === 'active'
                                      ? 'ml-status-pill--active'
                                      : 'ml-status-pill--closed'">
                                <span class="ml-status-pill__dot"></span>
                                {{ listing.status === 'active'
                                    ? (ar ? 'نشط' : 'Active')
                                    : (ar ? 'مغلق' : 'Closed') }}
                            </span>
                        </div>

                        <!-- ── Company · type · city ────────────── -->
                        <div class="ml-card__company">
                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" 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>
                            {{ listing.company_name }}
                            <span class="ml-sep">·</span>
                            {{ jobTypeLabel(listing.job_type) }}
                            <template v-if="listing.location_city">
                                <span class="ml-sep">·</span>
                                <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
                                </svg>
                                {{ listing.location_city }}
                            </template>
                        </div>

                        <!-- ── Hub badge + date ──────────────────── -->
                        <div class="ml-card__meta">
                            <span v-if="listing.hub"
                                  class="ml-hub-badge"
                                  :style="{ color: listing.hub.color, borderColor: listing.hub.color + '40', background: listing.hub.color + '12' }">
                                {{ ar ? listing.hub.name_ar : listing.hub.name_en }}
                            </span>
                            <span class="ml-card__date">{{ listing.created_at }}</span>
                        </div>

                        <!-- ── Divider ───────────────────────────── -->
                        <div class="ml-card__divider"></div>

                        <!-- ── Footer: applicants + actions ─────── -->
                        <div class="ml-card__footer">
                            <!-- Applicant count -->
                            <div class="ml-applicant-count">
                                <span class="ml-applicant-count__num">{{ listing.applicant_count ?? 0 }}</span>
                                <span class="ml-applicant-count__label">
                                    {{ ar ? 'متقدم' : listing.applicant_count === 1 ? 'Applicant' : 'Applicants' }}
                                </span>
                            </div>

                            <!-- Actions -->
                            <div class="ml-card__actions">
                                <a :href="route('member.jobs.show', listing.id)"
                                   class="ml-btn ml-btn--view">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" 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>
                                    {{ ar ? 'عرض التقديمات' : 'View Applicants' }}
                                </a>

                                <button class="ml-btn"
                                        :class="listing.status === 'active'
                                            ? 'ml-btn--close'
                                            : 'ml-btn--reopen'"
                                        :disabled="togglingId === listing.id"
                                        @click="toggleClose(listing)">
                                    <!-- Spinner when toggling -->
                                    <svg v-if="togglingId === listing.id" xmlns="http://www.w3.org/2000/svg" width="13" height="13" 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>
                                    <template v-else>
                                        <svg v-if="listing.status === 'active'" xmlns="http://www.w3.org/2000/svg" width="13" height="13" 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>
                                        <svg v-else xmlns="http://www.w3.org/2000/svg" width="13" height="13" 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 9.9-1"/>
                                        </svg>
                                    </template>
                                    {{ listing.status === 'active'
                                        ? (ar ? 'إغلاق' : 'Close')
                                        : (ar ? 'إعادة فتح' : 'Reopen') }}
                                </button>
                            </div>
                        </div>

                    </div><!-- /ml-card__body -->
                </div>
            </div><!-- /ml-grid -->

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

<style scoped>
.ml-page {
    padding: 16px 16px 100px;
    max-width: 1250px;
    margin: 0 auto;
}

/* ── Back link ──────────────────────────────────────────────────── */
.back-link {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    font-weight: 500;
    color: var(--color-text-muted);
    text-decoration: none;
    margin-bottom: 20px;
    transition: color var(--transition-fast);
}

.back-link:hover { color: var(--color-primary); }
[dir="rtl"] .back-link svg { transform: scaleX(-1); }

/* ══════════════════════════════════════════════════════════════
   HERO BANNER
══════════════════════════════════════════════════════════════ */
.ml-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;
    margin-bottom: 16px;
    box-shadow: var(--shadow-card);
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    flex-wrap: wrap;
}

.ml-hero__left {
    display: flex;
    align-items: center;
    gap: 14px;
}

.ml-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;
}

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

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

.ml-post-btn {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    background: var(--color-primary);
    color: #fff;
    border-radius: var(--radius-md);
    padding: 10px 18px;
    font-size: 13px;
    font-weight: 600;
    text-decoration: none;
    transition: background var(--transition-fast), box-shadow var(--transition-fast);
    white-space: nowrap;
    flex-shrink: 0;
}

.ml-post-btn:hover {
    background: var(--color-primary-light);
    box-shadow: 0 4px 14px rgba(29, 158, 117, 0.3);
}

/* ══════════════════════════════════════════════════════════════
   STATS STRIP
══════════════════════════════════════════════════════════════ */
.ml-stats {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    padding: 16px 24px;
    margin-bottom: 20px;
    box-shadow: var(--shadow-card);
    display: flex;
    align-items: center;
    gap: 0;
}

.ml-stat-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 3px;
    text-align: center;
}

.ml-stat-card__value {
    font-size: 26px;
    font-weight: 700;
    color: var(--color-text-primary);
    line-height: 1;
}

.ml-stat-card__value--green { color: var(--color-primary); }

.ml-stat-card__label {
    font-size: 11px;
    color: var(--color-text-muted);
    font-weight: 500;
}

.ml-stat-divider {
    width: 1px;
    height: 36px;
    background: var(--color-border);
    flex-shrink: 0;
}

/* ══════════════════════════════════════════════════════════════
   EMPTY STATE
══════════════════════════════════════════════════════════════ */
.ml-empty {
    text-align: center;
    padding: 56px 16px;
    color: var(--color-text-muted);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
}

.ml-empty__icon {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: rgba(29, 158, 117, 0.08);
    color: var(--color-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 4px;
}

.ml-empty__title {
    font-size: 15px;
    font-weight: 600;
    color: var(--color-text-primary);
    margin: 0;
}

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

.ml-empty__cta {
    display: inline-block;
    background: var(--color-primary);
    color: #fff;
    border-radius: var(--radius-md);
    padding: 10px 22px;
    font-size: 13px;
    font-weight: 600;
    text-decoration: none;
    margin-top: 6px;
    transition: background var(--transition-fast);
}

.ml-empty__cta:hover { background: var(--color-primary-light); }

/* ══════════════════════════════════════════════════════════════
   GRID
══════════════════════════════════════════════════════════════ */
.ml-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
}

/* ══════════════════════════════════════════════════════════════
   CARD
══════════════════════════════════════════════════════════════ */
.ml-card {
    display: flex;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    overflow: hidden;
    box-shadow: var(--shadow-card);
    transition: box-shadow var(--transition-fast), opacity var(--transition-fast);
}

.ml-card:hover { box-shadow: var(--shadow-card-hover); }
.ml-card--closed { opacity: 0.7; }

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

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

/* ── Head: title + status ───────────────────────────────────────── */
.ml-card__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.ml-card__title {
    font-size: 15px;
    font-weight: 700;
    color: var(--color-text-primary);
    text-decoration: none;
    transition: color var(--transition-fast);
    line-height: 1.3;
}

.ml-card__title:hover { color: var(--color-primary); }

/* Status pill with dot */
.ml-status-pill {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 3px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    white-space: nowrap;
    flex-shrink: 0;
}

.ml-status-pill--active {
    background: rgba(29, 158, 117, 0.12);
    color: var(--color-primary);
}

.ml-status-pill--active .ml-status-pill__dot {
    width: 6px; height: 6px;
    border-radius: 50%;
    background: var(--color-primary);
}

.ml-status-pill--closed {
    background: var(--color-bg);
    color: var(--color-text-muted);
    border: 1px solid var(--color-border);
}

.ml-status-pill--closed .ml-status-pill__dot {
    width: 6px; height: 6px;
    border-radius: 50%;
    background: var(--color-text-muted);
    opacity: 0.5;
}

/* ── Company row ────────────────────────────────────────────────── */
.ml-card__company {
    font-size: 12px;
    color: var(--color-text-secondary);
    display: flex;
    align-items: center;
    gap: 4px;
    flex-wrap: wrap;
}

.ml-sep { opacity: 0.35; margin: 0 1px; }

/* ── Meta: hub badge + date ─────────────────────────────────────── */
.ml-card__meta {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 11px;
}

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

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

/* ── Divider ────────────────────────────────────────────────────── */
.ml-card__divider {
    height: 1px;
    background: var(--color-border);
    margin: 4px 0;
}

/* ── Footer: applicants + actions ───────────────────────────────── */
.ml-card__footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
}

.ml-applicant-count {
    display: flex;
    align-items: baseline;
    gap: 5px;
}

.ml-applicant-count__num {
    font-size: 24px;
    font-weight: 700;
    color: var(--color-text-primary);
    line-height: 1;
}

.ml-applicant-count__label {
    font-size: 11px;
    color: var(--color-text-muted);
}

.ml-card__actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

/* ── Buttons ────────────────────────────────────────────────────── */
.ml-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 7px 14px;
    border-radius: var(--radius-md);
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    text-decoration: none;
    border: 1.5px solid;
    transition: all var(--transition-fast);
    background: transparent;
    font-family: inherit;
}

.ml-btn:disabled { opacity: 0.5; cursor: not-allowed; }

.ml-btn--view {
    border-color: var(--color-border);
    color: var(--color-text-secondary);
}

.ml-btn--view:hover {
    border-color: var(--color-primary);
    color: var(--color-primary);
}

.ml-btn--close {
    border-color: #dc3545;
    color: #dc3545;
}

.ml-btn--close:hover:not(:disabled) {
    background: #dc3545;
    color: #fff;
}

.ml-btn--reopen {
    border-color: var(--color-primary);
    color: var(--color-primary);
}

.ml-btn--reopen:hover:not(:disabled) {
    background: var(--color-primary);
    color: #fff;
}

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

/* ══════════════════════════════════════════════════════════════
   DESKTOP
══════════════════════════════════════════════════════════════ */
@media (min-width: 768px) {
    .ml-page  { padding: 24px 32px 60px; }
    .ml-grid  { grid-template-columns: 1fr 1fr; }
}
</style>