<script setup>
// ══════════════════════════════════════════════════════════════════
//  InPractice — Admin/Users/Index.vue
//  Location: resources/js/Pages/Admin/Users/Index.vue
//
//  MOBILE  (<768px):
//    - Filter bar (search, status dropdown)
//    - Member cards — avatar, name, email, hubs, suspend toggle
//
//  DESKTOP (≥768px):
//    - Max-width 1250px container
//    - Filter row: search + hub + experience + status
//    - Full table: name, email, nickname, profession, level, hubs, joined, status, action
//
//  Toggle active:
//    - Fires PATCH /admin/users/{id}/toggle-active
//    - Returns JSON { is_active, message }
//    - Updates the local list in place — NO page reload
//
//  Rules:
//    - Zero DB calls in Vue — all data from UserService
//    - All CSS uses var(--color-*) tokens
//    - Experience levels match ExperienceLevel.php (8 levels)
// ══════════════════════════════════════════════════════════════════

import { ref, computed } from 'vue';
import { Head, Link, router } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';

// ── Props ─────────────────────────────────────────────────────────
const props = defineProps({
    users:   { type: Object, required: true }, // LengthAwarePaginator
    hubs:    { type: Array,  required: true },
    filters: { type: Object, default: () => ({}) },
});

// ── Local reactive copy of users so toggle updates in-place ───────
const localUsers = ref([...props.users.data]);

// ── Filter state ──────────────────────────────────────────────────
const search          = ref(props.filters.search           ?? '');
const selectedHub     = ref(props.filters.hub_id           ?? '');
const selectedLevel   = ref(props.filters.experience_level ?? '');
const selectedStatus  = ref(props.filters.status           ?? '');

// Debounce timer for search
let searchTimer = null;

function applyFilters() {
    const params = {};
    if (search.value)         params.search            = search.value;
    if (selectedHub.value)    params.hub_id             = selectedHub.value;
    if (selectedLevel.value)  params.experience_level   = selectedLevel.value;
    if (selectedStatus.value) params.status             = selectedStatus.value;

    router.get(route('admin.users.index'), params, {
        preserveState: true,
        replace: true,
    });
}

function onSearchInput() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(applyFilters, 400);
}

function clearFilters() {
    search.value         = '';
    selectedHub.value    = '';
    selectedLevel.value  = '';
    selectedStatus.value = '';
    applyFilters();
}

const hasActiveFilters = computed(() =>
    !!(search.value || selectedHub.value || selectedLevel.value || selectedStatus.value)
);

// ── Toggle active ─────────────────────────────────────────────────
const togglingId = ref(null); // track which row is in-flight

async function toggleActive(member) {
    if (togglingId.value) return; // debounce double-tap
    togglingId.value = member.id;

    try {
        const res = await fetch(route('admin.users.toggle-active', member.id), {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
            },
        });

        const json = await res.json();

        // Update the local copy — no page reload
        const idx = localUsers.value.findIndex(u => u.id === member.id);
        if (idx !== -1) {
            localUsers.value[idx] = { ...localUsers.value[idx], is_active: json.is_active };
        }
    } catch (e) {
        console.error('Toggle failed', e);
    } finally {
        togglingId.value = null;
    }
}

// ── Helpers — all 8 experience levels ────────────────────────────
function expLabel(level) {
    const map = {
        student:         'Student',
        fresh:           'Fresh Graduate',
        junior:          'Junior (1–3 yrs)',
        mid:             'Mid-Level (3–5 yrs)',
        senior:          'Senior (5–10 yrs)',
        ten_fifteen:     '10–15 Years',
        fifteen_twenty:  '15–20 Years',
        twenty_plus:     '20+ Years',
    };
    return map[level] ?? level;
}

function expColor(level) {
    const map = {
        student:         'rgba(139,92,246,0.10)',
        fresh:           'rgba(29,158,117,0.10)',
        junior:          'rgba(55,138,221,0.10)',
        mid:             'rgba(216,90,48,0.10)',
        senior:          'rgba(255,193,7,0.12)',
        ten_fifteen:     'rgba(255,193,7,0.12)',
        fifteen_twenty:  'rgba(255,193,7,0.15)',
        twenty_plus:     'rgba(255,193,7,0.18)',
    };
    return map[level] ?? 'var(--color-surface-alt)';
}

function expTextColor(level) {
    const map = {
        student:         '#8B5CF6',
        fresh:           'var(--color-primary)',
        junior:          '#378ADD',
        mid:             '#D85A30',
        senior:          '#B8860B',
        ten_fifteen:     '#B8860B',
        fifteen_twenty:  '#B8860B',
        twenty_plus:     '#B8860B',
    };
    return map[level] ?? 'var(--color-text-secondary)';
}
</script>

<template>
    <Head title="Members — Admin" />

    <AdminLayout title="Members">
        <div class="um-wrap">

            <!-- ══════════════════════════════════════════════════
                 PAGE HEADER
            ═══════════════════════════════════════════════════════ -->
            <div class="um-header">
                <div>
                    <h1 class="um-title">Members</h1>
                    <p class="um-sub">
                        {{ users.total.toLocaleString() }} total ·
                        {{ users.from ?? 0 }}–{{ users.to ?? 0 }} shown
                    </p>
                </div>
                <Link :href="route('admin.dashboard')" class="um-back-link">
                    ← Dashboard
                </Link>
            </div>

            <!-- ══════════════════════════════════════════════════
                 FILTER BAR
            ═══════════════════════════════════════════════════════ -->
            <div class="um-filters">

                <!-- Search -->
                <div class="um-search-wrap">
                    <svg class="um-search-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
                    </svg>
                    <input
                        v-model="search"
                        type="text"
                        class="um-search"
                        placeholder="Search by name, email or nickname…"
                        @input="onSearchInput"
                    />
                </div>

                <!-- Hub filter -->
                <select v-model="selectedHub" class="um-select" @change="applyFilters">
                    <option value="">All Hubs</option>
                    <option v-for="hub in hubs" :key="hub.id" :value="hub.id">
                        {{ hub.name_en }}
                    </option>
                </select>

                <!-- Experience filter — all 8 levels -->
                <select v-model="selectedLevel" class="um-select" @change="applyFilters">
                    <option value="">All Levels</option>
                    <option value="student">Student</option>
                    <option value="fresh">Fresh Graduate</option>
                    <option value="junior">Junior (1–3 yrs)</option>
                    <option value="mid">Mid-Level (3–5 yrs)</option>
                    <option value="senior">Senior (5–10 yrs)</option>
                    <option value="ten_fifteen">10–15 Years</option>
                    <option value="fifteen_twenty">15–20 Years</option>
                    <option value="twenty_plus">20+ Years</option>
                </select>

                <!-- Status filter -->
                <select v-model="selectedStatus" class="um-select" @change="applyFilters">
                    <option value="">All Status</option>
                    <option value="active">Active</option>
                    <option value="suspended">Suspended</option>
                </select>

                <!-- Clear -->
                <button v-if="hasActiveFilters" class="um-clear-btn" @click="clearFilters">
                    Clear
                </button>

            </div>

            <!-- ══════════════════════════════════════════════════
                 DESKTOP TABLE
            ═══════════════════════════════════════════════════════ -->
            <div class="um-table-wrap">
                <table class="um-table">
                    <thead>
                        <tr>
                            <th>Member</th>
                            <th>Nickname</th>
                            <th>Profession</th>
                            <th>Level</th>
                            <th>Hubs</th>
                            <th>Joined</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="member in localUsers" :key="member.id" :class="{ 'um-row--suspended': !member.is_active }">

                            <!-- Member identity -->
                            <td>
                                <div class="um-member-cell">
                                    <div class="um-avatar" :class="{ 'um-avatar--suspended': !member.is_active }">
                                        {{ member.name.charAt(0).toUpperCase() }}
                                    </div>
                                    <div>
                                        <div class="um-name">{{ member.name }}</div>
                                        <div class="um-email">{{ member.email }}</div>
                                    </div>
                                </div>
                            </td>

                            <!-- Nickname -->
                            <td class="um-nickname">@{{ member.nickname }}</td>

                            <!-- Profession -->
                            <td class="um-cell">{{ member.profession ?? '—' }}</td>

                            <!-- Level -->
                            <td>
                                <span
                                    class="um-level-badge"
                                    :style="{ background: expColor(member.experience_level), color: expTextColor(member.experience_level) }"
                                >
                                    {{ expLabel(member.experience_level) }}
                                </span>
                            </td>

                            <!-- Hubs -->
                            <td>
                                <div class="um-hub-dots">
                                    <span
                                        v-for="hub in member.hubs"
                                        :key="hub.id"
                                        class="um-hub-chip"
                                        :style="{ background: hub.color + '22', color: hub.color }"
                                    >
                                        {{ hub.name_en }}
                                    </span>
                                </div>
                            </td>

                            <!-- Joined -->
                            <td class="um-cell um-cell--muted" :title="member.created_at">
                                {{ member.created_at_diff }}
                            </td>

                            <!-- Status badge -->
                            <td>
                                <span
                                    class="um-status"
                                    :class="member.is_active ? 'um-status--active' : 'um-status--suspended'"
                                >
                                    {{ member.is_active ? 'Active' : 'Suspended' }}
                                </span>
                            </td>

                            <!-- Toggle action -->
                            <td>
                                <button
                                    class="um-toggle-btn"
                                    :class="member.is_active ? 'um-toggle-btn--suspend' : 'um-toggle-btn--activate'"
                                    :disabled="togglingId === member.id"
                                    @click="toggleActive(member)"
                                >
                                    <span v-if="togglingId === member.id">…</span>
                                    <span v-else-if="member.is_active">Suspend</span>
                                    <span v-else>Activate</span>
                                </button>
                            </td>

                        </tr>

                        <tr v-if="localUsers.length === 0">
                            <td colspan="8" class="um-empty">
                                No members match these filters.
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- ══════════════════════════════════════════════════
                 MOBILE CARDS
            ═══════════════════════════════════════════════════════ -->
            <div class="um-cards">
                <div
                    v-for="member in localUsers"
                    :key="'c-' + member.id"
                    class="um-card"
                    :class="{ 'um-card--suspended': !member.is_active }"
                >
                    <div class="um-card__head">
                        <div class="um-avatar" :class="{ 'um-avatar--suspended': !member.is_active }">
                            {{ member.name.charAt(0).toUpperCase() }}
                        </div>
                        <div class="um-card__identity">
                            <div class="um-name">{{ member.name }}</div>
                            <div class="um-email">{{ member.email }}</div>
                        </div>
                        <span
                            class="um-status"
                            :class="member.is_active ? 'um-status--active' : 'um-status--suspended'"
                        >
                            {{ member.is_active ? 'Active' : 'Suspended' }}
                        </span>
                    </div>

                    <div class="um-card__meta">
                        <span class="um-card__meta-item">@{{ member.nickname }}</span>
                        <span class="um-card__sep">·</span>
                        <span
                            class="um-level-badge"
                            :style="{ background: expColor(member.experience_level), color: expTextColor(member.experience_level) }"
                        >{{ expLabel(member.experience_level) }}</span>
                        <span class="um-card__sep">·</span>
                        <span class="um-card__meta-item">{{ member.created_at_diff }}</span>
                    </div>

                    <div v-if="member.profession" class="um-card__profession">
                        {{ member.profession }}
                    </div>

                    <div class="um-card__hubs">
                        <span
                            v-for="hub in member.hubs"
                            :key="hub.id"
                            class="um-hub-chip"
                            :style="{ background: hub.color + '22', color: hub.color }"
                        >{{ hub.name_en }}</span>
                    </div>

                    <div class="um-card__actions">
                        <button
                            class="um-toggle-btn um-toggle-btn--full"
                            :class="member.is_active ? 'um-toggle-btn--suspend' : 'um-toggle-btn--activate'"
                            :disabled="togglingId === member.id"
                            @click="toggleActive(member)"
                        >
                            <span v-if="togglingId === member.id">Processing…</span>
                            <span v-else-if="member.is_active">Suspend Account</span>
                            <span v-else>Reactivate Account</span>
                        </button>
                    </div>
                </div>

                <div v-if="localUsers.length === 0" class="um-empty-mobile">
                    No members match these filters.
                </div>
            </div>

            <!-- ══════════════════════════════════════════════════
                 PAGINATION
            ═══════════════════════════════════════════════════════ -->
            <div v-if="users.last_page > 1" class="um-pagination">

                <!-- Previous -->
                <Link
                    v-if="users.prev_page_url"
                    :href="users.prev_page_url"
                    class="um-page-btn"
                >
                    ← Prev
                </Link>
                <span v-else class="um-page-btn um-page-btn--disabled">← Prev</span>

                <!-- Page numbers -->
                <template v-for="link in users.links" :key="link.label">
                    <span
                        v-if="link.label === '...'"
                        class="um-page-ellipsis"
                    >…</span>
                    <Link
                        v-else-if="link.url && link.label !== '&laquo; Previous' && link.label !== 'Next &raquo;'"
                        :href="link.url"
                        class="um-page-btn"
                        :class="{ 'um-page-btn--active': link.active }"
                    >
                        {{ link.label }}
                    </Link>
                </template>

                <!-- Next -->
                <Link
                    v-if="users.next_page_url"
                    :href="users.next_page_url"
                    class="um-page-btn"
                >
                    Next →
                </Link>
                <span v-else class="um-page-btn um-page-btn--disabled">Next →</span>

            </div>

        </div><!-- /um-wrap -->
    </AdminLayout>
</template>

<style scoped>
/* ── Container ───────────────────────────────────────────────── */
.um-wrap {
    max-width: 1250px;
    margin: 0 auto;
    padding: var(--space-6) var(--space-4);
    display: flex;
    flex-direction: column;
    gap: var(--space-5);
}

/* ── Header ──────────────────────────────────────────────────── */
.um-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: var(--space-4);
    flex-wrap: wrap;
}

.um-title {
    font-size: var(--text-2xl);
    font-weight: var(--fw-bold);
    color: var(--color-text-primary);
    margin: 0 0 var(--space-1);
}

.um-sub {
    font-size: var(--text-sm);
    color: var(--color-text-muted);
    margin: 0;
}

.um-back-link {
    font-size: var(--text-sm);
    font-weight: var(--fw-medium);
    color: var(--color-primary);
    text-decoration: none;
    flex-shrink: 0;
    padding-top: var(--space-1);
}

.um-back-link:hover { opacity: 0.75; }

/* ── Filter bar ──────────────────────────────────────────────── */
.um-filters {
    display: flex;
    flex-wrap: wrap;
    gap: var(--space-3);
    align-items: center;
}

.um-search-wrap {
    position: relative;
    flex: 1;
    min-width: 200px;
}

.um-search-icon {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--color-text-muted);
    pointer-events: none;
}

.um-search {
    width: 100%;
    padding: var(--space-2) var(--space-3) var(--space-2) 32px;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    font-size: var(--text-sm);
    color: var(--color-text-primary);
    outline: none;
    transition: border-color var(--transition-fast);
}

.um-search:focus {
    border-color: var(--color-primary);
}

.um-select {
    padding: var(--space-2) var(--space-3);
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    font-size: var(--text-sm);
    color: var(--color-text-primary);
    outline: none;
    cursor: pointer;
    transition: border-color var(--transition-fast);
}

.um-select:focus {
    border-color: var(--color-primary);
}

.um-clear-btn {
    padding: var(--space-2) var(--space-3);
    background: transparent;
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    font-size: var(--text-sm);
    font-weight: var(--fw-medium);
    color: var(--color-text-secondary);
    cursor: pointer;
    transition: border-color var(--transition-fast), color var(--transition-fast);
}

.um-clear-btn:hover {
    border-color: var(--color-danger);
    color: var(--color-danger);
}

/* ── Desktop table ───────────────────────────────────────────── */
.um-table-wrap {
    display: none;
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    overflow: hidden;
    overflow-x: auto;
}

@media (min-width: 768px) {
    .um-table-wrap { display: block; }
}

.um-table {
    width: 100%;
    border-collapse: collapse;
    font-size: var(--text-sm);
}

.um-table thead tr {
    background: var(--color-surface-alt);
    border-bottom: 1px solid var(--color-border);
}

.um-table th {
    padding: var(--space-3) var(--space-4);
    text-align: left;
    font-size: 11px;
    font-weight: var(--fw-semibold);
    color: var(--color-text-muted);
    text-transform: uppercase;
    letter-spacing: 0.05em;
    white-space: nowrap;
}

.um-table tbody tr {
    border-bottom: 1px solid var(--color-border);
    transition: background var(--transition-fast);
}

.um-table tbody tr:last-child { border-bottom: none; }

.um-table tbody tr:hover { background: var(--color-surface-alt); }

.um-row--suspended td { opacity: 0.65; }
.um-row--suspended:hover { background: rgba(229,57,53,0.04) !important; }

.um-table td {
    padding: var(--space-3) var(--space-4);
    vertical-align: middle;
}

.um-empty {
    text-align: center;
    color: var(--color-text-muted);
    padding: var(--space-10) !important;
}

/* Member cell */
.um-member-cell {
    display: flex;
    align-items: center;
    gap: var(--space-3);
}

.um-avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--color-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    font-weight: var(--fw-bold);
    color: #fff;
    flex-shrink: 0;
    letter-spacing: 0.03em;
}

.um-avatar--suspended {
    background: var(--color-text-muted);
}

.um-name {
    font-weight: var(--fw-medium);
    color: var(--color-text-primary);
    white-space: nowrap;
}

.um-email {
    font-size: var(--text-xs);
    color: var(--color-text-muted);
    white-space: nowrap;
}

.um-nickname {
    font-family: monospace;
    font-size: var(--text-xs);
    color: var(--color-text-muted);
}

.um-cell {
    color: var(--color-text-secondary);
    white-space: nowrap;
}

.um-cell--muted {
    color: var(--color-text-muted);
    font-size: var(--text-xs);
}

/* Level badge */
.um-level-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: var(--radius-pill);
    font-size: 11px;
    font-weight: var(--fw-medium);
    white-space: nowrap;
}

/* Hub chips */
.um-hub-dots {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}

.um-hub-chip {
    display: inline-block;
    padding: 2px 7px;
    border-radius: var(--radius-pill);
    font-size: 10px;
    font-weight: var(--fw-semibold);
    white-space: nowrap;
}

/* Status badge */
.um-status {
    display: inline-block;
    padding: 2px 8px;
    border-radius: var(--radius-pill);
    font-size: 11px;
    font-weight: var(--fw-semibold);
    white-space: nowrap;
}

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

.um-status--suspended {
    background: rgba(229, 57, 53, 0.10);
    color: var(--color-danger);
}

/* Toggle button */
.um-toggle-btn {
    padding: var(--space-1) var(--space-3);
    border-radius: var(--radius-sm);
    font-size: var(--text-xs);
    font-weight: var(--fw-semibold);
    cursor: pointer;
    border: 1px solid transparent;
    transition: opacity var(--transition-fast), background var(--transition-fast);
    white-space: nowrap;
}

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

.um-toggle-btn--suspend {
    background: rgba(229, 57, 53, 0.08);
    color: var(--color-danger);
    border-color: rgba(229, 57, 53, 0.20);
}

.um-toggle-btn--suspend:hover:not(:disabled) {
    background: rgba(229, 57, 53, 0.15);
}

.um-toggle-btn--activate {
    background: rgba(29, 158, 117, 0.10);
    color: var(--color-primary);
    border-color: rgba(29, 158, 117, 0.20);
}

.um-toggle-btn--activate:hover:not(:disabled) {
    background: rgba(29, 158, 117, 0.18);
}

.um-toggle-btn--full {
    width: 100%;
    padding: var(--space-2) var(--space-3);
    font-size: var(--text-sm);
}

/* ── Mobile cards ────────────────────────────────────────────── */
.um-cards {
    display: flex;
    flex-direction: column;
    gap: var(--space-3);
}

@media (min-width: 768px) {
    .um-cards { display: none; }
}

.um-card {
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-lg);
    padding: var(--space-4);
    display: flex;
    flex-direction: column;
    gap: var(--space-3);
    transition: border-color var(--transition-fast);
}

.um-card--suspended {
    opacity: 0.75;
    border-color: rgba(229, 57, 53, 0.20);
}

.um-card__head {
    display: flex;
    align-items: center;
    gap: var(--space-3);
}

.um-card__identity {
    flex: 1;
    min-width: 0;
}

.um-card__meta {
    display: flex;
    align-items: center;
    gap: var(--space-2);
    flex-wrap: wrap;
}

.um-card__meta-item {
    font-size: var(--text-xs);
    color: var(--color-text-muted);
}

.um-card__sep {
    color: var(--color-border);
    font-size: var(--text-xs);
}

.um-card__profession {
    font-size: var(--text-sm);
    color: var(--color-text-secondary);
}

.um-card__hubs {
    display: flex;
    flex-wrap: wrap;
    gap: var(--space-2);
}

.um-card__actions {
    padding-top: var(--space-2);
    border-top: 1px solid var(--color-border);
}

.um-empty-mobile {
    text-align: center;
    color: var(--color-text-muted);
    font-size: var(--text-sm);
    padding: var(--space-10) 0;
}

/* ── Pagination ──────────────────────────────────────────────── */
.um-pagination {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: var(--space-2);
    flex-wrap: wrap;
    padding-bottom: var(--space-4);
}

.um-page-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 36px;
    height: 36px;
    padding: 0 var(--space-3);
    background: var(--color-surface);
    border: 1px solid var(--color-border);
    border-radius: var(--radius-md);
    font-size: var(--text-sm);
    font-weight: var(--fw-medium);
    color: var(--color-text-secondary);
    text-decoration: none;
    cursor: pointer;
    transition: background var(--transition-fast), border-color var(--transition-fast), color var(--transition-fast);
}

.um-page-btn:hover {
    background: var(--color-primary-soft);
    border-color: var(--color-primary);
    color: var(--color-primary);
}

.um-page-btn--active {
    background: var(--color-primary) !important;
    border-color: var(--color-primary) !important;
    color: #fff !important;
}

.um-page-btn--disabled {
    opacity: 0.40;
    cursor: default;
    pointer-events: none;
}

.um-page-ellipsis {
    color: var(--color-text-muted);
    font-size: var(--text-sm);
    padding: 0 var(--space-1);
}
</style>