<script setup>
import { computed, reactive, ref } from 'vue';
import { Head, router, useForm } from '@inertiajs/vue3';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import AppCard from '@/Components/ui/AppCard.vue';
import AppModal from '@/Components/ui/AppModal.vue';
import AppTable from '@/Components/ui/AppTable.vue';
import AppTabs from '@/Components/ui/AppTabs.vue';

const props = defineProps({
    rules: { type: Object, required: true },
    filters: { type: Object, default: () => ({}) },
    statuses: { type: Array, default: () => ['active', 'inactive'] },
    types: { type: Array, default: () => ['fixed', 'percent'] },
    tiers: { type: Array, default: () => ['subscriber', 'reseller', 'agent'] },
    categories: { type: Array, default: () => [] },
    networks: { type: Array, default: () => [] },
    summary: { type: Object, default: () => ({}) },
    settings: {
        type: Object,
        default: () => ({ enabled: false, expiry_enabled: false, expiry_days: 90 }),
    },
});

const filters = reactive({
    q: props.filters?.q || '',
    status: props.filters?.status || '',
});

const settingsForm = useForm({
    enabled: !!props.settings?.enabled,
    expiry_enabled: !!props.settings?.expiry_enabled,
    expiry_days: props.settings?.expiry_days ?? 90,
});

const modalOpen = ref(false);
const editingId = ref(null);
const activeTab = ref('rules');

const ruleForm = useForm({
    name: '',
    priority: 100,
    status: 'inactive',
    type: 'percent',
    value: '',
    min_amount: '',
    max_cashback: '',
    allow_with_coupon: false,
    applicable_category_ids: [],
    applicable_network_ids: [],
    applicable_customer_tiers: [],
    applicable_user_ids_text: '',
    starts_at: '',
    ends_at: '',
});

const isEditing = computed(() => editingId.value !== null);

const openCreate = () => {
    editingId.value = null;
    ruleForm.reset();
    ruleForm.clearErrors();
    ruleForm.priority = 100;
    ruleForm.status = 'inactive';
    ruleForm.type = 'percent';
    ruleForm.allow_with_coupon = false;
    ruleForm.applicable_category_ids = [];
    ruleForm.applicable_network_ids = [];
    ruleForm.applicable_customer_tiers = [];
    ruleForm.applicable_user_ids_text = '';
    modalOpen.value = true;
};

const openEdit = (rule) => {
    editingId.value = rule.id;
    ruleForm.clearErrors();
    ruleForm.name = rule.name || '';
    ruleForm.priority = rule.priority ?? 100;
    ruleForm.status = rule.status || 'inactive';
    ruleForm.type = rule.type || 'percent';
    ruleForm.value = rule.value ?? '';
    ruleForm.min_amount = rule.min_amount ?? '';
    ruleForm.max_cashback = rule.max_cashback ?? '';
    ruleForm.allow_with_coupon = !!rule.allow_with_coupon;
    ruleForm.applicable_category_ids = (rule.applicable_category_ids || []).map((v) => Number(v));
    ruleForm.applicable_network_ids = (rule.applicable_network_ids || []).map((v) => Number(v));
    ruleForm.applicable_customer_tiers = [...(rule.applicable_customer_tiers || [])];
    ruleForm.applicable_user_ids_text = (rule.applicable_user_ids || []).join(', ');
    ruleForm.starts_at = rule.starts_at || '';
    ruleForm.ends_at = rule.ends_at || '';
    modalOpen.value = true;
};

const closeModal = () => {
    if (ruleForm.processing) return;
    modalOpen.value = false;
};

const saveSettings = () => {
    settingsForm
        .transform((data) => ({
            enabled: !!data.enabled,
            expiry_enabled: !!data.expiry_enabled,
            expiry_days: Number(data.expiry_days || 0),
        }))
        .put(route('admin.cashbacks.settings.update'), {
        preserveScroll: true,
        onFinish: () => settingsForm.transform((data) => data),
    });
};

const submitRule = () => {
    const payload = {
        ...ruleForm.data(),
        min_amount: ruleForm.min_amount === '' ? null : ruleForm.min_amount,
        max_cashback: ruleForm.max_cashback === '' ? null : ruleForm.max_cashback,
        starts_at: ruleForm.starts_at || null,
        ends_at: ruleForm.ends_at || null,
    };

    if (isEditing.value) {
        ruleForm.transform(() => payload).put(route('admin.cashbacks.update', editingId.value), {
            preserveScroll: true,
            onSuccess: () => closeModal(),
        });
        return;
    }

    ruleForm.transform(() => payload).post(route('admin.cashbacks.store'), {
        preserveScroll: true,
        onSuccess: () => closeModal(),
    });
};

const applyFilters = () => {
    router.get(route('admin.cashbacks.index'), {
        q: filters.q || undefined,
        status: filters.status || undefined,
    }, {
        preserveState: true,
        preserveScroll: true,
        replace: true,
    });
};

const clearFilters = () => {
    filters.q = '';
    filters.status = '';
    applyFilters();
};

const toggleSelection = (field, value) => {
    const normalized = Number.isFinite(Number(value)) ? Number(value) : value;
    const current = Array.isArray(ruleForm[field]) ? [...ruleForm[field]] : [];
    const exists = current.some((item) => String(item) === String(normalized));
    ruleForm[field] = exists
        ? current.filter((item) => String(item) !== String(normalized))
        : [...current, normalized];
};

const selectionHas = (field, value) => (ruleForm[field] || []).some((item) => String(item) === String(value));

const statusChipClass = (status) => ({
    active: 'bg-emerald-50 text-emerald-700 ring-emerald-200',
    inactive: 'bg-slate-100 text-slate-700 ring-slate-200',
}[status] || 'bg-slate-100 text-slate-700 ring-slate-200');

const formatCurrency = (value) => {
    const n = Number(value || 0);
    if (Number.isNaN(n)) return 'NGN 0.00';
    return `NGN ${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};

const cashbackValueLabel = (rule) => rule.type === 'percent'
    ? `${Number(rule.value).toFixed(2)}%`
    : formatCurrency(rule.value);

const pageTabs = computed(() => ([
    { key: 'rules', label: 'Rules', count: props.rules?.total ?? props.rules?.data?.length ?? 0 },
    { key: 'overview', label: 'Overview' },
]));
</script>

<template>
    <Head title="Cashback" />

    <AdminLayout>
        <template #header>
            <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h2 class="text-xl font-semibold text-slate-900">Cashback</h2>
                    <p class="mt-1 text-sm text-slate-500">Instant cashback balance credit after successful transactions. Default behavior is non-stackable with coupons.</p>
                </div>
                <button
                    type="button"
                    class="inline-flex items-center justify-center rounded-lg border border-slate-900 bg-slate-900 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-800"
                    @click="openCreate"
                >
                    + New Cashback Rule
                </button>
            </div>
        </template>

        <div class="mx-auto max-w-7xl space-y-5 px-4 py-6 sm:px-6 lg:px-8">
            <AppTabs v-model="activeTab" :tabs="pageTabs" aria-label="Cashback sections" />

            <div v-if="activeTab === 'overview'" class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                <AppCard title="Rules" :subtitle="String(summary?.rules_total ?? 0)" />
                <AppCard title="Active Rules" :subtitle="String(summary?.rules_active ?? 0)" />
                <AppCard title="Credited Rewards" :subtitle="String(summary?.rewards_credited ?? 0)" />
                <AppCard title="Total Cashback" :subtitle="formatCurrency(summary?.total_cashback ?? 0)" />
            </div>

            <AppCard v-if="activeTab === 'overview'" title="Cashback Engine" subtitle="Global toggle for all cashback payouts.">
                <div class="space-y-3 rounded-xl border border-slate-200 bg-slate-50 p-4">
                    <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <div>
                            <div class="text-sm font-semibold text-slate-900">Cashback is {{ settingsForm.enabled ? 'On' : 'Off' }}</div>
                            <p class="mt-1 text-xs text-slate-500">When off, no cashback is credited even if rules are active.</p>
                        </div>
                        <div class="inline-flex items-center gap-2">
                            <button
                                type="button"
                                class="rounded-lg border px-3 py-2 text-xs font-semibold"
                                :class="settingsForm.enabled ? 'border-emerald-600 bg-emerald-600 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                                :disabled="settingsForm.processing"
                                @click="settingsForm.enabled = true"
                            >
                                Turn On
                            </button>
                            <button
                                type="button"
                                class="rounded-lg border px-3 py-2 text-xs font-semibold"
                                :class="!settingsForm.enabled ? 'border-rose-600 bg-rose-600 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                                :disabled="settingsForm.processing"
                                @click="settingsForm.enabled = false"
                            >
                                Turn Off
                            </button>
                        </div>
                    </div>

                    <div class="rounded-xl border border-slate-200 bg-white p-3">
                        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                            <div>
                                <div class="text-sm font-semibold text-slate-900">Expiry Policy</div>
                                <p class="mt-1 text-xs text-slate-500">Expire cashback balance when no cashback activity happens for configured days.</p>
                            </div>
                            <div class="inline-flex items-center gap-2">
                                <button
                                    type="button"
                                    class="rounded-lg border px-3 py-2 text-xs font-semibold"
                                    :class="settingsForm.expiry_enabled ? 'border-emerald-600 bg-emerald-600 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                                    :disabled="settingsForm.processing"
                                    @click="settingsForm.expiry_enabled = true"
                                >
                                    Turn On
                                </button>
                                <button
                                    type="button"
                                    class="rounded-lg border px-3 py-2 text-xs font-semibold"
                                    :class="!settingsForm.expiry_enabled ? 'border-rose-600 bg-rose-600 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                                    :disabled="settingsForm.processing"
                                    @click="settingsForm.expiry_enabled = false"
                                >
                                    Turn Off
                                </button>
                            </div>
                        </div>

                        <div class="mt-3 grid gap-3 sm:grid-cols-[240px_1fr] sm:items-center">
                            <label class="text-xs font-semibold uppercase tracking-wide text-slate-600">Expiry After (Days)</label>
                            <div>
                                <input
                                    v-model="settingsForm.expiry_days"
                                    type="number"
                                    min="1"
                                    max="3650"
                                    step="1"
                                    class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0"
                                />
                                <p class="mt-1 text-[11px] text-slate-500">Example: 90 means cashback expires after 90 days without cashback usage/credit activity.</p>
                                <p v-if="settingsForm.errors.expiry_days" class="mt-1 text-xs text-rose-600">{{ settingsForm.errors.expiry_days }}</p>
                            </div>
                        </div>
                    </div>

                    <div class="flex justify-end">
                        <button
                            type="button"
                            class="rounded-lg border border-slate-900 bg-slate-900 px-3 py-2 text-xs font-semibold text-white hover:bg-slate-800 disabled:opacity-60"
                            :disabled="settingsForm.processing"
                            @click="saveSettings"
                        >
                            {{ settingsForm.processing ? 'Saving...' : 'Save' }}
                        </button>
                    </div>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'rules'" title="Filter Rules" subtitle="Search rules by name or filter by status.">
                <div class="grid gap-3 md:grid-cols-[1fr_220px_auto_auto]">
                    <input v-model="filters.q" type="text" placeholder="Search rule name" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" @keyup.enter="applyFilters" />
                    <select v-model="filters.status" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0">
                        <option value="">All statuses</option>
                        <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                    </select>
                    <button type="button" class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50" @click="applyFilters">Apply</button>
                    <button type="button" class="rounded-lg border border-slate-200 bg-slate-50 px-4 py-2 text-sm font-semibold text-slate-600 hover:bg-slate-100" @click="clearFilters">Clear</button>
                </div>
            </AppCard>

            <AppCard v-if="activeTab === 'rules'" title="Cashback Rules" subtitle="Rules are evaluated by ascending priority (1 = highest priority).">
                <AppTable>
                    <thead class="bg-slate-50">
                        <tr class="text-left text-xs font-semibold uppercase tracking-wide text-slate-500">
                            <th class="px-4 py-3">Rule</th>
                            <th class="px-4 py-3">Priority</th>
                            <th class="px-4 py-3">Status</th>
                            <th class="px-4 py-3">Value</th>
                            <th class="px-4 py-3">Scope</th>
                            <th class="px-4 py-3">Uses</th>
                            <th class="px-4 py-3"></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm">
                        <tr v-for="rule in rules.data" :key="rule.id">
                            <td class="px-4 py-3 align-top">
                                <div class="font-medium text-slate-900">{{ rule.name }}</div>
                                <div class="mt-1 text-xs text-slate-500">
                                    {{ rule.allow_with_coupon ? 'Can apply with coupon' : 'No coupon stacking' }}
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top text-slate-700">{{ rule.priority }}</td>
                            <td class="px-4 py-3 align-top">
                                <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1 ring-inset" :class="statusChipClass(rule.status)">
                                    {{ rule.status }}
                                </span>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="font-medium text-slate-900">{{ cashbackValueLabel(rule) }}</div>
                                <div class="mt-1 text-xs text-slate-500">
                                    <span v-if="rule.min_amount !== null">Min {{ formatCurrency(rule.min_amount) }}</span>
                                    <span v-if="rule.min_amount !== null && rule.max_cashback !== null"> • </span>
                                    <span v-if="rule.max_cashback !== null">Cap {{ formatCurrency(rule.max_cashback) }}</span>
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="text-xs text-slate-600">
                                    <div>Categories: {{ (rule.applicable_category_ids || []).length || 'All' }}</div>
                                    <div>Networks: {{ (rule.applicable_network_ids || []).length || 'All' }}</div>
                                    <div>Tiers: {{ (rule.applicable_customer_tiers || []).length || 'All' }}</div>
                                    <div>Users: {{ (rule.applicable_user_ids || []).length || 'All' }}</div>
                                </div>
                            </td>
                            <td class="px-4 py-3 align-top text-xs text-slate-600">
                                Credited: {{ rule.credited_count || 0 }}
                            </td>
                            <td class="px-4 py-3 align-top">
                                <div class="flex justify-end">
                                    <button type="button" class="rounded-md border border-slate-300 px-2.5 py-1 text-xs font-semibold text-slate-700 hover:bg-slate-50" @click="openEdit(rule)">Edit</button>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="!rules.data?.length">
                            <td colspan="7" class="px-4 py-8 text-center text-sm text-slate-500">No cashback rules yet.</td>
                        </tr>
                    </tbody>
                </AppTable>

                <div v-if="rules.links?.length" class="mt-4 flex flex-wrap gap-2">
                    <button
                        v-for="link in rules.links"
                        :key="link.label"
                        type="button"
                        class="rounded-md border px-3 py-1.5 text-xs font-semibold"
                        :class="link.active ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-50'"
                        :disabled="!link.url"
                        @click="link.url && router.visit(link.url, { preserveScroll: true, preserveState: true })"
                        v-html="link.label"
                    />
                </div>
            </AppCard>
        </div>

        <AppModal :show="modalOpen" :title="isEditing ? 'Edit Cashback Rule' : 'Create Cashback Rule'" @close="closeModal">
            <div class="max-h-[75vh] space-y-4 overflow-y-auto pr-1">
                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Rule Name</label>
                        <input v-model="ruleForm.name" type="text" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="5% Data Cashback" />
                        <p v-if="ruleForm.errors.name" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.name }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Priority</label>
                        <input v-model="ruleForm.priority" type="number" min="1" step="1" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                        <p v-if="ruleForm.errors.priority" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.priority }}</p>
                    </div>
                </div>

                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Status</label>
                        <select v-model="ruleForm.status" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0">
                            <option v-for="status in statuses" :key="status" :value="status">{{ status }}</option>
                        </select>
                        <p v-if="ruleForm.errors.status" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.status }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Type</label>
                        <select v-model="ruleForm.type" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0">
                            <option value="percent">Percent (%)</option>
                            <option value="fixed">Fixed (NGN)</option>
                        </select>
                        <p v-if="ruleForm.errors.type" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.type }}</p>
                    </div>
                </div>

                <div class="grid gap-3 sm:grid-cols-3">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Value</label>
                        <input v-model="ruleForm.value" type="number" min="0.01" step="0.01" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                        <p v-if="ruleForm.errors.value" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.value }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Min Amount</label>
                        <input v-model="ruleForm.min_amount" type="number" min="0" step="0.01" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Optional" />
                        <p v-if="ruleForm.errors.min_amount" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.min_amount }}</p>
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Max Cashback</label>
                        <input v-model="ruleForm.max_cashback" type="number" min="0" step="0.01" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" placeholder="Optional" />
                        <p v-if="ruleForm.errors.max_cashback" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.max_cashback }}</p>
                    </div>
                </div>

                <label class="inline-flex items-center gap-2 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700">
                    <input v-model="ruleForm.allow_with_coupon" type="checkbox" class="rounded border-slate-300 text-slate-900 focus:ring-slate-400" />
                    Allow cashback even when a coupon discount was used on the same transaction
                </label>

                <div class="grid gap-3 sm:grid-cols-2">
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Starts At</label>
                        <input v-model="ruleForm.starts_at" type="datetime-local" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                    </div>
                    <div>
                        <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Ends At</label>
                        <input v-model="ruleForm.ends_at" type="datetime-local" class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0" />
                    </div>
                </div>
                <p v-if="ruleForm.errors.starts_at || ruleForm.errors.ends_at" class="text-xs text-rose-600">
                    {{ ruleForm.errors.starts_at || ruleForm.errors.ends_at }}
                </p>

                <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                    <div class="text-xs font-semibold uppercase tracking-wide text-slate-700">Target Customer Tiers (optional)</div>
                    <div class="mt-2 flex flex-wrap gap-2">
                        <button
                            v-for="tier in tiers"
                            :key="tier"
                            type="button"
                            class="rounded-full border px-3 py-1 text-xs font-semibold capitalize"
                            :class="selectionHas('applicable_customer_tiers', tier) ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                            @click="toggleSelection('applicable_customer_tiers', tier)"
                        >
                            {{ tier }}
                        </button>
                    </div>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                    <div class="text-xs font-semibold uppercase tracking-wide text-slate-700">Target Categories (optional)</div>
                    <div class="mt-2 flex flex-wrap gap-2">
                        <button
                            v-for="category in categories"
                            :key="category.id"
                            type="button"
                            class="rounded-full border px-3 py-1 text-xs font-semibold"
                            :class="selectionHas('applicable_category_ids', category.id) ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                            @click="toggleSelection('applicable_category_ids', category.id)"
                        >
                            {{ category.name }}
                        </button>
                    </div>
                </div>

                <div class="rounded-xl border border-slate-200 bg-slate-50 p-3">
                    <div class="text-xs font-semibold uppercase tracking-wide text-slate-700">Target Networks (optional)</div>
                    <div class="mt-2 flex flex-wrap gap-2">
                        <button
                            v-for="network in networks"
                            :key="network.id"
                            type="button"
                            class="rounded-full border px-3 py-1 text-xs font-semibold"
                            :class="selectionHas('applicable_network_ids', network.id) ? 'border-slate-900 bg-slate-900 text-white' : 'border-slate-300 bg-white text-slate-700 hover:bg-slate-100'"
                            @click="toggleSelection('applicable_network_ids', network.id)"
                        >
                            {{ network.name }}
                        </button>
                    </div>
                </div>

                <div>
                    <label class="mb-1 block text-xs font-semibold uppercase tracking-wide text-slate-700">Specific User IDs (optional)</label>
                    <textarea
                        v-model="ruleForm.applicable_user_ids_text"
                        rows="3"
                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm shadow-sm focus:border-slate-400 focus:ring-0"
                        placeholder="Comma or space separated user IDs e.g. 12, 19, 44"
                    />
                    <p class="mt-1 text-xs text-slate-500">Leave empty to apply to all users (subject to tier/category/network filters).</p>
                    <p v-if="ruleForm.errors.applicable_user_ids_text" class="mt-1 text-xs text-rose-600">{{ ruleForm.errors.applicable_user_ids_text }}</p>
                </div>

                <div class="flex items-center justify-end gap-2">
                    <button type="button" class="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50" :disabled="ruleForm.processing" @click="closeModal">Cancel</button>
                    <button type="button" class="rounded-lg border border-slate-900 bg-slate-900 px-4 py-2 text-sm font-semibold text-white hover:bg-slate-800 disabled:opacity-60" :disabled="ruleForm.processing" @click="submitRule">
                        {{ ruleForm.processing ? 'Saving...' : (isEditing ? 'Update Rule' : 'Create Rule') }}
                    </button>
                </div>
            </div>
        </AppModal>
    </AdminLayout>
</template>
