"use client";

import { useState, useEffect } from "react";
import { getRating, setRating } from "@/app/lib/learning";

export function RatingSection() {
  const [stars, setStars] = useState(0);
  const [comment, setComment] = useState("");
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    const r = getRating();
    if (r) {
      setStars(r.stars);
      setComment(r.comment);
      setSubmitted(true);
    }
  }, []);

  const handleSubmit = () => {
    setRating(stars, comment);
    setSubmitted(true);
  };

  return (
    <section className="border-t border-[var(--border)] py-12 sm:py-16">
      <div className="mx-auto max-w-2xl px-4 text-center sm:px-6">
        <h2 className="mb-2 text-xl font-bold sm:text-2xl">课程评价</h2>
        <p className="mb-6 text-sm text-[var(--muted-foreground)]">
          你的反馈对我们很重要
        </p>
        {submitted ? (
          <p className="text-[var(--muted-foreground)]">感谢你的评价 ✓</p>
        ) : (
          <>
            <div className="mb-4 flex justify-center gap-1">
              {[1, 2, 3, 4, 5].map((n) => (
                <button
                  key={n}
                  type="button"
                  onClick={() => setStars(n)}
                  className="text-2xl transition hover:scale-110"
                >
                  {n <= stars ? "⭐" : "☆"}
                </button>
              ))}
            </div>
            <textarea
              value={comment}
              onChange={(e) => setComment(e.target.value)}
              placeholder="选填：一句话评价"
              className="mb-4 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-[var(--accent)]"
              rows={2}
            />
            <button
              type="button"
              onClick={handleSubmit}
              className="rounded-full bg-[var(--accent)] px-6 py-2 text-sm font-medium text-[var(--accent-foreground)] hover:opacity-90"
            >
              提交评价
            </button>
          </>
        )}
      </div>
    </section>
  );
}
