"use client";

import { useEffect, useState, use } from "react";
import { ArrowLeft } from "lucide-react";
import { useRouter } from "next/navigation";

interface Notice {
  OBJID: string; TITLE: string; BODY: string | null;
  IMAGE_URL: string | null; URL: string | null; REGDATE: string;
}

export default function NoticeViewPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [notice, setNotice] = useState<Notice | null>(null);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState("");

  useEffect(() => {
    fetch(`/api/m/notices/${id}`)
      .then((r) => r.json())
      .then((j) => {
        if (j.success) setNotice(j.notice);
        else setErr(j.message || "공지를 찾을 수 없습니다.");
      })
      .catch(() => setErr("불러오기 실패"))
      .finally(() => setLoading(false));
  }, [id]);

  const back = () => {
    if (typeof window !== "undefined" && window.history.length > 1) router.back();
    else router.push("/m/orders/new");
  };

  if (loading) return <div className="text-center py-12 text-slate-400">불러오는 중…</div>;
  if (err || !notice) return (
    <div className="text-center py-12">
      <div className="text-slate-400 mb-3">{err || "공지를 찾을 수 없습니다."}</div>
      <button onClick={back} className="inline-flex items-center gap-1 h-9 px-3 rounded-lg border border-slate-300 bg-white text-sm font-semibold">
        <ArrowLeft size={14} /> 돌아가기
      </button>
    </div>
  );

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <button onClick={back} className="inline-flex items-center gap-1 text-xs text-slate-500 hover:text-emerald-700">
        <ArrowLeft size={14} /> 돌아가기
      </button>

      <article className="bg-white border border-slate-200 rounded-xl overflow-hidden">
        {notice.IMAGE_URL && (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={notice.IMAGE_URL} alt={notice.TITLE} className="w-full object-contain bg-slate-50" />
        )}
        <div className="p-4 sm:p-6 space-y-3">
          <h1 className="text-xl sm:text-2xl font-bold text-slate-900">{notice.TITLE}</h1>
          <div className="text-[11px] text-slate-400">{notice.REGDATE}</div>
          {notice.BODY && (
            <div className="text-sm sm:text-base text-slate-700 whitespace-pre-wrap leading-relaxed pt-2 border-t border-slate-100">
              {notice.BODY}
            </div>
          )}
          {notice.URL && (
            <a href={notice.URL} target="_blank" rel="noreferrer"
               className="inline-flex items-center gap-1 text-sm font-bold text-emerald-700 hover:underline pt-2 border-t border-slate-100">
              연결 페이지 열기 →
            </a>
          )}
        </div>
      </article>
    </div>
  );
}
