"use client";

import { useEffect, useState } from "react";
import { AlertTriangle } from "lucide-react";
import { TopBar } from "@/components/ui/TopBar";
import { Skeleton } from "@/components/ui/Skeleton";
import { fetchCmsPage, LegalContent } from "@/lib/data/cms";
import { useTranslation } from "@/lib/i18n/LanguageProvider";

/**
 * Shared renderer for Terms of Service and Privacy Policy — both are the
 * same shape (a draft-notice banner, a last-updated line, a list of
 * title+body sections), both admin-editable via cms_pages, so one
 * component handles both instead of duplicating the layout twice.
 */
export function LegalPageContent({
  cmsKey,
  title,
}: {
  cmsKey: "terms" | "privacy";
  title: string;
}) {
  const { language } = useTranslation();
  const [content, setContent] = useState<LegalContent | null>(null);

  useEffect(() => {
    let active = true;
    setContent(null);
    fetchCmsPage<LegalContent>(cmsKey, language).then(
      (result) => active && setContent(result)
    );
    return () => {
      active = false;
    };
  }, [cmsKey, language]);

  return (
    <div className="flex flex-1 flex-col">
      <TopBar title={title} />

      <div className="flex flex-1 flex-col gap-5 px-4 pb-8 pt-4">
        {!content ? (
          <>
            <Skeleton className="h-16 w-full !rounded-3xl" />
            <Skeleton className="h-24 w-full" />
            <Skeleton className="h-24 w-full" />
          </>
        ) : (
          <>
            {content.notice && (
              <div className="flex items-start gap-3 rounded-3xl border border-dashed border-gold/40 bg-gold/10 px-4 py-3.5">
                <AlertTriangle size={18} className="mt-0.5 shrink-0 text-gold-dim dark:text-gold-bright" />
                <p className="text-xs leading-relaxed text-muted">{content.notice}</p>
              </div>
            )}

            {content.lastUpdated && <p className="text-xs text-muted">{content.lastUpdated}</p>}

            <div className="flex flex-col gap-5">
              {content.sections.map((s) => (
                <div key={s.title}>
                  <h2 className="mb-1.5 text-sm font-semibold">{s.title}</h2>
                  <p className="text-sm leading-relaxed text-muted">{s.body}</p>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </div>
  );
}
