<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Member/JobClub/Notifications/Index.vue
//  Location: resources/js/Pages/Member/JobClub/Notifications/Index.vue
//
//  The professional's inbox — incoming job interest notifications.
//  Accept / Decline / Consent all happen on this page.
//  No page reload — all actions are PATCH via fetch.
// ══════════════════════════════════════════════════════════════════

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

const props = defineProps({
    notifications: { type: Object, required: true },
});

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

// ── Local state ───────────────────────────────────────────────────
// Keep notifications reactive without a page reload
const items = ref(props.notifications.data.map(n => ({ ...n })));

// ── Respond (accept / decline) ────────────────────────────────────
const responding = ref(null);

async function respond(notifId, response) {
    if (responding.value) return;
    responding.value = notifId;
    try {
        const res  = await fetch(route('member.jobs.respond', notifId), {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
            body: JSON.stringify({ response }),
        });
        const data = await res.json();
        const item = items.value.find(n => n.id === notifId);
        if (item) item.status = data.status;
    } finally {
        responding.value = null;
    }
}

// ── Consent ───────────────────────────────────────────────────────
// Shows a confirmation gate before calling the API
const consentingId = ref(null);

function openConsent(notifId) {
    consentingId.value = notifId;
}

function cancelConsent() {
    consentingId.value = null;
}

const confirmingConsent = ref(false);

async function confirmConsent(notifId) {
    if (confirmingConsent.value) return;
    confirmingConsent.value = true;
    try {
        const res  = await fetch(route('member.jobs.consent', notifId), {
            method: 'PATCH',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            },
        });
        const data = await res.json();
        const item = items.value.find(n => n.id === notifId);
        if (item) {
            item.status                 = data.status;
            item.professional_consented = data.professional_consented;
            item.employer_consented     = data.employer_consented;
            item.connected_at           = data.connected_at;
        }
        consentingId.value = null;
    } finally {
        confirmingConsent.value = false;
    }
}

// ── Helpers ───────────────────────────────────────────────────────
function statusLabel(s) {
    const map = {
        pending:   { en: 'Waiting',         ar: 'في الانتظار' },
        accepted:  { en: 'Accepted',        ar: 'مقبول' },
        connected: { en: 'Connected',       ar: 'متصل' },
        declined:  { en: 'Declined',        ar: 'مرفوض' },
    };
    return ar.value ? (map[s]?.ar ?? s) : (map[s]?.en ?? s);
}

function jobTypeLabel(v) {
    const map = {
        full_time:  { en: 'Full Time',  ar: 'دوام كامل' },
        part_time:  { en: 'Part Time',  ar: 'دوام جزئي' },
        contract:   { en: 'Contract',   ar: 'عقد' },
        internship: { en: 'Internship', ar: 'تدريب' },
    };
    return ar.value ? (map[v]?.ar ?? v) : (map[v]?.en ?? v);
}
</script>

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

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

            <!-- ── Header ───────────────────────────────────────── -->
            <div class="notif-header">
                <h1 class="notif-title">{{ ar ? 'إشعارات الوظائف' : 'Job Notifications' }}</h1>
                <p class="notif-sub">
                    {{ ar
                        ? 'هنا تجد فرص العمل التي أرسلها إليك أعضاء المجتمع'
                        : 'Job opportunities sent to you by community members' }}
                </p>
            </div>

            <!-- ── Empty ─────────────────────────────────────────── -->
            <div v-if="!items.length" class="notif-empty">
                <i class="ti ti-inbox"></i>
                <p>{{ ar ? 'لا توجد إشعارات بعد' : 'No notifications yet' }}</p>
                <p class="notif-empty-sub">
                    {{ ar
                        ? 'عندما يرسل أحد فرصة وظيفية لملفك ستجدها هنا'
                        : 'When someone sends a job opportunity to your CV profile, it will appear here' }}
                </p>
            </div>

            <!-- ── Notification cards ───────────────────────────── -->
            <div v-else class="notif-list">
                <div v-for="notif in items"
                     :key="notif.id"
                     class="notif-card"
                     :class="`notif-card--${notif.status}`">

                    <!-- Status banner -->
                    <div class="notif-card__status-bar">
                        <span class="notif-status-badge" :class="`status--${notif.status}`">
                            {{ statusLabel(notif.status) }}
                        </span>
                        <span class="notif-time">{{ notif.created_at }}</span>
                    </div>

                    <!-- Job info -->
                    <div v-if="notif.job" class="notif-job-info">
                        <div class="notif-job-title">{{ notif.job.job_title }}</div>
                        <div class="notif-job-company">
                            <i class="ti ti-building"></i> {{ notif.job.company_name }}
                        </div>
                        <div class="notif-job-meta">
                            <span v-if="notif.job.hub"
                                  class="notif-hub-badge"
                                  :style="{ color: notif.job.hub.color, borderColor: notif.job.hub.color + '40' }">
                                {{ ar ? notif.job.hub.name_ar : notif.job.hub.name_en }}
                            </span>
                            <span>{{ jobTypeLabel(notif.job.job_type) }}</span>
                        </div>
                    </div>

                    <!-- Message from poster -->
                    <div v-if="notif.message" class="notif-message">
                        <i class="ti ti-quote"></i>
                        <em>{{ notif.message }}</em>
                    </div>

                    <!-- ── Actions by status ─────────────────────── -->

                    <!-- PENDING — accept or decline -->
                    <div v-if="notif.status === 'pending'" class="notif-actions">
                        <p class="notif-action-sub">
                            {{ ar
                                ? 'هل أنت مهتم بهذه الفرصة؟'
                                : 'Are you interested in this opportunity?' }}
                        </p>
                        <div class="notif-action-btns">
                            <button class="notif-btn notif-btn--accept"
                                    :disabled="responding === notif.id"
                                    @click="respond(notif.id, 'accepted')">
                                <i class="ti ti-check"></i>
                                {{ ar ? 'نعم، أنا مهتم' : 'Yes, I\'m Interested' }}
                            </button>
                            <button class="notif-btn notif-btn--decline"
                                    :disabled="responding === notif.id"
                                    @click="respond(notif.id, 'declined')">
                                <i class="ti ti-x"></i>
                                {{ ar ? 'لا، شكراً' : 'No, Thanks' }}
                            </button>
                        </div>
                    </div>

                    <!-- ACCEPTED — consent gate -->
                    <div v-else-if="notif.status === 'accepted' && !notif.professional_consented"
                         class="notif-actions">

                        <!-- Not yet in consent flow -->
                        <div v-if="consentingId !== notif.id">
                            <p class="notif-action-sub">
                                {{ ar
                                    ? 'للمضي قدماً يجب مشاركة بياناتك مع صاحب الإعلان'
                                    : 'To proceed, your contact details will be shared with the poster' }}
                            </p>
                            <button class="notif-btn notif-btn--consent"
                                    @click="openConsent(notif.id)">
                                <i class="ti ti-shield-check"></i>
                                {{ ar ? 'مشاركة بياناتي والتواصل' : 'Share My Details & Connect' }}
                            </button>
                        </div>

                        <!-- Consent confirmation gate -->
                        <div v-else class="consent-gate">
                            <div class="consent-gate__icon">
                                <i class="ti ti-alert-triangle"></i>
                            </div>
                            <div class="consent-gate__title">
                                {{ ar ? 'تأكيد مشاركة البيانات' : 'Confirm Contact Sharing' }}
                            </div>
                            <p class="consent-gate__body">
                                {{ ar
                                    ? 'سيتم مشاركة اسمك وبريدك الإلكتروني ورقم هاتفك مع صاحب الإعلان. هذا الإجراء لا يمكن التراجع عنه.'
                                    : 'Your name, email, and phone number will be shared with the job poster. This action cannot be undone.' }}
                            </p>
                            <div class="consent-gate__btns">
                                <button class="notif-btn notif-btn--confirm"
                                        :disabled="confirmingConsent"
                                        @click="confirmConsent(notif.id)">
                                    {{ ar ? 'نعم، أوافق' : 'Yes, I Confirm' }}
                                </button>
                                <button class="notif-btn notif-btn--cancel"
                                        @click="cancelConsent">
                                    {{ ar ? 'إلغاء' : 'Cancel' }}
                                </button>
                            </div>
                        </div>

                    </div>

                    <!-- ACCEPTED — waiting for employer -->
                    <div v-else-if="notif.status === 'accepted' && notif.professional_consented && !notif.connected_at"
                         class="notif-waiting">
                        <i class="ti ti-clock"></i>
                        {{ ar ? 'في انتظار تأكيد صاحب الإعلان' : 'Waiting for the poster to confirm' }}
                    </div>

                    <!-- CONNECTED — show contact details -->
                    <div v-else-if="notif.status === 'connected'" class="notif-connected">
                        <div class="notif-connected__title">
                            <i class="ti ti-circle-check"></i>
                            {{ ar ? 'تم التواصل!' : 'Connected!' }}
                        </div>
                        <div v-if="notif.contact" class="notif-contact-details">
                            <div class="contact-detail">
                                <i class="ti ti-user"></i> {{ notif.contact.name }}
                            </div>
                            <div class="contact-detail">
                                <i class="ti ti-mail"></i>
                                <a :href="`mailto:${notif.contact.email}`">{{ notif.contact.email }}</a>
                            </div>
                            <div v-if="notif.contact.phone" class="contact-detail">
                                <i class="ti ti-phone"></i>
                                <a :href="`tel:${notif.contact.phone}`">{{ notif.contact.phone }}</a>
                            </div>
                        </div>
                    </div>

                    <!-- DECLINED -->
                    <div v-else-if="notif.status === 'declined'" class="notif-declined">
                        <i class="ti ti-x"></i>
                        {{ ar ? 'قررت عدم المتابعة بهذه الفرصة' : 'You declined this opportunity' }}
                    </div>

                </div>
            </div>

            <!-- ── Pagination ────────────────────────────────────── -->
            <div v-if="notifications.last_page > 1" class="notif-pagination">
                <a v-for="link in notifications.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><!-- /notif-page -->
    </AppLayout>
</template>

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

/* ── Header ────────────────────────────────────────────────────── */
.notif-header  { margin-bottom: 20px; }
.notif-title   { font-size: 20px; font-weight: 700; color: var(--color-text-primary); margin-bottom: 4px; }
.notif-sub     { font-size: 12px; color: var(--color-text-muted); }

/* ── Empty ──────────────────────────────────────────────────────── */
.notif-empty {
    text-align: center;
    padding: 48px 16px;
    color: var(--color-text-muted);
}
.notif-empty i { font-size: 36px; display: block; margin-bottom: 10px; }
.notif-empty p { font-size: 14px; margin-bottom: 6px; }
.notif-empty-sub { font-size: 12px; }

/* ── List ───────────────────────────────────────────────────────── */
.notif-list { display: flex; flex-direction: column; gap: 14px; }

/* ── Card ───────────────────────────────────────────────────────── */
.notif-card {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    overflow: hidden;
    box-shadow: var(--shadow-card);
    display: flex;
    flex-direction: column;
    gap: 0;
}

.notif-card--connected { border-color: rgba(29,158,117,0.3); }
.notif-card--declined  { opacity: 0.7; }

/* ── Status bar ─────────────────────────────────────────────────── */
.notif-card__status-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 14px;
    background: var(--color-bg);
    border-bottom: 1px solid var(--color-border);
}

.notif-status-badge {
    padding: 2px 8px;
    border-radius: 20px;
    font-size: 11px;
    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; }

.notif-time { font-size: 11px; color: var(--color-text-muted); }

/* ── Job info ───────────────────────────────────────────────────── */
.notif-job-info { padding: 14px 14px 0; }

.notif-job-title {
    font-size: 16px;
    font-weight: 700;
    color: var(--color-text-primary);
    margin-bottom: 4px;
}

.notif-job-company {
    font-size: 13px;
    color: var(--color-text-secondary);
    display: flex;
    align-items: center;
    gap: 5px;
    margin-bottom: 6px;
}

.notif-job-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 11px;
    color: var(--color-text-muted);
}

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

/* ── Message ────────────────────────────────────────────────────── */
.notif-message {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    padding: 10px 14px 0;
    font-size: 13px;
    color: var(--color-text-secondary);
    font-style: italic;
}

/* ── Actions ────────────────────────────────────────────────────── */
.notif-actions { padding: 14px; }

.notif-action-sub {
    font-size: 13px;
    color: var(--color-text-secondary);
    margin-bottom: 12px;
}

.notif-action-btns {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.notif-btn {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 9px 16px;
    border-radius: var(--radius-md);
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    border: none;
    transition: all var(--transition-fast);
}

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

.notif-btn--accept  { background: var(--color-primary); color: #fff; }
.notif-btn--accept:hover:not(:disabled) { background: var(--color-primary-light); }

.notif-btn--decline { background: transparent; border: 1.5px solid #dc3545; color: #dc3545; }
.notif-btn--decline:hover:not(:disabled) { background: #dc3545; color: #fff; }

.notif-btn--consent { background: var(--color-primary); color: #fff; width: 100%; justify-content: center; }
.notif-btn--consent:hover { background: var(--color-primary-light); }

.notif-btn--confirm { background: var(--color-primary); color: #fff; flex: 1; justify-content: center; }
.notif-btn--cancel  { background: transparent; border: 1.5px solid var(--color-border); color: var(--color-text-secondary); flex: 1; justify-content: center; }

/* ── Consent gate ───────────────────────────────────────────────── */
.consent-gate {
    background: rgba(247,181,0,0.06);
    border: 1px solid rgba(247,181,0,0.3);
    border-radius: var(--radius-md);
    padding: 14px;
}

.consent-gate__icon { font-size: 22px; color: #b7860a; margin-bottom: 8px; }
.consent-gate__title { font-size: 14px; font-weight: 700; color: var(--color-text-primary); margin-bottom: 6px; }
.consent-gate__body { font-size: 13px; color: var(--color-text-secondary); line-height: 1.5; margin-bottom: 14px; }
.consent-gate__btns { display: flex; gap: 8px; }

/* ── Waiting ────────────────────────────────────────────────────── */
.notif-waiting {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 12px 14px;
    font-size: 13px;
    color: var(--color-text-muted);
    font-style: italic;
}

/* ── Connected ──────────────────────────────────────────────────── */
.notif-connected { padding: 14px; }

.notif-connected__title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 15px;
    font-weight: 700;
    color: var(--color-primary);
    margin-bottom: 12px;
}

.notif-contact-details { display: flex; flex-direction: column; gap: 6px; }

.contact-detail {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: var(--color-text-secondary);
}

.contact-detail a { color: var(--color-primary); text-decoration: none; }
.contact-detail a:hover { text-decoration: underline; }

/* ── Declined ───────────────────────────────────────────────────── */
.notif-declined {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 12px 14px;
    font-size: 13px;
    color: var(--color-text-muted);
}

/* ── Pagination ─────────────────────────────────────────────────── */
.notif-pagination { display: flex; gap: 4px; justify-content: center; flex-wrap: wrap; margin-top: 20px; }

.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) {
    .notif-page { padding: 24px 32px 60px; }
}
</style>
