"use client";

import { useState, useEffect } from "react";
import { getNote, setNote } from "@/app/lib/learning";

type Props = { moduleIndex: number; lessonIndex: number };

export function LessonNotes({ moduleIndex, lessonIndex }: Props) {
  const [text, setText] = useState("");
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    setText(getNote(moduleIndex, lessonIndex));
  }, [moduleIndex, lessonIndex]);

  const handleSave = () => {
    setNote(moduleIndex, lessonIndex, text);
    setSaved(true);
    setTimeout(() => setSaved(false), 1500);
  };

  return (
    <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 sm:p-6">
      <h3 className="mb-3 flex items-center gap-2 font-semibold">
        <span>📝</span> 学习笔记
      </h3>
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        onBlur={handleSave}
        placeholder="记录你的学习心得..."
        className="mb-3 w-full min-h-[100px] rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-[var(--accent)]"
        rows={4}
      />
      <p className="text-xs text-[var(--muted-foreground)]">
        {saved ? "✓ 已保存" : "失焦自动保存"}
      </p>
    </div>
  );
}
