import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState, type FormEvent } from "react";
import {
  Check,
  CircleDot,
  Download,
  ExternalLink,
  Filter,
  Loader2,
  Play,
  Search,
  Store,
  Tags,
  TriangleAlert,
} from "lucide-react";
import { cn } from "#/lib/utils";
import {
  BUILD_PRESETS,
  MARKETPLACE_OPTIONS,
  MARKET_META,
  SORT_OPTIONS,
  planLauncher,
  type Marketplace,
  type SortId,
} from "#/lib/launcher";
import { CouponVault } from "#/components/CouponVault";
import { PartnerComparison } from "#/components/PartnerComparison";
import { PriceComparison } from "#/components/PriceComparison";
import { VerifiedListings } from "#/components/VerifiedListings";
import { CpuComparison } from "#/components/CpuComparison";

export const Route = createFileRoute("/")({ component: Home });

function TerminalSection({
  no,
  title,
  sub,
  children,
}: {
  no: string;
  title: string;
  sub?: string;
  children: React.ReactNode;
}) {
  return (
    <section className="flex flex-col gap-4">
      <div className="flex items-baseline gap-3 border-b border-white/15 pb-2">
        <span className="font-mono text-[11px] uppercase tracking-[0.25em] text-[#FF2A2A]">
          [{no} // {title}]
        </span>
        {sub && (
          <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
            {sub}
          </span>
        )}
      </div>
      {children}
    </section>
  );
}

function Home() {
  const [query, setQuery] = useState("");
  const [market, setMarket] = useState<Marketplace>("both");
  const [sortId, setSortId] = useState<SortId>("price-asc");

  const plan = useMemo(
    () => planLauncher(query, market, sortId),
    [query, market, sortId],
  );
  const hasContent = plan.positive.length > 0;

  const onGenerate = (e?: FormEvent) => {
    e?.preventDefault();
    document
      .getElementById("launchers")
      ?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <main className="mx-auto flex w-full max-w-6xl flex-col gap-12 px-4 py-10 sm:px-8 sm:py-16">
      {/* System utility bar */}
      <div className="flex flex-wrap items-center gap-x-3 gap-y-2 justify-between border border-white/15 px-3 py-2 font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
        <span>[ ZEZO.EXE ]</span>
        <span className="hidden sm:inline">ZIAD ALMUTIRI // HARDWARE UNIT</span>
        <a
          href="/zezo-source-export.zip"
          download="zezo-source-export.zip"
          className="inline-flex cursor-pointer items-center gap-1.5 text-[#4AF626] transition hover:text-[#FF2A2A]"
        >
          <Download className="size-3.5" aria-hidden="true" />
          تنزيل كود المصدر (ZIP)
        </a>
      </div>

      {/* Header */}
      <header className="flex flex-col gap-4">
        <div className="flex items-center gap-2 font-mono text-[11px] uppercase tracking-[0.25em] text-[#FF2A2A]">
          <span aria-hidden="true">+</span>
          [ راصد ومنصة صيد صفقات 11.11 ]
          <span aria-hidden="true">+</span>
        </div>
        <h1
          aria-label="Zezo for Premium Price"
          className="font-display text-2xl leading-none text-pretty sm:text-5xl"
        >
          <span className="sm:hidden">Zezo Deals</span>
          <span className="hidden sm:inline">Zezo for Premium Price</span>
        </h1>
        <p className="max-w-2xl font-medium text-label text-(--muted)">
          راصد ومنصة صيد صفقات 11.11
        </p>
        <p className="max-w-2xl text-body leading-relaxed text-(--muted)">
          مطلق بحث ذكي: يولّد كلمات بحث دقيقة مع تصفية الملحقات (كابلات،
          أغطية، أداة تثبيت...) ويفتح أمازون السعودية أو علي إكسبريس بروابط
          بحث جاهزة. لا يعرض أسعاراً وهمية، ولا يخترع عروضاً.
        </p>
      </header>

      {/* Control panel */}
      <section className="crt-frame scanlines flex w-full flex-col">
        <div className="flex items-center justify-between border-b border-white/15 px-3 py-2 font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
          <span>[ 01 // QUERY + LAUNCH ]</span>
          <span className="hidden sm:inline">ACCURATE_URLS</span>
        </div>

        <form className="flex flex-col gap-4 p-3 sm:p-5" onSubmit={onGenerate} role="search">
          <label className="flex flex-col gap-2">
            <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
              &gt; اكتب المنتج أو الرمز (مثال: B650, Ryzen 7 9800X3D, iPhone 16)
            </span>
            <div className="relative">
              <Search
                className="pointer-events-none absolute start-3 top-1/2 size-4 -translate-y-1/2 text-(--muted)"
                aria-hidden="true"
              />
              <input
                type="search"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="مثال: Gigabyte B650 Eagle AX"
                className="w-full border border-white/20 bg-[#0D0F12] py-3.5 pe-4 ps-11 text-body text-(--ink) outline-none transition focus-visible:border-[#FF2A2A] focus-visible:ring-1 focus-visible:ring-[#FF2A2A]"
              />
            </div>
          </label>

          {/* Quick-launch presets for Ziyad's build */}
          <div className="flex flex-col gap-2">
            <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
              &gt; اختصارات تشكيل Ziyad
            </span>
            <div className="flex flex-wrap gap-2">
              {BUILD_PRESETS.map((p) => (
                <button
                  key={p.id}
                  type="button"
                  onClick={() => setQuery(p.query)}
                  className="cursor-pointer border border-white/20 bg-[#0D0F12] px-2.5 py-1.5 font-mono text-[11px] uppercase tracking-wide text-(--ink) transition hover:border-[#FF2A2A] hover:text-[#FF2A2A] active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#FF2A2A]"
                >
                  {p.label}
                  <span className="ms-2 text-(--muted)">{p.en}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div className="flex flex-col gap-2">
              <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
                &gt; السوق
              </span>
              <div className="grid grid-cols-1 gap-2">
                {MARKETPLACE_OPTIONS.map((opt) => {
                  const active = market === opt.value;
                  return (
                    <button
                      key={opt.value}
                      type="button"
                      onClick={() => setMarket(opt.value)}
                      aria-pressed={active}
                      className={cn(
                        "flex cursor-pointer items-center justify-between gap-2 border px-3 py-2.5 text-start transition active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#FF2A2A]",
                        active
                          ? "border-[#FF2A2A] bg-[#FF2A2A]/10"
                          : "border-white/20 bg-[#0D0F12] hover:border-white/40",
                      )}
                    >
                      <span
                        className={cn(
                          "flex items-center gap-1.5 text-label font-medium",
                          active && "text-[#FF2A2A]",
                        )}
                      >
                        {active && (
                          <CircleDot className="size-3" aria-hidden="true" />
                        )}
                        {opt.label}
                      </span>
                      <span className="font-mono text-[10px] uppercase tracking-[0.18em] text-(--muted)">
                        {opt.en}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="flex flex-col gap-2">
              <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
                &gt; فرز / فلتر (يُطبَّق فقط إن أمكن ترميزه في الرابط)
              </span>
              <div className="flex flex-col gap-2">
                {SORT_OPTIONS.map((s) => {
                  const active = sortId === s.id;
                  return (
                    <button
                      key={s.id}
                      type="button"
                      onClick={() => setSortId(s.id)}
                      aria-pressed={active}
                      className={cn(
                        "flex cursor-pointer items-center justify-between gap-2 border px-3 py-2.5 text-start transition active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#FF2A2A]",
                        active
                          ? "border-[#FF2A2A] bg-[#FF2A2A]/10"
                          : "border-white/20 bg-[#0D0F12] hover:border-white/40",
                      )}
                    >
                      <span className="flex items-center gap-1.5 text-label font-medium">
                        {active && (
                          <CircleDot className="size-3 text-[#FF2A2A]" aria-hidden="true" />
                        )}
                        {s.label}
                      </span>
                      <span className="font-mono text-[10px] uppercase tracking-[0.18em] text-(--muted)">
                        {s.en}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>

          <button
            type="submit"
            className="mt-1 inline-flex cursor-pointer items-center justify-center gap-2 border border-[#FF2A2A] bg-[#FF2A2A] px-6 py-3.5 font-mono text-label font-bold uppercase tracking-[0.15em] text-black shadow-[0_6px_0_-4px_rgba(10,10,10,0.9),0_1px_2px_rgba(0,0,0,0.5)] transition hover:brightness-110 active:translate-y-[1px] active:shadow-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70"
          >
            <Play className="size-4" aria-hidden="true" />
            إنشاء روابط الإطلاق
          </button>
        </form>

        <div className="flex items-start gap-2.5 border-t border-amber-500/30 bg-amber-500/[0.06] px-3 py-3">
          <TriangleAlert className="mt-0.5 size-4 shrink-0 text-amber-400" aria-hidden="true" />
          <p className="font-mono text-[11px] font-medium leading-relaxed text-amber-100/80">
            هذا مطلق بحث فقط: يفتح صفحة بحث في المتجر ولا يعرض أسعاراً. لا يتم
            عرض أسعار أو عروض وهمية، وأي كوبون غير موثّق بمصدر حي يبقى بوسم
            "مثال".
          </p>
        </div>
      </section>

      {/* Keyword intel */}
      <TerminalSection no="02" title="KEYWORD INTEL" sub="الكلمات + استبعاد الملحقات">
        <div className="flex flex-col gap-3">
          <div className="flex items-center gap-2 border border-white/15 bg-white/[0.02] px-3 py-2.5">
            <span className="font-mono text-[10px] uppercase tracking-[0.2em] text-[#FF2A2A]">
              [INTENT]
            </span>
            <span className="text-label font-medium">{plan.intent.label}</span>
            <span className="font-mono text-[10px] uppercase tracking-[0.18em] text-(--muted)">
              / {plan.intent.en}
            </span>
          </div>

          <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
            <div className="flex flex-col gap-2 border border-white/15 bg-white/[0.02] p-3">
              <span className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
                <Tags className="size-3" aria-hidden="true" />
                كلمات البحث الموجبة
              </span>
              <div className="flex flex-wrap gap-1.5">
                {plan.positive.length > 0 ? (
                  plan.positive.map((t, i) => (
                    <code
                      key={`${t}-${i}`}
                      className="border border-white/15 bg-black/20 px-2 py-0.5 font-mono text-[11px] text-[#EAEAEA]"
                    >
                      {t}
                    </code>
                  ))
                ) : (
                  <span className="font-mono text-[11px] text-(--muted)">
                    أدخل منتجاً أو اختر اختصاراً
                  </span>
                )}
              </div>
            </div>

            <div className="flex flex-col gap-2 border border-white/15 bg-white/[0.02] p-3">
              <span className="flex items-center gap-1.5 font-mono text-[10px] uppercase tracking-[0.2em] text-(--muted)">
                <Filter className="size-3" aria-hidden="true" />
                كلمات مستبعَدة (ملحقات)
              </span>
              <div className="flex flex-wrap gap-1.5">
                {plan.negative.map((t, i) => (
                  <code
                    key={`${t}-${i}`}
                    className="border border-white/15 bg-black/20 px-2 py-0.5 font-mono text-[11px] text-(--muted) line-through"
                  >
                    -{t}
                  </code>
                ))}
              </div>
              <p className="font-mono text-[10px] leading-relaxed text-amber-100/60">
                هذه المصطلحات تُستبعَد من الاستهداف. لا تدعم أمازون وعلي إكسبريس
                عامل الاستبعاد "-" في الرابط، لذا تُحتسَب لصياغة كلمات موجبة أدق
                ولا تُدَّعى كفلتر مطبَّق.
              </p>
            </div>
          </div>
        </div>
      </TerminalSection>

      {/* Launchers */}
      <section id="launchers" className="flex scroll-mt-24 flex-col gap-4">
        <TerminalSection no="03" title="LAUNCHERS" sub="افتح البحث في المتجر">
          {hasContent ? (
            <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
              {plan.launches.map((l) => (
                <article
                  key={l.key}
                  className="flex flex-col gap-3 border border-white/15 bg-white/[0.02] p-3"
                >
                  <div className="flex items-center justify-between gap-2">
                    <span className="flex items-center gap-1.5 font-mono text-[11px] uppercase tracking-[0.18em] text-[#FF2A2A]">
                      <Store className="size-3.5" aria-hidden="true" />
                      {MARKET_META[l.key].en}
                    </span>
                    {l.applied ? (
                      <span className="inline-flex items-center gap-1 border border-[#4AF626]/50 bg-[#4AF626]/10 px-1.5 py-0.5 font-mono text-[10px] uppercase tracking-wider text-[#4AF626]">
                        <Check className="size-3" aria-hidden="true" />
                        {l.applied}
                      </span>
                    ) : (
                      <span className="font-mono text-[10px] uppercase tracking-wider text-(--muted)">
                        لا فرز مطبَّق
                      </span>
                    )}
                  </div>

                  {l.primeNote && (
                    <p className="font-mono text-[10px] leading-relaxed text-amber-100/60">
                      فلتر Prime غير قابل للترميز في الرابط - فعِّله يدوياً في صفحة
                      أمازون بعد الفتح.
                    </p>
                  )}

                  <code className="break-all border border-white/10 bg-black/30 px-2 py-1.5 font-mono text-[11px] leading-relaxed text-(--muted)">
                    {l.url}
                  </code>

                  <a
                    href={l.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex cursor-pointer items-center justify-center gap-2 border border-[#FF2A2A] bg-[#FF2A2A]/10 px-4 py-2.5 font-mono text-label font-bold uppercase tracking-[0.12em] text-[#FF2A2A] transition hover:bg-[#FF2A2A] hover:text-black active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white/70"
                  >
                    فتح البحث في {MARKET_META[l.key].en}
                    <ExternalLink className="size-4" aria-hidden="true" />
                  </a>
                </article>
              ))}
            </div>
          ) : (
            <div className="flex flex-col items-center gap-3 border border-dashed border-white/15 py-16 text-center">
              <Search className="size-5 text-(--muted)" aria-hidden="true" />
              <p className="max-w-md font-mono text-[13px] text-(--muted)">
                أدخل اسم المنتج أو الرمز، أو اختر اختصاراً من تشكيل Ziyad،
                لتوليد روابط إطلاق بحث دقيقة.
              </p>
            </div>
          )}
        </TerminalSection>
      </section>

      {/* Price comparison (reference + live attempt, never a dead-end) */}
      <PriceComparison query={query} intentId={plan.intent.id} />

      {/* CPU retail prices (boxed vs tray, verified-or-unavailable) */}
      {plan.intent.id === "cpu" && <CpuComparison query={query} />}

      {/* Verified Amazon.sa listings (real observed prices, GPU) */}
      {plan.intent.id === "gpu" && <VerifiedListings />}

      {/* AIB partner editions (GPU only) */}
      {plan.intent.id === "gpu" && (
        <PartnerComparison query={query} intentId={plan.intent.id} />
      )}

      {/* Coupon vault */}
      <CouponVault />
    </main>
  );
}
