/* ============================================================
   CHANGELOG PAGE — Release notes / 更新说明
   Content is loaded from /changelog.md (public dir) at runtime,
   so updating the notes only requires editing that markdown file.
   ============================================================ */
import BottomNav from "@/components/BottomNav";
import { useDevice } from "@/contexts/DeviceContext";
import { usePageTitleWithConnection } from "@/hooks/usePageTitleWithConnection";
import { resolveLocalePack } from "@/locales/resolveLocale";
import localeZh from "@/locales/data-zh.json";
import { ChevronLeft } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useLocation } from "wouter";
import { Streamdown } from "streamdown";

type HomeLocale = NonNullable<(typeof localeZh)["home"]>;

export default function ChangelogPage() {
  const [, setLocation] = useLocation();
  const { deviceState } = useDevice();

  const homeText = useMemo((): HomeLocale => {
    const pack = resolveLocalePack(deviceState?.language);
    return (pack.home ?? {}) as HomeLocale;
  }, [deviceState?.language]);

  const pageTitle = usePageTitleWithConnection(homeText.changelog ?? "更新说明");

  const [content, setContent] = useState<string | null>(null);
  const [failed, setFailed] = useState(false);

  useEffect(() => {
    let cancelled = false;
    fetch(`${import.meta.env.BASE_URL}changelog.md`)
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.text();
      })
      .then((text) => {
        if (!cancelled) setContent(text);
      })
      .catch(() => {
        if (!cancelled) setFailed(true);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  return (
    <div className="min-h-[100dvh] bg-black flex flex-col pb-[calc(env(safe-area-inset-bottom,0px)+56px)]">
      <div className="page-header">
        <button
          type="button"
          onClick={() => setLocation("/")}
          className="mr-4 text-white/60 active:text-white transition-colors"
          aria-label="Back"
        >
          <ChevronLeft size={24} />
        </button>
        <h1 className="flex-1 text-center text-[17px] font-semibold text-white">{pageTitle}</h1>
        <div className="w-8" />
      </div>

      <div className="flex-1 px-4 pt-4 overflow-y-auto">
        <div
          className="ios-list-group p-4"
          style={{
            background: "linear-gradient(180deg, rgba(34,36,40,0.95) 0%, rgba(24,26,30,0.95) 100%)",
            border: "1px solid rgba(255,255,255,0.1)",
            borderRadius: 14,
            boxShadow: "0 8px 32px rgba(0,0,0,0.35)",
          }}
        >
          {failed ? (
            <p className="text-[14px] text-white/45 text-center py-10">{homeText.changelogLoadFailed ?? "加载失败，请稍后重试"}</p>
          ) : content ? (
            <div className="markdown-body text-[14px] leading-relaxed text-white/85 [&_h1]:text-[18px] [&_h1]:font-bold [&_h1]:text-white [&_h1]:mb-3 [&_h2]:text-[16px] [&_h2]:font-semibold [&_h2]:text-[#00FFF6] [&_h2]:mt-5 [&_h2]:mb-2 [&_h3]:text-[14px] [&_h3]:font-semibold [&_h3]:text-white/90 [&_h3]:mt-3 [&_h3]:mb-1.5 [&_li]:mb-1 [&_blockquote]:border-l-2 [&_blockquote]:border-white/20 [&_blockquote]:pl-3 [&_blockquote]:text-white/55 [&_hr]:border-white/10 [&_hr]:my-4 [&_code]:bg-white/10 [&_code]:rounded [&_code]:px-1 [&_code]:text-[13px]">
              <Streamdown>{content}</Streamdown>
            </div>
          ) : (
            <div className="flex justify-center py-10">
              <div className="w-6 h-6 rounded-full border-2 border-white/20 border-t-[#00FFF6] animate-spin" />
            </div>
          )}
        </div>
      </div>

      <BottomNav />
    </div>
  );
}
