"use client";

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Loader2 } from "lucide-react";

import { getPublicSettings } from "@/api";
import { PlayerPanel } from "@/components/layout/player-panel";
import { resolvePlayRulesHtml } from "@/lib/play-rules-html";
import { Card, CardContent } from "@/components/ui/card";

export function PlayRulesScreen() {
  const { t, i18n } = useTranslation("player");
  const [htmlContent, setHtmlContent] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadRules() {
      try {
        const res = await getPublicSettings("frontend");
        const html = resolvePlayRulesHtml(res.items, i18n.language);
        if (html) {
          setHtmlContent(html);
        } else {
          setHtmlContent(`<div style="text-align:center;padding:2rem;color:#64748b;">${t("rules.empty", { defaultValue: "暂无玩法规则说明" })}</div>`);
        }
      } catch {
        setHtmlContent(`<div style="text-align:center;padding:2rem;color:#64748b;">${t("rules.loadFailed", { defaultValue: "规则加载失败" })}</div>`);
      } finally {
        setLoading(false);
      }
    }
    void loadRules();
  }, [i18n.language, t]);

  return (
    <PlayerPanel
      title={t("rules.title")}
      backHref="/hall"
      className="bg-[#f7f9fd]"
    >
      <div className="space-y-3">
        <Card className="border-[#dbe7fb] bg-white shadow-sm overflow-hidden min-h-[300px]">
          <CardContent className="p-4">
            {loading ? (
              <div className="flex h-[200px] items-center justify-center">
                <Loader2 className="size-6 animate-spin text-slate-400" />
              </div>
            ) : (
              <div
                className="prose prose-sm max-w-none text-slate-700"
                dangerouslySetInnerHTML={{ __html: htmlContent || "" }}
              />
            )}
          </CardContent>
        </Card>
      </div>
    </PlayerPanel>
  );
}
