"use client";

import Link from "next/link";
import { Rocket } from "lucide-react";
import { Button, Card, CardContent, Badge } from "@/components/ds";
import { useExperienceCapabilities } from "@/modules/experience/hooks/useExperienceCapabilities";
import { ExperiencePageLoader, ExperiencePageError } from "@/modules/experience/pages/shared";
import { ExperienceBreadcrumbs } from "@/modules/experience/components/ExperienceBreadcrumbs";
import type { PhaseGateConfig } from "@/modules/experience/types";

/** Phase gate — builder pages bypass gate per ADR-002 (Experience FE owns builder UX). */
export function ExperiencePhaseGate({
  config,
  children,
  bypass = false,
}: {
  config: PhaseGateConfig;
  children?: React.ReactNode;
  bypass?: boolean;
}) {
  const caps = useExperienceCapabilities();

  if (caps.isLoading) return <ExperiencePageLoader label="بررسی قابلیت‌ها…" />;
  if (caps.error) return <ExperiencePageError error={caps.error} onRetry={() => caps.refetch()} />;

  const enabled = bypass || caps.data?.features?.[config.feature] === true;
  if (enabled && children) return <>{children}</>;

  return (
    <div className="space-y-4">
      <ExperienceBreadcrumbs current={config.title} />
      <Card>
        <CardContent className="flex flex-col items-center gap-4 p-8 text-center">
          <div className="rounded-full bg-[var(--experience-accent-soft)] p-4">
            <Rocket className="h-8 w-8 text-[var(--experience-accent)]" />
          </div>
          <div>
            <h2 className="text-xl font-bold text-secondary">{config.title}</h2>
            <p className="mt-2 max-w-lg text-sm text-[var(--muted)]">{config.description}</p>
          </div>
          <Badge tone="info">فاز {config.phase}</Badge>
          <div className="flex flex-wrap gap-2">
            <Link href="/experience/capabilities">
              <Button variant="outline">مشاهده قابلیت‌ها</Button>
            </Link>
            <Link href="/experience">
              <Button>بازگشت به داشبورد</Button>
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

export function createExperiencePhasePage(config: PhaseGateConfig, bypass = false) {
  return function ExperiencePhasePage() {
    return <ExperiencePhaseGate config={config} bypass={bypass} />;
  };
}
