import { create } from 'zustand';
import type { DealType } from '@/lib/deal-types';
import type { FulfillmentInfo } from '@/server/domain/fulfillment/mode';
import type { GroupData } from './GroupDealStatusRow';

// ─── Shared types ────────────────────────────────────────────────────────────

export interface DealContext {
  id: string;
  groupDealId: string | null;
  title: string;
  businessName: string;
  thumbnailUrl: string | null;
  discountedPriceAgorot: number;
  originalPriceAgorot: number;
  dealType: DealType;
  fulfillment: FulfillmentInfo;
  vatRatePercent: number;
  skuLabel: string | null;
  defaultSkuId: string | null;
  csrfToken: string | null;
  isGuest: boolean;
  stockRemaining: number | null;
  maxPerUser: number | null;
  group: GroupData | null;
}

export interface CheckoutModalPreview {
  thumbnailUrl: string | null;
  title: string;
  businessName: string;
  skuLabel: string | null;
  /** null when no SKU is selected (multi-variant deal) — price row is skeletonised */
  discountedPriceAgorot: number | null;
  originalPriceAgorot: number | null;
}

// ─── Store ───────────────────────────────────────────────────────────────────

export interface CheckoutModalPayload {
  dealId: string;
  skuId: string | null;
  preview?: CheckoutModalPreview;
  /** In-flight fetch started on onPointerDown; modal awaits it instead of a fresh fetch. */
  pendingContextFetch?: Promise<{ ok: boolean; deal?: DealContext }>;
}

interface CheckoutModalStore {
  payload: CheckoutModalPayload | null;
  open(payload: CheckoutModalPayload): void;
  close(): void;
}

export const useCheckoutModalStore = create<CheckoutModalStore>((set) => ({
  payload: null,
  open: (payload) => set({ payload }),
  close: () => set({ payload: null }),
}));
