"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { ArrowRight, PlayCircle, Clock, Tag, BookOpen, ChevronLeft } from "lucide-react";

/**
 * يحوّل رابط يوتيوب/فيميو إلى رابط تضمين.
 * يرجع null لأي رابط غير مدعوم بدل تضمينه كما هو.
 */
function toEmbedUrl(url) {
  if (!url) return null;
  try {
    const u = new URL(url);
    const host = u.hostname.replace(/^www\./, "");

    if (host === "youtu.be") {
      const id = u.pathname.slice(1);
      return id ? `https://www.youtube.com/embed/${id}` : null;
    }
    if (host === "youtube.com" || host === "m.youtube.com") {
      if (u.pathname === "/watch") {
        const id = u.searchParams.get("v");
        return id ? `https://www.youtube.com/embed/${id}` : null;
      }
      if (u.pathname.startsWith("/embed/")) return `https://www.youtube.com${u.pathname}`;
      if (u.pathname.startsWith("/shorts/")) {
        const id = u.pathname.split("/")[2];
        return id ? `https://www.youtube.com/embed/${id}` : null;
      }
    }
    if (host === "vimeo.com") {
      const id = u.pathname.split("/").filter(Boolean)[0];
      return id ? `https://player.vimeo.com/video/${id}` : null;
    }
  } catch {}
  return null;
}

export default function KnowledgeArticlePage() {
  const params = useParams();
  const slug = params?.slug;
  const [data, setData] = useState({ categories: [], articles: [] });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/knowledge-base")
      .then((r) => r.json())
      .then((d) => setData({ categories: d.categories || [], articles: d.articles || [] }))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const article = useMemo(
    () => data.articles.find((a) => a.slug === slug) || null,
    [data, slug]
  );

  const category = useMemo(
    () => data.categories.find((c) => c.id === article?.categoryId) || null,
    [data, article]
  );

  const related = useMemo(() => {
    if (!article) return [];
    return data.articles
      .filter((a) => a.categoryId === article.categoryId && a.slug !== article.slug)
      .slice(0, 4);
  }, [data, article]);

  // تسجيل مشاهدة مرة واحدة لكل فتح
  useEffect(() => {
    if (!article) return;
    fetch("/api/knowledge-base", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ slug: article.slug }),
    }).catch(() => {});
  }, [article?.slug]);

  const embed = toEmbedUrl(article?.videoUrl);

  if (loading) {
    return (
      <div dir="rtl" className="min-h-screen bg-slate-50 flex items-center justify-center">
        <div className="text-slate-400 text-sm">جاري التحميل…</div>
      </div>
    );
  }

  if (!article) {
    return (
      <div dir="rtl" className="min-h-screen bg-slate-50 flex items-center justify-center px-4">
        <div className="text-center">
          <BookOpen className="w-12 h-12 text-slate-300 mx-auto mb-4" />
          <h1 className="text-xl font-bold text-slate-800 mb-2">المقال غير موجود</h1>
          <p className="text-slate-500 text-sm mb-6">ربما تم نقله أو حذفه.</p>
          <Link
            href="/knowledge-base"
            className="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-bold px-5 py-2.5 rounded-lg"
          >
            <ArrowRight className="w-4 h-4" />
            العودة لقاعدة المعرفة
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div dir="rtl" className="min-h-screen bg-slate-50">
      {/* ===== المسار ===== */}
      <div className="bg-white border-b border-slate-200">
        <div className="max-w-4xl mx-auto px-4 py-4 flex items-center gap-2 text-xs text-slate-500 flex-wrap">
          <Link href="/knowledge-base" className="hover:text-blue-600 font-bold">
            قاعدة المعرفة
          </Link>
          {category && (
            <>
              <ChevronLeft className="w-3.5 h-3.5" />
              <span>{category.name}</span>
            </>
          )}
        </div>
      </div>

      <article className="max-w-4xl mx-auto px-4 py-10">
        <header className="mb-8">
          <h1 className="text-2xl sm:text-3xl font-bold text-slate-900 leading-snug">
            {article.title}
          </h1>
          {article.excerpt && (
            <p className="text-slate-600 mt-3 leading-relaxed">{article.excerpt}</p>
          )}

          <div className="flex items-center gap-4 mt-5 text-xs text-slate-400 flex-wrap">
            {article.updatedAt && (
              <span className="inline-flex items-center gap-1.5">
                <Clock className="w-3.5 h-3.5" />
                آخر تحديث{" "}
                {new Date(article.updatedAt).toLocaleDateString("ar-EG", {
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </span>
            )}
            {embed && (
              <span className="inline-flex items-center gap-1.5 text-rose-600 font-bold">
                <PlayCircle className="w-3.5 h-3.5" />
                يتضمن فيديو
              </span>
            )}
          </div>
        </header>

        {/* ===== الفيديو ===== */}
        {embed && (
          <div className="mb-8 rounded-xl overflow-hidden border border-slate-200 bg-black aspect-video">
            <iframe
              src={embed}
              title={article.title}
              className="w-full h-full"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              loading="lazy"
            />
          </div>
        )}

        {/* ===== الشرح المكتوب ===== */}
        <div
          className="kb-body bg-white border border-slate-200 rounded-xl p-6 sm:p-8"
          dangerouslySetInnerHTML={{ __html: article.body }}
        />

        {/* ===== الوسوم ===== */}
        {article.tags?.length > 0 && (
          <div className="flex items-center gap-2 flex-wrap mt-6">
            <Tag className="w-4 h-4 text-slate-400" />
            {article.tags.map((t) => (
              <span
                key={t}
                className="text-[11px] bg-slate-100 text-slate-600 px-2.5 py-1 rounded-full"
              >
                {t}
              </span>
            ))}
          </div>
        )}

        {/* ===== مقالات ذات صلة ===== */}
        {related.length > 0 && (
          <section className="mt-12">
            <h2 className="text-lg font-bold text-slate-800 mb-4">مواضيع ذات صلة</h2>
            <div className="grid gap-3 sm:grid-cols-2">
              {related.map((a) => (
                <Link
                  key={a.id}
                  href={`/knowledge-base/${a.slug}`}
                  className="bg-white border border-slate-200 rounded-xl p-4 hover:border-blue-400 transition"
                >
                  <h3 className="font-bold text-slate-800 text-sm">{a.title}</h3>
                  <p className="text-xs text-slate-500 mt-1 line-clamp-2">{a.excerpt}</p>
                </Link>
              ))}
            </div>
          </section>
        )}

        {/* ===== لم تجد ما تبحث عنه ===== */}
        <section className="mt-12 bg-[#0b1f3f] text-white rounded-xl p-6 sm:p-8 text-center">
          <h2 className="text-lg font-bold mb-2">لم تجد ما تبحث عنه؟</h2>
          <p className="text-white/70 text-sm mb-5">
            فريق الدعم الفني متاح على مدار الساعة لمساعدتك.
          </p>
          <Link
            href="/contact"
            className="inline-block bg-white text-[#0b1f3f] text-sm font-bold px-6 py-2.5 rounded-lg hover:bg-white/90"
          >
            تواصل مع الدعم
          </Link>
        </section>
      </article>

      {/* تنسيق النص الغني — الوسوم تأتي من المحرر لا من JSX */}
      <style jsx global>{`
        .kb-body {
          line-height: 1.95;
          color: #334155;
        }
        .kb-body h2 {
          font-size: 1.25rem;
          font-weight: 700;
          color: #0f172a;
          margin: 1.75rem 0 0.75rem;
        }
        .kb-body h2:first-child {
          margin-top: 0;
        }
        .kb-body h3 {
          font-size: 1.05rem;
          font-weight: 700;
          color: #1e293b;
          margin: 1.5rem 0 0.6rem;
        }
        .kb-body p {
          margin: 0 0 1rem;
        }
        .kb-body ul,
        .kb-body ol {
          margin: 0 0 1rem;
          padding-inline-start: 1.5rem;
        }
        .kb-body ul {
          list-style: disc;
        }
        .kb-body ol {
          list-style: decimal;
        }
        .kb-body li {
          margin-bottom: 0.4rem;
        }
        .kb-body code {
          background: #f1f5f9;
          color: #0f172a;
          padding: 0.15rem 0.4rem;
          border-radius: 0.3rem;
          font-size: 0.875em;
          direction: ltr;
          display: inline-block;
        }
        .kb-body strong {
          color: #0f172a;
          font-weight: 700;
        }
        .kb-body a {
          color: #2563eb;
          text-decoration: underline;
        }
        .kb-body img {
          max-width: 100%;
          height: auto;
          border-radius: 0.5rem;
          margin: 1rem 0;
        }
      `}</style>
    </div>
  );
}
