"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { readProgress, type ReadingProgress } from "@/lib/progress";

type ChapterLite = {
  number: number;
  title: string;
};

type Props = {
  mangaSlug: string;
  chapters: ChapterLite[];
};

export { readProgress, writeProgress } from "@/lib/progress";
export type { ReadingProgress } from "@/lib/progress";

export function ReadingProgressButton({ mangaSlug, chapters }: Props) {
  const [progress, setProgress] = useState<ReadingProgress | null>(null);

  useEffect(() => {
    setProgress(readProgress(mangaSlug));
  }, [mangaSlug]);

  if (chapters.length === 0) return null;
  const first = chapters[0];
  const resumeChapter =
    progress !== null
      ? chapters.find((c) => c.number === progress.chapter)
      : null;
  const target = resumeChapter ?? first;
  const href = resumeChapter
    ? `/manga/${mangaSlug}/${target.number}?resume=1`
    : `/manga/${mangaSlug}/${target.number}`;

  return (
    <Link
      href={href}
      scroll={false}
      className="flex items-center justify-center gap-3 w-full py-3 mb-6 px-4 text-sm font-semibold bg-accent hover:bg-accent-hover text-white rounded-xl transition-colors active:scale-[0.98]"
    >
      {resumeChapter ? (
        <>
          <span>继续阅读</span>
          <span className="opacity-50">·</span>
          <span className="truncate">
            #{resumeChapter.number} {resumeChapter.title}
          </span>
        </>
      ) : (
        "开始阅读"
      )}
    </Link>
  );
}
