/**
 * PromoCodeForm — vendor promo-code create/edit form.
 *
 * Constraints (vendor scope):
 * - funder is fixed to 'vendor' (hidden; server also clamps)
 * - vendorId not editable (server clamps from session)
 * - scope.kind excludes 'all' — options: vendor | deals | categories | tags
 * - scope === 'deals' → deal picker fetches /api/vendor/deals/list?tab=active
 * - All kind options available: percentage / fixed_amount / bogo
 */

'use client';
import { ErrorState } from '@/components/ui/feedback/ErrorState';

import { useState, type SubmitEvent } from 'react';
import type { z } from 'zod';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { HydratedIsland } from '@/components/HydratedIsland';
import { VendorShell } from '@/components/ui/layout/VendorShell';
import { Badge } from '@/components/ui/primitives/Badge';
import { Button } from '@/components/ui/primitives/Button';
import { Input } from '@/components/ui/primitives/Input';
import { FormField } from '@/components/ui/primitives/FormField';
import {
  Select,
  SelectTrigger,
  SelectValue,
  SelectContent,
  SelectItem,
} from '@/components/ui/primitives/Select';
import { PageShellSkeleton, SkeletonGuard } from '@/components/ui/feedback/Skeleton';
import { useT } from '@/lib/i18n/react';
import { getCsrfToken } from '@/lib/csrf';
import { qk } from '@/lib/query/keys';
import { NumberInput } from '@/components/ui/primitives/NumberInput';
import { Checkbox } from '@/components/ui/primitives/Checkbox';
import { type PromoKind } from '@/lib/enums/promo-kind';
import { promoStatus } from '@/lib/enums/promo-status';
import { promoScopeKind } from '@/lib/enums/promo-scope-kind';

// ─── Types ────────────────────────────────────────────────────────────────────

// vendor cannot set 'archived' — archived is admin/system-only
const _VendorPromoStatus = promoStatus.schema.extract(['active', 'paused']);
type Status = z.infer<typeof _VendorPromoStatus>;

// vendor cannot create platform-wide ('all') promos — guard: SCOPE_ALL_FORBIDDEN
const _VendorPromoScopeKind = promoScopeKind.schema.extract([
  'deals',
  'categories',
  'tags',
  'vendor',
]);
type ScopeKind = z.infer<typeof _VendorPromoScopeKind>;
type DiscountKind = PromoKind;

interface VendorDeal {
  id: string;
  title: string;
}

interface FormValues {
  code: string;
  kind: DiscountKind;
  valueBps: string;
  valueAmount: string;
  bogoBuy: string;
  bogoGetFree: string;
  maxCapAmount: string;
  status: Status;
  validFrom: string;
  validUntil: string;
  minSubtotal: string;
  maxSubtotal: string;
  totalCap: string;
  perUserCap: string;
  description: string;
  scopeKind: ScopeKind;
  scopeDealIds: string[];
  scopeCategoryIds: string;
  scopeTagIds: string;
  eligibilityFirstPurchaseOnly: boolean;
  eligibilityClubOnly: boolean;
}

interface ApiPromoCode {
  id: string;
  code: string;
  kind: DiscountKind;
  valueBps: number | null;
  valueAmount: number | null;
  bogoBuy: number | null;
  bogoGetFree: number | null;
  maxCapAmount: number | null;
  status: Status | 'archived';
  validFrom: string | null;
  validUntil: string | null;
  minSubtotal: number | null;
  maxSubtotal: number | null;
  totalCap: number | null;
  perUserCap: number;
  description: string | null;
  rulesJson: {
    scope: {
      kind: ScopeKind;
      dealIds?: string[];
      categoryIds?: string[];
      tagIds?: string[];
      vendorId?: string;
    };
    eligibility: { firstPurchaseOnly?: boolean; clubOnly?: boolean };
  };
}

// ─── Defaults ─────────────────────────────────────────────────────────────────

function defaultValues(): FormValues {
  return {
    code: '',
    kind: 'percentage',
    valueBps: '',
    valueAmount: '',
    bogoBuy: '',
    bogoGetFree: '',
    maxCapAmount: '',
    status: 'active',
    validFrom: '',
    validUntil: '',
    minSubtotal: '',
    maxSubtotal: '',
    totalCap: '',
    perUserCap: '1',
    description: '',
    scopeKind: 'vendor',
    scopeDealIds: [],
    scopeCategoryIds: '',
    scopeTagIds: '',
    eligibilityFirstPurchaseOnly: false,
    eligibilityClubOnly: false,
  };
}

function codeToFormValues(code: ApiPromoCode): FormValues {
  const scope = code.rulesJson?.scope;
  const scopeKind: ScopeKind =
    scope?.kind === 'vendor' ||
    scope?.kind === 'deals' ||
    scope?.kind === 'categories' ||
    scope?.kind === 'tags'
      ? scope.kind
      : 'vendor';
  return {
    code: code.code,
    kind: code.kind,
    valueBps: code.valueBps != null ? String(code.valueBps / 100) : '',
    valueAmount: code.valueAmount != null ? String(code.valueAmount / 100) : '',
    bogoBuy: code.bogoBuy != null ? String(code.bogoBuy) : '',
    bogoGetFree: code.bogoGetFree != null ? String(code.bogoGetFree) : '',
    maxCapAmount: code.maxCapAmount != null ? String(code.maxCapAmount / 100) : '',
    status: code.status === 'archived' ? 'paused' : code.status,
    validFrom: code.validFrom ? code.validFrom.slice(0, 16) : '',
    validUntil: code.validUntil ? code.validUntil.slice(0, 16) : '',
    minSubtotal: code.minSubtotal != null ? String(code.minSubtotal / 100) : '',
    maxSubtotal: code.maxSubtotal != null ? String(code.maxSubtotal / 100) : '',
    totalCap: code.totalCap != null ? String(code.totalCap) : '',
    perUserCap: String(code.perUserCap),
    description: code.description ?? '',
    scopeKind,
    scopeDealIds: scope?.dealIds ?? [],
    scopeCategoryIds: (scope?.categoryIds ?? []).join(','),
    scopeTagIds: (scope?.tagIds ?? []).join(','),
    eligibilityFirstPurchaseOnly: code.rulesJson?.eligibility?.firstPurchaseOnly ?? false,
    eligibilityClubOnly: code.rulesJson?.eligibility?.clubOnly ?? false,
  };
}

function buildPayload(v: FormValues, vendorId: string) {
  // Build scope — never 'all'
  let scope: Record<string, unknown>;
  if (v.scopeKind === 'vendor') {
    scope = { kind: 'vendor', vendorId };
  } else if (v.scopeKind === 'deals') {
    scope = { kind: 'deals', dealIds: v.scopeDealIds };
  } else if (v.scopeKind === 'categories') {
    scope = {
      kind: 'categories',
      categoryIds: v.scopeCategoryIds
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
    };
  } else {
    scope = {
      kind: 'tags',
      tagIds: v.scopeTagIds
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean),
    };
  }

  const eligibility: Record<string, unknown> = {};
  if (v.eligibilityFirstPurchaseOnly) eligibility.firstPurchaseOnly = true;
  if (v.eligibilityClubOnly) eligibility.clubOnly = true;

  const payload: Record<string, unknown> = {
    code: v.code.trim().toUpperCase(),
    kind: v.kind,
    funder: 'vendor', // always vendor — server also clamps
    status: v.status,
    perUserCap: parseInt(v.perUserCap || '1', 10),
    rulesJson: { scope, eligibility },
  };

  if (v.kind === 'percentage' && v.valueBps) {
    payload.valueBps = Math.round(parseFloat(v.valueBps) * 100);
  }
  if (v.kind === 'fixed_amount' && v.valueAmount) {
    payload.valueAmount = Math.round(parseFloat(v.valueAmount) * 100);
  }
  if (v.kind === 'bogo') {
    if (v.bogoBuy) payload.bogoBuy = parseInt(v.bogoBuy, 10);
    if (v.bogoGetFree) payload.bogoGetFree = parseInt(v.bogoGetFree, 10);
  }
  if (v.maxCapAmount) payload.maxCapAmount = Math.round(parseFloat(v.maxCapAmount) * 100);
  if (v.validFrom) payload.validFrom = new Date(v.validFrom).toISOString();
  if (v.validUntil) payload.validUntil = new Date(v.validUntil).toISOString();
  if (v.minSubtotal) payload.minSubtotal = Math.round(parseFloat(v.minSubtotal) * 100);
  if (v.maxSubtotal) payload.maxSubtotal = Math.round(parseFloat(v.maxSubtotal) * 100);
  if (v.totalCap) payload.totalCap = parseInt(v.totalCap, 10);
  if (v.description) payload.description = v.description;

  return payload;
}

// ─── Vendor deals hook (for scope=deals picker) ───────────────────────────────

function useVendorActiveDeals(enabled: boolean) {
  return useQuery<VendorDeal[]>({
    queryKey: qk.vendorDeals('active'),
    queryFn: async () => {
      const res = await fetch('/api/vendor/deals/list?tab=active');
      if (!res.ok) return [];
      const json = (await res.json()) as { ok: boolean; deals: VendorDeal[] };
      return json.deals ?? [];
    },
    enabled,
    staleTime: 60_000,
  });
}

// ─── Component ────────────────────────────────────────────────────────────────

interface PromoCodeFormProps {
  /** When provided, loads the existing code and switches to edit mode. */
  codeId?: string;
}

function PromoCodeFormInner({ codeId }: PromoCodeFormProps) {
  const t = useT('promo_codes') as (key: string) => string;
  const tCommon = useT('common');
  const qc = useQueryClient();
  const isEdit = Boolean(codeId);

  const [values, setValues] = useState<FormValues>(defaultValues);
  const [loaded, setLoaded] = useState(false);
  const [isArchived, setIsArchived] = useState(false);
  const [serverError, setServerError] = useState<string | null>(null);

  // ── Load existing code ──
  const {
    isLoading: loadingCode,
    isError,
    refetch,
  } = useQuery<ApiPromoCode | null>({
    queryKey: ['vendor-promo-code', codeId],
    queryFn: async () => {
      if (!codeId) return null;
      const res = await fetch(`/api/vendor/promo-codes/${codeId}`);
      if (!res.ok) throw new Error('Not found');
      const json = (await res.json()) as { ok: boolean; data: { code: ApiPromoCode } };
      return json.data?.code ?? null;
    },
    enabled: isEdit,
    staleTime: 0,
    gcTime: 0,
  });

  // Apply loaded code to form (once)
  useQuery<ApiPromoCode | null>({
    queryKey: ['vendor-promo-code', codeId],
    select: (code) => {
      if (code && !loaded) {
        setValues(codeToFormValues(code));
        setIsArchived(code.status === 'archived');
        setLoaded(true);
      }
      return code;
    },
    enabled: isEdit,
    staleTime: 0,
  });

  // ── Vendor profile (needed for scope.vendorId in vendor-scoped codes) ──
  const { data: vendorProfile } = useQuery<{ id: string }>({
    queryKey: ['vendor-profile'],
    queryFn: async () => {
      const res = await fetch('/api/vendor/profile');
      if (!res.ok) throw new Error('Failed to load profile');
      const json = (await res.json()) as { ok: boolean; vendor: { id: string } };
      return json.vendor;
    },
    staleTime: 300_000,
  });

  // ── Deals for scope picker ──
  const { data: activeDeals = [] } = useVendorActiveDeals(values.scopeKind === 'deals');

  // ── Submit mutation ──
  const mutation = useMutation({
    mutationFn: async (payload: Record<string, unknown>) => {
      const url = isEdit ? `/api/vendor/promo-codes/${codeId}` : '/api/vendor/promo-codes';
      const method = isEdit ? 'PATCH' : 'POST';
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json', 'x-csrf-token': getCsrfToken() },
        body: JSON.stringify(payload),
      });
      const json = (await res.json()) as { ok: boolean; error?: string };
      if (!json.ok) throw new Error(json.error ?? 'Request failed');
      return json;
    },
    onSuccess: () => {
      void qc.invalidateQueries({ queryKey: ['vendor-promo-codes'] });
      window.location.href = '/vendor/promo-codes';
    },
    onError: (err: Error) => {
      setServerError(err.message);
    },
  });

  function set<K extends keyof FormValues>(key: K, val: FormValues[K]) {
    setValues((prev) => ({ ...prev, [key]: val }));
    setServerError(null);
  }

  function handleSubmit(e: SubmitEvent) {
    e.preventDefault();
    setServerError(null);
    if (!vendorProfile?.id) return; // guard: profile must be loaded before submitting
    const payload = buildPayload(values, vendorProfile.id);
    mutation.mutate(payload);
  }

  const isLoading = isEdit && loadingCode && !loaded;
  const pageTitle = isEdit ? t('vendor_edit_title') : t('vendor_new_title');

  // ── Scope kind options — excludes 'all' ──
  const scopeOptions: { value: ScopeKind; label: string }[] = [
    { value: 'vendor', label: t('vendor.scope_all_my_deals') },
    { value: 'deals', label: t('admin.form.scope_deals') },
    { value: 'categories', label: t('admin.form.scope_categories') },
    { value: 'tags', label: t('admin.form.scope_tags') },
  ];

  const kindOptions: { value: DiscountKind; label: string }[] = [
    { value: 'percentage', label: t('admin.form.kind_percentage') },
    { value: 'fixed_amount', label: t('admin.form.kind_fixed') },
    { value: 'bogo', label: t('admin.form.kind_bogo') },
  ];

  const statusOptions: { value: Status; label: string }[] = [
    { value: 'active', label: t('admin.form.status_active') },
    { value: 'paused', label: t('admin.form.status_paused') },
  ];

  if (isError) {
    return (
      <ErrorState
        title={tCommon('error_loading')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }
  return (
    <VendorShell variant="dashboard" currentPath="/vendor/promo-codes" pageTitle={pageTitle}>
      <main id="main" className="px-4 py-6 lg:px-8">
        <div className="mb-6 flex items-center gap-3">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              window.location.href = '/vendor/promo-codes';
            }}
            aria-label={t('admin.form.cancel')}
          >
            ←
          </Button>
        </div>

        {isLoading && (
          <div aria-busy="true" role="status">
            <span className="sr-only">{t('loading')}</span>
            <SkeletonGuard delay={0}>
              <PageShellSkeleton />
            </SkeletonGuard>
          </div>
        )}

        {!isLoading && isArchived && (
          <div className="mb-6 flex flex-col gap-3">
            <Badge tone="neutral" size="sm">
              {t('admin.form.status_archived')}
            </Badge>
            <p className="text-text-secondary text-sm">{t('vendor.archived_readonly')}</p>
            <Button
              type="button"
              variant="secondary"
              size="sm"
              onClick={() => {
                window.location.href = '/vendor/promo-codes';
              }}
            >
              {t('admin.form.cancel')}
            </Button>
          </div>
        )}

        {!isLoading && !isArchived && (
          <form
            onSubmit={handleSubmit}
            className="max-w-2xl space-y-6"
            aria-label={pageTitle}
            noValidate
          >
            {/* ── Code ── */}
            <FormField label={t('admin.form.code_label')} required htmlFor="promo-code">
              <Input
                id="promo-code"
                value={values.code}
                onChange={(e) => set('code', e.target.value.toUpperCase())}
                placeholder="SUMMER20"
                maxLength={64}
                required
                autoComplete="off"
                pattern="[A-Za-z0-9_-]+"
              />
            </FormField>

            {/* ── Description ── */}
            <FormField label={t('admin.form.description_label')} htmlFor="promo-desc">
              <Input
                id="promo-desc"
                value={values.description}
                onChange={(e) => set('description', e.target.value)}
                maxLength={280}
              />
            </FormField>

            {/* ── Kind ── */}
            <FormField label={t('admin.form.kind_label')} required htmlFor="promo-kind">
              <Select value={values.kind} onValueChange={(v) => set('kind', v as DiscountKind)}>
                <SelectTrigger id="promo-kind" aria-label={t('admin.form.kind_label')}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {kindOptions.map((o) => (
                    <SelectItem key={o.value} value={o.value}>
                      {o.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </FormField>

            {/* ── Kind-specific value fields ── */}
            {values.kind === 'percentage' && (
              <FormField label={t('admin.form.value_bps_label')} required htmlFor="promo-bps">
                <NumberInput
                  id="promo-bps"
                  min={0.01}
                  max={100}
                  step={0.01}
                  value={values.valueBps ? parseFloat(values.valueBps) : 0}
                  onChange={(n) => set('valueBps', String(n))}
                  required
                />
              </FormField>
            )}
            {values.kind === 'fixed_amount' && (
              <FormField label={t('admin.form.value_amount_label')} required htmlFor="promo-amount">
                <NumberInput
                  id="promo-amount"
                  min={0.01}
                  step={0.01}
                  value={values.valueAmount ? parseFloat(values.valueAmount) : 0}
                  onChange={(n) => set('valueAmount', String(n))}
                  required
                />
              </FormField>
            )}
            {values.kind === 'bogo' && (
              <div className="grid grid-cols-2 gap-4">
                <FormField label={t('admin.form.bogo_buy_label')} required htmlFor="promo-buy">
                  <NumberInput
                    id="promo-buy"
                    min={1}
                    step={1}
                    value={values.bogoBuy ? parseInt(values.bogoBuy, 10) : 1}
                    onChange={(n) => set('bogoBuy', String(n))}
                    required
                  />
                </FormField>
                <FormField label={t('admin.form.bogo_get_label')} required htmlFor="promo-get-free">
                  <NumberInput
                    id="promo-get-free"
                    min={1}
                    step={1}
                    value={values.bogoGetFree ? parseInt(values.bogoGetFree, 10) : 1}
                    onChange={(n) => set('bogoGetFree', String(n))}
                    required
                  />
                </FormField>
              </div>
            )}

            {/* ── Scope (no 'all') ── */}
            <FormField label={t('admin.form.scope_label')} required htmlFor="promo-scope">
              <Select
                value={values.scopeKind}
                onValueChange={(v) => set('scopeKind', v as ScopeKind)}
              >
                <SelectTrigger id="promo-scope" aria-label={t('admin.form.scope_label')}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {scopeOptions.map((o) => (
                    <SelectItem key={o.value} value={o.value}>
                      {o.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </FormField>

            {/* ── Scope: deal picker (vendor's own deals only) ── */}
            {values.scopeKind === 'deals' && (
              <fieldset className="space-y-2">
                <legend className="text-text-primary text-sm font-medium">
                  {t('admin.form.scope_deals')}
                </legend>
                {activeDeals.length === 0 && (
                  <p className="text-text-muted text-sm">{t('vendor.deal_picker_empty')}</p>
                )}
                <ul className="border-border-default max-h-48 overflow-y-auto rounded-md border p-2">
                  {activeDeals.map((deal) => {
                    const checked = values.scopeDealIds.includes(deal.id);
                    return (
                      <li key={deal.id} className="flex items-center gap-2 py-1">
                        <Checkbox
                          id={`deal-${deal.id}`}
                          checked={checked}
                          onCheckedChange={(v) => {
                            set(
                              'scopeDealIds',
                              v
                                ? [...values.scopeDealIds, deal.id]
                                : values.scopeDealIds.filter((id) => id !== deal.id),
                            );
                          }}
                        />
                        <label htmlFor={`deal-${deal.id}`} className="cursor-pointer text-sm">
                          {deal.title}
                        </label>
                      </li>
                    );
                  })}
                </ul>
              </fieldset>
            )}

            {/* ── Scope: category IDs ── */}
            {values.scopeKind === 'categories' && (
              <FormField
                label={t('admin.form.scope_categories')}
                htmlFor="promo-cat-ids"
                hint={t('admin.form.scope_ids_hint')}
              >
                <Input
                  id="promo-cat-ids"
                  value={values.scopeCategoryIds}
                  onChange={(e) => set('scopeCategoryIds', e.target.value)}
                  placeholder={t('admin.form.scope_ids_placeholder')}
                />
              </FormField>
            )}

            {/* ── Scope: tag IDs ── */}
            {values.scopeKind === 'tags' && (
              <FormField
                label={t('admin.form.scope_tags')}
                htmlFor="promo-tag-ids"
                hint={t('admin.form.scope_ids_hint')}
              >
                <Input
                  id="promo-tag-ids"
                  value={values.scopeTagIds}
                  onChange={(e) => set('scopeTagIds', e.target.value)}
                  placeholder={t('admin.form.scope_ids_placeholder')}
                />
              </FormField>
            )}

            {/* ── Status ── */}
            <FormField label={t('admin.form.status_label')} htmlFor="promo-status">
              <Select value={values.status} onValueChange={(v) => set('status', v as Status)}>
                <SelectTrigger id="promo-status" aria-label={t('admin.form.status_label')}>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {statusOptions.map((o) => (
                    <SelectItem key={o.value} value={o.value}>
                      {o.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </FormField>

            {/* ── Validity ── */}
            <fieldset className="space-y-4">
              <legend className="text-text-primary text-sm font-medium">
                {t('admin.form.validity_label')}
              </legend>
              <div className="grid grid-cols-2 gap-4">
                <FormField label={t('admin.form.from')} htmlFor="promo-from">
                  <Input
                    id="promo-from"
                    type="datetime-local"
                    value={values.validFrom}
                    onChange={(e) => set('validFrom', e.target.value)}
                  />
                </FormField>
                <FormField label={t('admin.form.until')} htmlFor="promo-until">
                  <Input
                    id="promo-until"
                    type="datetime-local"
                    value={values.validUntil}
                    onChange={(e) => set('validUntil', e.target.value)}
                  />
                </FormField>
              </div>
            </fieldset>

            {/* ── Caps ── */}
            <fieldset className="space-y-4">
              <legend className="text-text-primary text-sm font-medium">
                {t('admin.form.caps_label')}
              </legend>
              <div className="grid grid-cols-2 gap-4">
                <FormField label={t('admin.form.min_subtotal_label')} htmlFor="promo-min-subtotal">
                  <NumberInput
                    id="promo-min-subtotal"
                    min={0}
                    step={0.01}
                    value={values.minSubtotal ? parseFloat(values.minSubtotal) : 0}
                    onChange={(n) => set('minSubtotal', n > 0 ? String(n) : '')}
                  />
                </FormField>
                <FormField label={t('admin.form.max_subtotal_label')} htmlFor="promo-max-subtotal">
                  <NumberInput
                    id="promo-max-subtotal"
                    min={0}
                    step={0.01}
                    value={values.maxSubtotal ? parseFloat(values.maxSubtotal) : 0}
                    onChange={(n) => set('maxSubtotal', n > 0 ? String(n) : '')}
                  />
                </FormField>
                <FormField label={t('admin.form.max_cap_amount_label')} htmlFor="promo-max-cap">
                  <NumberInput
                    id="promo-max-cap"
                    min={0}
                    step={0.01}
                    value={values.maxCapAmount ? parseFloat(values.maxCapAmount) : 0}
                    onChange={(n) => set('maxCapAmount', n > 0 ? String(n) : '')}
                  />
                </FormField>
                <FormField label={t('admin.form.total_cap')} htmlFor="promo-total-cap">
                  <NumberInput
                    id="promo-total-cap"
                    min={1}
                    step={1}
                    value={values.totalCap ? parseInt(values.totalCap, 10) : 0}
                    onChange={(n) => set('totalCap', n > 0 ? String(n) : '')}
                  />
                </FormField>
                <FormField label={t('admin.form.per_user_cap')} required htmlFor="promo-user-cap">
                  <NumberInput
                    id="promo-user-cap"
                    min={1}
                    step={1}
                    value={values.perUserCap ? parseInt(values.perUserCap, 10) : 1}
                    onChange={(n) => set('perUserCap', String(n))}
                    required
                  />
                </FormField>
              </div>
            </fieldset>

            {/* ── Eligibility ── */}
            <fieldset className="space-y-2">
              <legend className="text-text-primary text-sm font-medium">
                {t('admin.form.eligibility_label')}
              </legend>
              <label className="flex cursor-pointer items-center gap-2 text-sm">
                <Checkbox
                  checked={values.eligibilityFirstPurchaseOnly}
                  onCheckedChange={(v) => set('eligibilityFirstPurchaseOnly', Boolean(v))}
                />
                {t('admin.form.first_purchase_only')}
              </label>
              <label className="flex cursor-pointer items-center gap-2 text-sm">
                <Checkbox
                  checked={values.eligibilityClubOnly}
                  onCheckedChange={(v) => set('eligibilityClubOnly', Boolean(v))}
                />
                {t('admin.form.club_only')}
              </label>
            </fieldset>

            {/* ── Server error ── */}
            {serverError && (
              <p className="text-danger-600 text-sm" role="alert">
                {serverError}
              </p>
            )}

            {/* ── Actions ── */}
            <div className="flex items-center gap-3 pt-2">
              <Button
                type="submit"
                variant="primary"
                loading={mutation.isPending}
                disabled={!vendorProfile?.id}
              >
                {t('admin.form.submit')}
              </Button>
              <Button
                type="button"
                variant="ghost"
                onClick={() => {
                  window.location.href = '/vendor/promo-codes';
                }}
              >
                {t('admin.form.cancel')}
              </Button>
            </div>
          </form>
        )}
      </main>
    </VendorShell>
  );
}

export function PromoCodeForm({ codeId }: PromoCodeFormProps) {
  return (
    <HydratedIsland>
      <PromoCodeFormInner codeId={codeId} />
    </HydratedIsland>
  );
}
