import Link from "next/link";
import Image from "next/image";
import { listPosts } from "@/lib/cms";
import { PreviewBar } from "../_bar";

export const metadata = { title: "Mockup E · Conversational AI · Preview" };
export const dynamic = "force-dynamic";

const CAT_IDS = { tinNong: 148, phanTich: 36, crypto: 37, vang: 252, chungKhoan: 40 };

/**
 * MOCKUP E — Conversational AI-First.
 * Perplexity Finance × ChatGPT × Arc Browser. Homepage is a conversation,
 * not a publication. Centerpiece is a giant prompt box. AI generates a daily
 * briefing in chat-stream form with cited sources. Articles arrive as result
 * cards underneath. No traditional nav, no hero photo, no grid of stories.
 */
export default async function MockupEPage() {
  const [
    { posts: feat },
    { posts: latest },
    { posts: phanTich },
    { posts: tinNong },
    { posts: crypto },
  ] = await Promise.all([
    listPosts({ perPage: 1, featured: true, orderBy: "date", order: "desc" }),
    listPosts({ perPage: 8, orderBy: "date", order: "desc" }),
    listPosts({ perPage: 4, categories: [CAT_IDS.phanTich] }),
    listPosts({ perPage: 4, categories: [CAT_IDS.tinNong] }),
    listPosts({ perPage: 4, categories: [CAT_IDS.crypto] }),
  ]);

  const briefing = feat[0] ?? phanTich[0] ?? latest[0];
  const cited = phanTich.slice(0, 5);
  const followUpResults = [...tinNong, ...crypto].slice(0, 4);
  const trending = latest.slice(0, 6);

  // Tokens
  const BG = "#0E0E10";
  const BG2 = "#16161A";
  const PANEL = "#1A1A1F";
  const LINE = "#26262E";
  const LINE2 = "#33333D";
  const TEXT = "#F5F5F7";
  const DIM = "#8A8A95";
  const DIM2 = "#A1A1AC";
  const ACC = "#A1FFCB"; // mint cite
  const ACC2 = "#B794F4"; // violet
  const ACC3 = "#FFB86A"; // amber
  const SANS = "var(--font-manrope)";
  const SERIF = "var(--font-newsreader)";
  const MONO = "var(--font-jetbrains-mono)";

  const QUICK_PROMPTS = [
    { icon: "📊", label: "VN-Index hôm nay diễn biến ra sao?", color: ACC },
    { icon: "₿", label: "Bitcoin có break $70k trong tuần này không?", color: ACC3 },
    { icon: "🥇", label: "Vàng SJC vs vàng nhẫn — chênh lệch giải thích", color: ACC3 },
    { icon: "💱", label: "DXY tăng — ảnh hưởng VND thế nào?", color: ACC2 },
    { icon: "📈", label: "Phiên ATC chiều nay có gì đáng chú ý?", color: ACC },
    { icon: "🏦", label: "Fed họp tuần này — kịch bản nào cho TT?", color: ACC2 },
  ];

  return (
    <div style={{ background: BG, color: TEXT, minHeight: "100vh", fontFamily: SANS }}>
      <PreviewBar active="e" />

      {/* TOP — minimal, no nav clutter */}
      <header className="border-b" style={{ borderColor: LINE }}>
        <div className="mx-auto max-w-[1280px] px-6 py-4 flex items-center justify-between gap-6">
          <Link href="/" className="flex items-baseline gap-2.5">
            <span
              className="inline-block w-7 h-7 rounded-full"
              style={{
                background:
                  "conic-gradient(from 180deg, #A1FFCB, #B794F4, #FFB86A, #A1FFCB)",
                filter: "blur(0.5px)",
              }}
            />
            <span className="text-[18px] font-semibold tracking-tight" style={{ letterSpacing: "-0.02em" }}>
              Finzone
            </span>
            <span className="text-[10px] uppercase tracking-[0.25em] font-mono" style={{ color: DIM }}>
              · ask
            </span>
          </Link>
          <div className="flex items-center gap-2">
            <Link
              href="/category/tin-nong"
              className="hidden md:inline-flex items-center gap-2 px-3 py-1.5 text-[12px] hover:bg-white/5 rounded-md transition"
              style={{ color: DIM2 }}
            >
              Trang tin
            </Link>
            <button
              className="inline-flex items-center gap-2 px-3 py-1.5 text-[12px] rounded-md hover:bg-white/5 transition"
              style={{ color: DIM2 }}
            >
              Lịch sử
            </button>
            <button
              className="inline-flex items-center gap-2 px-3.5 py-1.5 text-[12px] font-medium rounded-md transition"
              style={{ background: ACC, color: "#0E0E10" }}
            >
              Đăng nhập
            </button>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-[920px] px-6 pt-10 pb-24">

        {/* GREETING + PROMPT BOX */}
        <section className="mb-12">
          <div className="text-[12px] font-mono uppercase tracking-[0.3em] mb-5" style={{ color: DIM }}>
            {new Date().toLocaleDateString("vi-VN", { weekday: "long", day: "2-digit", month: "long" })}
            {" · "}
            <span style={{ color: ACC }}>● online</span>
          </div>

          <h1
            className="mb-3"
            style={{
              fontFamily: SERIF,
              fontSize: "clamp(38px, 5.4vw, 64px)",
              lineHeight: 1.05,
              letterSpacing: "-0.02em",
              fontWeight: 400,
            }}
          >
            Chào bạn.
            <br />
            <span style={{ color: DIM2, fontStyle: "italic" }}>
              Hôm nay thị trường có gì?
            </span>
          </h1>

          <p className="text-[15px] mb-8 max-w-xl leading-[1.6]" style={{ color: DIM2 }}>
            Hỏi bất kỳ điều gì về tài chính. AI tổng hợp từ {trending.length}+ bài
            báo, dữ liệu thị trường live, có trích dẫn nguồn rõ ràng.
          </p>

          {/* PROMPT INPUT */}
          <div
            className="relative border rounded-2xl overflow-hidden focus-within:border-white/30 transition"
            style={{ background: PANEL, borderColor: LINE2 }}
          >
            <div className="flex items-start gap-3 p-5">
              <span className="text-[18px] mt-0.5" style={{ color: ACC }}>⌕</span>
              <div className="flex-1">
                <div
                  className="text-[18px] leading-[1.4] mb-3"
                  style={{ color: TEXT, minHeight: 28 }}
                >
                  <span style={{ color: DIM }}>
                    Hỏi bất kỳ điều gì... vd: "phân tích VN-Index tuần này"
                  </span>
                  <span
                    className="inline-block w-[2px] h-[20px] ml-1 align-middle animate-pulse"
                    style={{ background: ACC }}
                  />
                </div>
                <div className="flex items-center justify-between gap-4 pt-3 border-t" style={{ borderColor: LINE }}>
                  <div className="flex items-center gap-2 text-[11px]" style={{ color: DIM, fontFamily: MONO }}>
                    <button className="px-2 py-1 border rounded hover:border-white/30 transition" style={{ borderColor: LINE2, color: DIM2 }}>
                      🇻🇳 vi-VN
                    </button>
                    <button className="px-2 py-1 border rounded hover:border-white/30 transition" style={{ borderColor: LINE2, color: DIM2 }}>
                      📂 nguồn
                    </button>
                    <button className="px-2 py-1 border rounded hover:border-white/30 transition" style={{ borderColor: LINE2, color: DIM2 }}>
                      📅 7 ngày qua
                    </button>
                  </div>
                  <div className="flex items-center gap-2">
                    <kbd className="hidden md:inline px-2 py-0.5 border text-[10px] rounded font-mono" style={{ borderColor: LINE2, color: DIM }}>
                      ⌘ ↵
                    </kbd>
                    <button
                      className="inline-flex items-center justify-center w-9 h-9 rounded-lg transition"
                      style={{ background: ACC, color: BG }}
                      aria-label="Send"
                    >
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M5 12l14 0M13 6l6 6-6 6" />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* QUICK PROMPT CHIPS */}
          <div className="mt-6 flex flex-wrap gap-2">
            {QUICK_PROMPTS.map((p, i) => (
              <button
                key={i}
                className="inline-flex items-center gap-2 px-3 py-2 rounded-full border text-[13px] hover:bg-white/[0.03] transition group"
                style={{ borderColor: LINE2, color: DIM2 }}
              >
                <span style={{ color: p.color }}>{p.icon}</span>
                <span className="group-hover:text-white transition">{p.label}</span>
              </button>
            ))}
          </div>
        </section>

        {/* AI BRIEFING — chat reply visualization */}
        {briefing && (
          <section className="mb-12">
            {/* User question bubble */}
            <div className="flex items-start gap-3 mb-8">
              <div
                className="shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-[13px] font-semibold"
                style={{ background: BG2, color: DIM2, border: `1px solid ${LINE2}` }}
              >
                B
              </div>
              <div className="flex-1 pt-1">
                <div className="text-[15px]" style={{ color: TEXT }}>
                  Hôm nay thị trường có gì đáng chú ý?
                </div>
                <div className="text-[10px] font-mono mt-1.5" style={{ color: DIM }}>
                  {new Date().toLocaleTimeString("vi-VN", { hour: "2-digit", minute: "2-digit" })}
                </div>
              </div>
            </div>

            {/* AI response */}
            <div className="flex items-start gap-3">
              <div
                className="shrink-0 w-8 h-8 rounded-full flex items-center justify-center"
                style={{
                  background:
                    "conic-gradient(from 180deg, #A1FFCB, #B794F4, #FFB86A, #A1FFCB)",
                }}
              />
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-3">
                  <span className="text-[13px] font-semibold" style={{ color: TEXT }}>
                    Finzone Brief
                  </span>
                  <span className="px-2 py-0.5 text-[9px] uppercase tracking-wider rounded font-mono" style={{ background: BG2, color: ACC, border: `1px solid ${LINE2}` }}>
                    AI · sonnet
                  </span>
                  <span className="text-[10px] font-mono ml-auto flex items-center gap-1.5" style={{ color: DIM }}>
                    <span className="inline-block w-1.5 h-1.5 rounded-full animate-pulse" style={{ background: ACC }} />
                    đã trả lời trong 2.4s
                  </span>
                </div>

                {/* Response body */}
                <div
                  className="text-[16px] leading-[1.7] mb-6"
                  style={{ color: "#D4D4D9", fontFamily: SERIF }}
                >
                  <p className="mb-4">
                    Phiên hôm nay <span className="px-1.5 py-0.5 rounded" style={{ background: "rgba(161,255,203,0.1)", color: ACC }}>VN-Index +0.42%</span>{" "}
                    với thanh khoản cải thiện nhẹ. Điểm đáng chú ý nhất:
                  </p>
                  <p className="mb-4">
                    <strong style={{ color: TEXT }}>{briefing.title}</strong>
                    <sup className="ml-1 text-[11px] font-mono" style={{ color: ACC }}>[1]</sup>
                    {" — "}
                    {briefing.excerpt?.slice(0, 240) ?? "phân tích chi tiết về diễn biến thị trường và các yếu tố vĩ mô đang tác động"}
                    {cited.length > 1 && (
                      <sup className="ml-1 text-[11px] font-mono" style={{ color: ACC }}>[2]</sup>
                    )}
                    .
                  </p>
                  <p className="mb-4">
                    Trên thị trường tiền số, <span className="px-1.5 py-0.5 rounded" style={{ background: "rgba(255,184,106,0.12)", color: ACC3 }}>BTC −1.24%</span>{" "}
                    test vùng support 67k sau khi không giữ được 70k đầu tuần. ETH theo cùng nhịp{" "}
                    {cited.length > 2 && (
                      <sup className="text-[11px] font-mono" style={{ color: ACC }}>[3]</sup>
                    )}
                    . DXY tiếp tục mạnh lên ảnh hưởng cả crypto lẫn vàng.
                  </p>
                  <p>
                    Đáng theo dõi cuối ngày: <span style={{ color: ACC2 }}>báo cáo CPI Mỹ tháng 5</span>{" "}
                    sẽ ra lúc 19:30 ICT — định hướng kỳ vọng Fed cho cuộc họp tháng 6.
                  </p>
                </div>

                {/* CITATIONS */}
                <div
                  className="border rounded-xl p-4 mb-5"
                  style={{ background: BG2, borderColor: LINE2 }}
                >
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-2">
                      <span className="text-[11px] font-mono uppercase tracking-[0.2em]" style={{ color: ACC }}>
                        ⌖ Sources
                      </span>
                      <span className="text-[11px] font-mono" style={{ color: DIM }}>
                        {cited.length} bài
                      </span>
                    </div>
                    <button className="text-[11px] hover:text-white transition" style={{ color: DIM2 }}>
                      Xem chi tiết →
                    </button>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                    {cited.map((p, i) => (
                      <Link
                        key={p.id}
                        href={`/${p.slug}`}
                        className="group flex gap-3 p-2.5 rounded-lg border hover:border-white/20 transition"
                        style={{ borderColor: LINE2 }}
                      >
                        <span
                          className="shrink-0 w-6 h-6 rounded flex items-center justify-center text-[10px] font-mono font-bold tabular-nums"
                          style={{ background: "rgba(161,255,203,0.12)", color: ACC }}
                        >
                          {i + 1}
                        </span>
                        <div className="flex-1 min-w-0">
                          <div className="text-[12px] leading-[1.35] mb-0.5 line-clamp-2 group-hover:text-white transition" style={{ color: DIM2 }}>
                            {p.title}
                          </div>
                          <div className="text-[10px] font-mono" style={{ color: DIM }}>
                            {p.categories[0]?.name ?? "Tin"} · {p.author.name} · {p.readMinutes}'
                          </div>
                        </div>
                      </Link>
                    ))}
                  </div>
                </div>

                {/* INLINE RESULT CARDS */}
                {followUpResults.length > 0 && (
                  <div className="mb-5">
                    <div className="text-[11px] font-mono uppercase tracking-[0.2em] mb-3" style={{ color: DIM }}>
                      ▦ Bài liên quan
                    </div>
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      {followUpResults.map((p) => (
                        <Link
                          key={p.id}
                          href={`/${p.slug}`}
                          className="group flex gap-3 p-3 rounded-xl border hover:border-white/20 transition"
                          style={{ borderColor: LINE, background: BG2 }}
                        >
                          {p.featured && (
                            <div className="shrink-0 w-16 h-16 rounded-lg overflow-hidden bg-white/5 relative">
                              <Image src={p.featured.url} alt={p.featured.alt} fill sizes="64px" className="object-cover" />
                            </div>
                          )}
                          <div className="flex-1 min-w-0">
                            <div className="text-[10px] font-mono uppercase tracking-wider mb-1" style={{ color: ACC2 }}>
                              {p.categories[0]?.name ?? "Tin"}
                            </div>
                            <div className="text-[13px] leading-[1.35] line-clamp-2 group-hover:text-white transition" style={{ color: TEXT }}>
                              {p.title}
                            </div>
                            <div className="text-[10px] font-mono mt-1" style={{ color: DIM }}>
                              {p.readMinutes}' · {new Date(p.date).toLocaleDateString("vi-VN")}
                            </div>
                          </div>
                        </Link>
                      ))}
                    </div>
                  </div>
                )}

                {/* FOLLOW-UPS */}
                <div className="border-t pt-5" style={{ borderColor: LINE }}>
                  <div className="text-[11px] font-mono uppercase tracking-[0.2em] mb-3" style={{ color: DIM }}>
                    ⤓ Hỏi tiếp
                  </div>
                  <div className="space-y-2">
                    {[
                      { q: "Phân tích kỹ thuật VN30 — vùng kháng cự gần nhất?", c: ACC },
                      { q: "Top 5 cổ phiếu tăng mạnh phiên hôm nay", c: ACC },
                      { q: "Vàng SJC: nên mua tích lũy hay đợi điều chỉnh?", c: ACC3 },
                    ].map((f, i) => (
                      <button
                        key={i}
                        className="w-full text-left flex items-center gap-3 p-3 rounded-lg border hover:bg-white/[0.03] transition group"
                        style={{ borderColor: LINE }}
                      >
                        <span style={{ color: f.c }}>→</span>
                        <span className="text-[13px] flex-1" style={{ color: DIM2 }}>
                          {f.q}
                        </span>
                        <span className="text-[10px] font-mono opacity-0 group-hover:opacity-100 transition" style={{ color: DIM }}>
                          ⌘↵
                        </span>
                      </button>
                    ))}
                  </div>
                </div>

                {/* ACTION BAR */}
                <div className="flex items-center gap-3 mt-5 text-[11px] font-mono" style={{ color: DIM }}>
                  <button className="hover:text-white transition flex items-center gap-1.5">↻ thử lại</button>
                  <button className="hover:text-white transition flex items-center gap-1.5">⎘ copy</button>
                  <button className="hover:text-white transition flex items-center gap-1.5">↗ chia sẻ</button>
                  <button className="hover:text-white transition flex items-center gap-1.5">★ lưu</button>
                  <span className="ml-auto">tokens: 1,247 · model: sonnet-4</span>
                </div>
              </div>
            </div>
          </section>
        )}

        {/* TRENDING TOPICS — like Perplexity sidebar moved inline */}
        <section className="mb-10 pt-10 border-t" style={{ borderColor: LINE }}>
          <div className="flex items-baseline justify-between mb-6">
            <div>
              <div className="text-[11px] font-mono uppercase tracking-[0.25em] mb-1" style={{ color: ACC }}>
                ◉ Trending hôm nay
              </div>
              <h2 style={{ fontFamily: SERIF, fontSize: 28, fontStyle: "italic", color: TEXT }}>
                Mọi người đang hỏi gì
              </h2>
            </div>
            <Link href="/category/tin-nong" className="text-[12px]" style={{ color: DIM2 }}>
              Tất cả →
            </Link>
          </div>
          <div className="space-y-2">
            {trending.map((p, i) => (
              <Link
                key={p.id}
                href={`/${p.slug}`}
                className="flex items-baseline gap-4 p-4 rounded-xl border hover:bg-white/[0.02] transition group"
                style={{ borderColor: LINE }}
              >
                <span
                  className="text-[24px] font-mono tabular-nums shrink-0 w-8"
                  style={{ color: i < 3 ? ACC : DIM, fontVariantNumeric: "tabular-nums" }}
                >
                  {String(i + 1).padStart(2, "0")}
                </span>
                <div className="flex-1 min-w-0">
                  <div className="text-[15px] leading-[1.35] group-hover:text-white transition mb-1" style={{ color: TEXT }}>
                    {p.title}
                  </div>
                  <div className="flex items-center gap-2 text-[11px] font-mono" style={{ color: DIM }}>
                    <span style={{ color: ACC2 }}>{p.categories[0]?.name ?? "Tin"}</span>
                    <span>·</span>
                    <span>{p.readMinutes}'</span>
                    <span>·</span>
                    <span className="flex items-center gap-1">
                      <span style={{ color: ACC }}>↑</span>
                      {Math.floor(Math.random() * 800 + 200)} hỏi
                    </span>
                  </div>
                </div>
                <span className="text-[18px] opacity-30 group-hover:opacity-100 transition" style={{ color: TEXT }}>→</span>
              </Link>
            ))}
          </div>
        </section>

        {/* COLLECTIONS / SPACES — Perplexity Spaces equivalent */}
        <section className="mb-10">
          <div className="flex items-baseline justify-between mb-5">
            <div>
              <div className="text-[11px] font-mono uppercase tracking-[0.25em] mb-1" style={{ color: ACC2 }}>
                ▤ Spaces
              </div>
              <h2 style={{ fontFamily: SERIF, fontSize: 28, fontStyle: "italic", color: TEXT }}>
                Bộ sưu tập theo chủ đề
              </h2>
            </div>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
            {[
              { title: "Crypto VN", count: 142, color: ACC3, icon: "₿" },
              { title: "Vĩ mô & Fed", count: 87, color: ACC2, icon: "🏛" },
              { title: "VN-Index", count: 234, color: ACC, icon: "📊" },
              { title: "Vàng & FX", count: 56, color: ACC3, icon: "🥇" },
              { title: "Bất động sản", count: 78, color: ACC, icon: "🏘" },
              { title: "Phái sinh", count: 41, color: ACC2, icon: "⚙" },
            ].map((s) => (
              <Link
                key={s.title}
                href={`/category/${s.title.toLowerCase().replace(/\s+/g, "-")}`}
                className="p-4 rounded-xl border hover:bg-white/[0.03] transition group"
                style={{ borderColor: LINE, background: BG2 }}
              >
                <div className="flex items-center gap-2 mb-3">
                  <span className="text-[18px]" style={{ color: s.color }}>{s.icon}</span>
                  <span className="text-[10px] font-mono ml-auto" style={{ color: DIM }}>
                    {s.count} bài
                  </span>
                </div>
                <div className="text-[15px] font-medium" style={{ color: TEXT }}>
                  {s.title}
                </div>
                <div className="text-[11px] mt-1 group-hover:text-white transition" style={{ color: DIM2 }}>
                  Hỏi AI về {s.title.toLowerCase()} →
                </div>
              </Link>
            ))}
          </div>
        </section>
      </main>

      {/* MINIMAL FOOTER */}
      <footer className="border-t" style={{ borderColor: LINE }}>
        <div className="mx-auto max-w-[1280px] px-6 py-8 flex flex-wrap items-center justify-between gap-4 text-[11px] font-mono" style={{ color: DIM }}>
          <div className="flex items-center gap-3">
            <span
              className="inline-block w-4 h-4 rounded-full"
              style={{
                background: "conic-gradient(from 180deg, #A1FFCB, #B794F4, #FFB86A, #A1FFCB)",
              }}
            />
            <span>Finzone Ask · 2026</span>
          </div>
          <div className="flex items-center gap-5">
            <Link href="/gioi-thieu" className="hover:text-white transition">Về chúng tôi</Link>
            <Link href="/lien-he" className="hover:text-white transition">Liên hệ</Link>
            <Link href="/bao-mat" className="hover:text-white transition">Bảo mật</Link>
            <span className="flex items-center gap-1.5">
              <span className="inline-block w-1.5 h-1.5 rounded-full" style={{ background: ACC }} />
              <span style={{ color: ACC }}>online</span>
            </span>
          </div>
        </div>
      </footer>
    </div>
  );
}
