"use client";

import { useState, useEffect } from "react";
import { Link } from "@/i18n/navigation";
import { useTranslation } from "@/i18n/navigation";
import { CTA_CONFIG } from "@/config/course";
import { isPaid } from "@/app/lib/course-payment";

export function CTASection() {
  const { t } = useTranslation("community");
  const [paid, setPaid] = useState(false);
  const [toast, setToast] = useState(false);
  useEffect(() => {
    setPaid(isPaid());
    const onPayUpdate = () => setPaid(isPaid());
    window.addEventListener("pay:updated", onPayUpdate);
    return () => window.removeEventListener("pay:updated", onPayUpdate);
  }, []);

  return (
    <section className="border-t border-[var(--border)] py-16 sm:py-20 md:py-24">
      <div className="mx-auto max-w-3xl px-4 text-center sm:px-6">
        <h2 className="mb-4 text-xl font-bold sm:text-2xl md:text-3xl">
          {CTA_CONFIG.title}
        </h2>
        <p className="mb-6 text-[var(--muted-foreground)] sm:mb-8">
          {CTA_CONFIG.subtitle}
        </p>
        <div className="mb-8 flex flex-wrap justify-center gap-4 text-sm text-[var(--muted-foreground)] sm:mb-10 sm:gap-6">
          {CTA_CONFIG.badges.map((b, i) => (
            <span
              key={b}
              className="animate-float-badge rounded-full border border-[var(--border)] bg-[var(--card)] px-4 py-2"
              style={{ animationDelay: `${i * 0.2}s` }}
            >
              {b}
            </span>
          ))}
        </div>
        {paid ? (
          <Link
            href="/course/0/0"
            className="inline-flex items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] shadow-lg shadow-[var(--accent)]/25 transition-all duration-300 hover:scale-105 hover:opacity-95 hover:shadow-xl hover:shadow-[var(--accent)]/30 sm:px-10"
          >
            开始学习 →
          </Link>
        ) : (
          <button
            type="button"
            onClick={() => {
              setToast(true);
              setTimeout(() => setToast(false), 2000);
            }}
            className="inline-flex cursor-not-allowed items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] opacity-90 shadow-lg shadow-[var(--accent)]/25 transition hover:opacity-100 sm:px-10"
          >
            立即加入 →
          </button>
        )}
      </div>
      {toast && (
        <div
          className="fixed bottom-8 left-1/2 z-50 -translate-x-1/2 rounded-lg bg-slate-800 px-6 py-3 text-sm font-medium text-white shadow-lg dark:bg-slate-700"
          role="alert"
        >
          {t("updating")}
        </div>
      )}
    </section>
  );
}
