'use client';

/**
 * PaymentForm — provider-dispatching card form.
 *
 * With Stripe as the live payment provider, interactive checkout uses Stripe's
 * hosted PaymentElement flow (implemented in CheckoutFlow). This component
 * remains as the entry point for mock-provider dev scenarios only.
 *
 * The `scenario` for MockCardForm is read client-side from the `md_mock_scenario`
 * cookie, defaulting to 'success'. Reading is deferred to useEffect to avoid
 * SSR/client hydration mismatches (React #418).
 */

import { useEffect, useState } from 'react';
import type { ClientConfig } from '@/server/payments/provider';
import { isMockScenario, type MockScenario } from '@/server/payments/mock/scenarios';
import { MockCardForm } from './MockCardForm';

// ─── Props ────────────────────────────────────────────────────────────────────

export interface PaymentFormProps {
  /**
   * Provider config returned by GET /api/payments/client-config.
   * Discriminant `provider` determines which sub-form is rendered.
   */
  config: ClientConfig;
  /**
   * Called with the single-use token when the user submits the card form.
   * For Mock: `mock_tok_<scenario>` synthetic token (no brand).
   */
  onToken: (singleUseToken: string, detectedBrand?: string) => void;
  /** Whether a charge is in progress (disables the form). */
  isProcessing?: boolean;
  /** Optional error message surfaced from a prior charge attempt. */
  externalError?: string | null;
  /** Optional submit-button label override. */
  submitLabel?: string;
}

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

export function PaymentForm({
  config,
  onToken,
  isProcessing = false,
  externalError,
}: PaymentFormProps) {
  // Read md_mock_scenario cookie post-mount to avoid SSR/hydration mismatch.
  const [scenario, setScenario] = useState<MockScenario>('success');

  useEffect(() => {
    const match = document.cookie.match(/(?:^|;\s*)md_mock_scenario=([^;]+)/);
    const raw = match?.[1] ?? null;

    const timer = setTimeout(() => setScenario(isMockScenario(raw) ? raw : 'success'), 0);
    return () => clearTimeout(timer);
  }, []);

  // Stripe provider: PaymentElement is rendered inline by CheckoutFlow;
  // this component is only used by the mock dev path.
  if (config.provider === 'stripe') {
    return null;
  }

  return (
    <MockCardForm
      scenario={scenario}
      onToken={onToken}
      isProcessing={isProcessing}
      externalError={externalError ?? undefined}
    />
  );
}
