'use client';

/**
 * Payments — section 18 of /design-system.
 *
 * Renders <MockCardForm>, <StripePaymentElement>,
 * and <CheckoutComplete> with variants + token usage + a11y notes.
 */

import { useState } from 'react';
import { MockCardForm } from '@/features/checkout/MockCardForm';
import { MOCK_SCENARIOS } from '@/server/payments/mock/scenarios';
import { CheckoutShell } from '@/components/ui/layout/CheckoutShell';
import { CheckoutComplete } from '@/components/ui/checkout/CheckoutComplete';
import { ComponentEntry } from '../../components/ComponentEntry';
import { SectionShell } from '../../components/SectionShell';

export function Payments() {
  const [lastToken, setLastToken] = useState<string | null>(null);

  return (
    <SectionShell
      id="payments"
      title="18. Payments (MockCardForm)"
      description="MockCardForm — synthetic card form used when PAYMENT_PROVIDER=mock. Produces mock_tok_<scenario> without any real charge. Visual-only inputs; values are ignored."
    >
      {/* ── Variant: success scenario ─────────────────────────────────── */}
      <ComponentEntry
        id="mock-card-form-success"
        name="MockCardForm"
        path="src/features/checkout/MockCardForm"
        description="Default scenario: 'success'. On submit fires onToken('mock_tok_success')."
        tokens={[
          '--color-warning-50',
          '--color-warning-500',
          '--color-warning-700',
          '--color-brand-primary-600',
          '--color-neutral-200',
          '--color-neutral-900',
        ]}
        a11yNotes={[
          'All inputs have visible <Label> via FormField',
          'InlineNotice uses role="alert" (warning tone) to announce mock mode',
          'Submit button has aria-busy when isProcessing=true',
          'Focus rings visible on all interactive elements',
          'RTL-safe: logical props only (ps-*, pe-*, ms-*, me-*)',
        ]}
        importSnippet={`import { MockCardForm } from '@/features/checkout/MockCardForm';`}
      >
        <div className="max-w-sm rounded-lg border border-neutral-200 bg-white p-4">
          <MockCardForm scenario="success" onToken={(tok) => setLastToken(tok)} />
          {lastToken && (
            <p className="mt-3 text-xs text-neutral-500">
              Token produced: <code className="font-mono">{lastToken}</code>
            </p>
          )}
        </div>
      </ComponentEntry>

      {/* ── Variant: decline scenario ─────────────────────────────────── */}
      <ComponentEntry
        id="mock-card-form-decline"
        name="MockCardForm (decline)"
        path="src/features/checkout/MockCardForm"
        description="scenario='decline'. Produces mock_tok_decline → MockPaymentProvider returns CARD_DECLINED."
        tokens={[]}
        a11yNotes={['Same a11y guarantees as success variant']}
        importSnippet={`<MockCardForm scenario="decline" onToken={handleToken} />`}
      >
        <div className="max-w-sm rounded-lg border border-neutral-200 bg-white p-4">
          <MockCardForm scenario="decline" onToken={(tok) => setLastToken(tok)} />
        </div>
      </ComponentEntry>

      {/* ── Variant: with external error ──────────────────────────────── */}
      <ComponentEntry
        id="mock-card-form-error"
        name="MockCardForm (externalError)"
        path="src/features/checkout/MockCardForm"
        description="externalError prop shows InlineNotice with danger tone below the inputs."
        tokens={['--color-danger-50', '--color-danger-500', '--color-danger-700']}
        a11yNotes={[
          'InlineNotice uses role="alert" for danger tone — screen readers announce immediately',
        ]}
        importSnippet={`<MockCardForm scenario="success" externalError="Card declined" onToken={handleToken} />`}
      >
        <div className="max-w-sm rounded-lg border border-neutral-200 bg-white p-4">
          <MockCardForm
            scenario="success"
            externalError="CARD_DECLINED — כרטיס נדחה על ידי הבנק"
            onToken={(tok) => setLastToken(tok)}
          />
        </div>
      </ComponentEntry>

      {/* ── Variant: processing state ─────────────────────────────────── */}
      <ComponentEntry
        id="mock-card-form-processing"
        name="MockCardForm (isProcessing)"
        path="src/features/checkout/MockCardForm"
        description="isProcessing=true disables all inputs and shows aria-busy on the submit button."
        tokens={[]}
        a11yNotes={['Button has aria-busy=true', 'All inputs have disabled attribute']}
        importSnippet={`<MockCardForm scenario="success" isProcessing onToken={handleToken} />`}
      >
        <div className="max-w-sm rounded-lg border border-neutral-200 bg-white p-4">
          <MockCardForm scenario="success" isProcessing onToken={() => undefined} />
        </div>
      </ComponentEntry>

      {/* ── All scenarios reference table ─────────────────────────────── */}
      <ComponentEntry
        id="mock-card-form-scenarios"
        name="MOCK_SCENARIOS — all 9 values"
        path="src/server/payments/mock/scenarios"
        description="Complete list of MockScenario literals. Cookie md_mock_scenario holds the active one. /dev/payments lets devs switch it."
        tokens={[]}
        a11yNotes={[]}
        importSnippet={`import { MOCK_SCENARIOS } from '@/server/payments/mock/scenarios';\n// type MockScenario = (typeof MOCK_SCENARIOS)[number]`}
      >
        <ul className="flex flex-col gap-1 rounded-lg border border-neutral-200 bg-white p-4">
          {MOCK_SCENARIOS.map((s) => (
            <li key={s} className="font-mono text-sm text-neutral-800">
              <code>mock_tok_{s}</code>
            </li>
          ))}
        </ul>
      </ComponentEntry>

      <ComponentEntry
        id="checkoutshell-layout"
        name="CheckoutShell"
        path="src/components/ui/layout/CheckoutShell"
        description="Checkout page shell with RTL-aware step navigation, back affordance, and stable content slot."
        tokens={['color-surface-page', 'color-surface-glass', 'z-sticky']}
        a11yNotes={[
          'Step navigation is a labelled nav landmark',
          'Current step exposes aria-current=step',
          'Completed steps can be links; upcoming steps stay static',
        ]}
        importSnippet={`import { CheckoutShell } from '@/components/ui/layout/CheckoutShell';`}
      >
        <CheckoutShell
          activeStepId="payment"
          steps={[
            { id: 'cart', label: 'עגלה', href: '/cart' },
            { id: 'details', label: 'פרטים', href: '/cart?step=details' },
            { id: 'payment', label: 'תשלום' },
          ]}
          className="overflow-hidden rounded-lg"
          backHref="/cart?step=details"
          backLabel="חזרה לפרטים"
        >
          <div className="mx-auto flex max-w-lg flex-col gap-3 p-4">
            <p className="text-text-primary text-sm font-semibold">Payment step preview</p>
            <p className="text-text-secondary text-sm">
              The gallery renders the real shell while payment provider forms stay in their own
              demos below.
            </p>
          </div>
        </CheckoutShell>
      </ComponentEntry>
      {/* ── StripePaymentElement ──────────────────────────────────────── */}
      <ComponentEntry
        id="stripe-payment-element"
        name="StripePaymentElement"
        path="src/components/ui/checkout/StripePaymentElement"
        description="React island wrapping Stripe Elements PaymentElement. Loads Stripe asynchronously, renders the hosted card/payment form, calls confirmPayment on submit, and redirects to returnUrlPath."
        tokens={[
          '--color-primary',
          '--color-bg',
          '--color-text',
          '--font-sans',
          '--radius-md',
          '--color-danger-600',
        ]}
        a11yNotes={[
          'Error message rendered in <p role="alert"> — screen readers announce on payment failure',
          'Submit button has aria-busy=true while processing',
          'Button disabled when Stripe not loaded or form submitting',
          'Stripe Elements handles a11y for card inputs internally',
        ]}
        importSnippet={`import StripePaymentElement from '@/components/ui/checkout/StripePaymentElement';\n\n<StripePaymentElement\n  publishableKey="pk_test_..."\n  clientSecret="pi_..._secret_..."\n  purchaseId="uuid"\n  returnUrlPath="/checkout/uuid/complete"\n/>`}
      >
        <div
          className="max-w-sm rounded-lg border border-neutral-200 bg-white p-4"
          role="status"
          aria-live="polite"
        >
          <p className="text-sm text-neutral-500">
            Stripe Elements — requires real publishableKey + clientSecret to render.
          </p>
        </div>
      </ComponentEntry>

      {/* ── CheckoutComplete ──────────────────────────────────────────── */}
      <ComponentEntry
        id="checkout-complete"
        name="CheckoutComplete"
        path="src/components/ui/checkout/CheckoutComplete"
        description="Post-payment polling island. Polls /api/checkout/finalize every 2s up to 30s. Shows Spinner while pending, InlineNotice success when confirmed, ErrorState on failure."
        tokens={[
          '--spacing-40',
          '--color-danger-600',
          '--color-success-50',
          '--color-success-500',
          '--color-success-700',
        ]}
        a11yNotes={[
          'Spinner announces loading state to screen readers via label prop',
          'Success notice uses role="status"',
          'Error uses ErrorState with role="alert"',
          'Error retry button reloads the page',
        ]}
        importSnippet={`import { CheckoutComplete } from '@/components/ui/checkout/CheckoutComplete';\n\n<CheckoutComplete\n  purchaseId="uuid"\n  providerPaymentId="pi_..."\n  initialStatus="succeeded"\n/>`}
      >
        <div className="max-w-sm rounded-lg border border-neutral-200 bg-white p-4">
          <CheckoutComplete
            purchaseId="gallery-purchase"
            providerPaymentId="gallery-payment"
            initialStatus="succeeded"
            demo
          />
        </div>
      </ComponentEntry>
    </SectionShell>
  );
}
