import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { Navbar } from "@/components/layout/navbar";
import { Footer } from "@/components/layout/footer";
import {
  ArrowLeft,
  ArrowRight,
  ChevronLeft,
  ChevronRight,
  Lightbulb,
  LifeBuoy,
} from "lucide-react";
import {
  GUIDE_FEATURES,
  getFeatureBySlug,
  TIER_LABELS,
  type GuideFeature,
} from "../guide-data";
import { Wireframe } from "../wireframes";

const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://meezi.ir";

export function generateStaticParams() {
  return GUIDE_FEATURES.map((f) => ({ slug: f.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}): Promise<Metadata> {
  const { locale, slug } = await params;
  const feature = getFeatureBySlug(slug);
  if (!feature) return {};
  const c = locale === "fa" ? feature.fa : feature.en;
  return {
    title: c.title,
    description: c.tagline,
    alternates: {
      canonical: `${BASE_URL}/${locale}/docs/${slug}`,
      languages: {
        fa: `${BASE_URL}/fa/docs/${slug}`,
        en: `${BASE_URL}/en/docs/${slug}`,
      },
    },
    openGraph: {
      title: c.title,
      description: c.tagline,
      url: `${BASE_URL}/${locale}/docs/${slug}`,
    },
  };
}

function siblings(feature: GuideFeature): { prev?: GuideFeature; next?: GuideFeature } {
  const i = GUIDE_FEATURES.findIndex((f) => f.slug === feature.slug);
  return {
    prev: i > 0 ? GUIDE_FEATURES[i - 1] : undefined,
    next: i < GUIDE_FEATURES.length - 1 ? GUIDE_FEATURES[i + 1] : undefined,
  };
}

const COPY = {
  fa: {
    backToDocs: "راهنمای میزی",
    howTo: "گام‌به‌گام",
    tips: "نکته‌ها",
    prev: "قبلی",
    next: "بعدی",
    supportTitle: "نیاز به کمک؟",
    supportDesc: "تیم پشتیبانی ما آماده است. از طریق داشبورد یا ایمیل با ما در ارتباط باش.",
    supportBtn: "تماس با پشتیبانی",
    demoBtn: "درخواست آموزش رایگان",
  },
  en: {
    backToDocs: "Help Center",
    howTo: "Step by step",
    tips: "Tips",
    prev: "Previous",
    next: "Next",
    supportTitle: "Need help?",
    supportDesc: "Our support team is ready. Reach us through the dashboard or by email.",
    supportBtn: "Contact Support",
    demoBtn: "Request free training",
  },
};

export default async function FeatureGuidePage({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const feature = getFeatureBySlug(slug);
  if (!feature) notFound();

  const isEn = locale === "en";
  const base = `/${locale}`;
  const c = isEn ? feature.en : feature.fa;
  const t = isEn ? COPY.en : COPY.fa;
  const Icon = feature.icon;
  const Arrow = isEn ? ArrowRight : ArrowLeft;
  // Chevron pointing "back toward docs" — start-aligned, mirrors in RTL.
  const BackChevron = isEn ? ChevronLeft : ChevronRight;
  const { prev, next } = siblings(feature);

  return (
    <>
      <Navbar />
      <main className="pt-16">
        {/* Hero */}
        <div className="bg-gradient-to-br from-brand-900 to-brand-700 pb-16 pt-14">
          <div className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8">
            {/* Breadcrumb back to docs */}
            <a
              href={`${base}/docs`}
              className="inline-flex items-center gap-1.5 text-sm font-medium text-white/70 transition-colors hover:text-white"
            >
              <BackChevron className="h-4 w-4" />
              {t.backToDocs}
            </a>

            <div className="mt-6 flex items-start gap-4">
              <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-white/10">
                <Icon className="h-7 w-7 text-white" />
              </div>
              <div className="flex-1">
                <div className="flex flex-wrap items-center gap-3">
                  <h1 className="text-3xl font-extrabold text-white sm:text-4xl">{c.title}</h1>
                  {feature.tier && feature.tier !== "free" && (
                    <span className="rounded-full border border-white/20 bg-white/10 px-3 py-1 text-xs font-semibold text-white/80">
                      {isEn ? TIER_LABELS[feature.tier].en : TIER_LABELS[feature.tier].fa}
                    </span>
                  )}
                </div>
                <p className="mt-3 max-w-2xl text-lg leading-relaxed text-white/60">{c.tagline}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Two-column: wireframe + how-to */}
        <div className="mx-auto max-w-5xl px-4 py-16 sm:px-6 lg:px-8">
          <div className="grid items-start gap-10 lg:grid-cols-2">
            {/* Wireframe (sticky on desktop) */}
            <div className="lg:sticky lg:top-24">
              <Wireframe variant={feature.wireframe} />
            </div>

            {/* Numbered how-to steps */}
            <div>
              <h2 className="mb-6 text-2xl font-extrabold text-gray-900">{t.howTo}</h2>
              <ol className="space-y-5">
                {c.steps.map((step, i) => (
                  <li key={i} className="flex gap-4">
                    <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-brand-700 text-sm font-extrabold text-white">
                      {isEn ? i + 1 : toFa(i + 1)}
                    </span>
                    <p className="pt-1 leading-relaxed text-gray-600">{step}</p>
                  </li>
                ))}
              </ol>
            </div>
          </div>

          {/* Tips callout */}
          {c.tips && c.tips.length > 0 && (
            <div className="mt-12 rounded-2xl border border-brand-100 bg-brand-50 p-6">
              <div className="mb-3 flex items-center gap-2">
                <Lightbulb className="h-5 w-5 text-brand-700" />
                <h3 className="text-base font-bold text-gray-900">{t.tips}</h3>
              </div>
              <ul className="space-y-2">
                {c.tips.map((tip, i) => (
                  <li key={i} className="flex gap-2.5 text-sm leading-relaxed text-gray-600">
                    <span className="mt-2 h-1.5 w-1.5 shrink-0 rounded-full bg-brand-500" />
                    {tip}
                  </li>
                ))}
              </ul>
            </div>
          )}

          {/* Prev / Next */}
          <div className="mt-12 grid gap-4 sm:grid-cols-2">
            {prev ? (
              <a
                href={`${base}/docs/${prev.slug}`}
                className="group flex items-center gap-3 rounded-2xl border border-gray-100 bg-white p-5 shadow-sm transition-all hover:border-brand-200 hover:shadow-md"
              >
                <BackChevron className="h-5 w-5 text-gray-400 transition-colors group-hover:text-brand-700" />
                <div>
                  <div className="text-xs text-gray-400">{t.prev}</div>
                  <div className="font-semibold text-gray-900">{isEn ? prev.en.title : prev.fa.title}</div>
                </div>
              </a>
            ) : (
              <div className="hidden sm:block" />
            )}
            {next && (
              <a
                href={`${base}/docs/${next.slug}`}
                className="group flex items-center justify-end gap-3 rounded-2xl border border-gray-100 bg-white p-5 text-end shadow-sm transition-all hover:border-brand-200 hover:shadow-md"
              >
                <div>
                  <div className="text-xs text-gray-400">{t.next}</div>
                  <div className="font-semibold text-gray-900">{isEn ? next.en.title : next.fa.title}</div>
                </div>
                <Arrow className="h-5 w-5 text-gray-400 transition-colors group-hover:text-brand-700" />
              </a>
            )}
          </div>

          {/* Support CTA (copied from docs index) */}
          <section className="mt-16 rounded-2xl bg-gradient-to-br from-brand-900 to-brand-700 p-10">
            <div className="flex flex-col items-center gap-6 text-center sm:flex-row sm:text-start">
              <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-white/10">
                <LifeBuoy className="h-7 w-7 text-white" />
              </div>
              <div className="flex-1">
                <h2 className="mb-1 text-xl font-bold text-white">{t.supportTitle}</h2>
                <p className="text-white/60">{t.supportDesc}</p>
              </div>
              <div className="flex flex-wrap gap-3">
                <a
                  href={`${base}/contact`}
                  className="inline-flex items-center gap-2 rounded-xl bg-white px-5 py-2.5 text-sm font-semibold text-brand-700 transition-colors hover:bg-brand-50"
                >
                  {t.supportBtn}
                  <Arrow className="h-4 w-4" />
                </a>
                <a
                  href={`${base}/demo`}
                  className="inline-flex items-center gap-2 rounded-xl border border-white/20 px-5 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-white/10"
                >
                  {t.demoBtn}
                </a>
              </div>
            </div>
          </section>
        </div>
      </main>
      <Footer />
    </>
  );
}

/** Western digits → Persian digits for step numbers. */
function toFa(n: number): string {
  const map = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
  return String(n)
    .split("")
    .map((d) => map[Number(d)] ?? d)
    .join("");
}
