import React from "react";
import { Head, usePage } from "@inertiajs/react";
import MarketingLayout from "@/layouts/marketing/MarketingLayout";
import type { CheckoutPackage } from "./checkout/types";
import { CheckoutWizard } from "./checkout/CheckoutWizard";

interface PurchaseWizardPageProps {
  package: CheckoutPackage;
  packageOptions: CheckoutPackage[];
  stripePublishableKey: string;
  privacyHtml: string;
}

export default function PurchaseWizardPage({
  package: initialPackage,
  packageOptions,
  stripePublishableKey,
  privacyHtml,
}: PurchaseWizardPageProps) {
  const page = usePage<{ auth?: { user?: { id: number; email: string; name?: string } | null } }>();
  const currentUser = page.props.auth?.user ?? null;

  const dedupedOptions = React.useMemo(() => {
    const ids = new Set<number>();
    const list = [initialPackage, ...packageOptions];
    return list.filter((pkg) => {
      if (ids.has(pkg.id)) {
        return false;
      }
      ids.add(pkg.id);
      return true;
    });
  }, [initialPackage, packageOptions]);

  return (
    <MarketingLayout title="Checkout Wizard">
      <Head title="Checkout Wizard" />
      <div className="min-h-screen bg-muted/20 py-12">
        <div className="mx-auto w-full max-w-4xl px-4">
          <CheckoutWizard
            initialPackage={initialPackage}
            packageOptions={dedupedOptions}
            stripePublishableKey={stripePublishableKey}
            privacyHtml={privacyHtml}
            initialAuthUser={currentUser ? { id: currentUser.id, email: currentUser.email ?? '', name: currentUser.name ?? undefined } : null}
          />
        </div>
      </div>
    </MarketingLayout>
  );
}
