// @File: src/pages/DomainSearch.tsx
// @Desc: Domain Search & Registration page. Lets visitors type a domain name
//        (with or without a TLD), hits the backend /api/v1/whmcs/domain-check
//        endpoint which proxies WHMCS `DomainWhois` + `DomainGetPrices`, and
//        renders real-time availability with pricing and an "Add to cart" /
//        "Try another" CTA per TLD. Also features popular TLDs, FAQ and a
//        trust/benefits band — consistent with the rest of the marketing site.
import { useEffect, useState } from "react";
import {
  Search,
  Loader2,
  CheckCircle2,
  XCircle,
  HelpCircle,
  Globe2,
  ShieldCheck,
  Zap,
  HeartHandshake,
  Wallet,
  ChevronDown,
  AlertCircle,
} from "lucide-react";
import SiteLayout from "@/components/SiteLayout";
import AnimateIn from "@/components/AnimateIn";

/**
 * Public POST helper for the domain-check endpoint. We inline a small fetch
 * wrapper instead of relying on an SDK because this endpoint is unauthenticated
 * and the rest of the public marketing pages use the same pattern.
 */
async function postDomainCheck(
  payload: { domain: string; tlds: string[] },
): Promise<DomainCheckResponse> {
  let res: Response;
  try {
    res = await fetch("/api/v1/whmcs/domain-check", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      credentials: "omit",
    });
  } catch (err) {
    throw new Error(
      err instanceof Error
        ? `Network error: ${err.message}`
        : "Network error while checking your domain.",
    );
  }

  let body: unknown = null;
  try {
    body = await res.json();
  } catch {
    // fall through; we handle the non-JSON case via status
  }

  if (!res.ok) {
    const detail =
      body && typeof body === "object" && "detail" in body
        ? (body as { detail?: string }).detail
        : undefined;
    throw new Error(
      detail || `Request failed with status ${res.status}. Please try again.`,
    );
  }

  if (!body || typeof body !== "object") {
    throw new Error("Unexpected response from the billing system.");
  }
  return body as DomainCheckResponse;
}

/* ---------------- Types ---------------- */

interface DomainAvailabilityItem {
  domain: string;
  tld: string;
  available: boolean;
  status: "available" | "taken" | "unknown";
  price: string | null;
  currency: string | null;
  register_url: string | null;
}

interface DomainCheckResponse {
  sld: string;
  results: DomainAvailabilityItem[];
}

const DEFAULT_TLDS = [
  "com",
  "net",
  "org",
  "info",
  "io",
  "co",
  "sa",
  "ae",
  "online",
  "store",
];

const POPULAR_TLDS: { tld: string; desc: string; highlight?: boolean }[] = [
  { tld: "com", desc: "The global default — best for most businesses.", highlight: true },
  { tld: "net", desc: "Popular for tech, networking and infrastructure brands." },
  { tld: "org", desc: "Ideal for organizations, communities and non-profits." },
  { tld: "io", desc: "A favorite among startups and developer-focused brands." },
  { tld: "sa", desc: "Country-code TLD for Saudi Arabia — perfect for local presence." },
  { tld: "ae", desc: "Country-code TLD for the United Arab Emirates." },
  { tld: "online", desc: "A modern alternative that works for any industry." },
  { tld: "store", desc: "Purpose-built for e-commerce and retail sites." },
];

const FAQ: { q: string; a: string }[] = [
  {
    q: "How does domain registration work?",
    a: "Once you find an available domain, click 'Register' to add it to your cart. Choose your registration period (1-10 years) and complete checkout. Your domain will be active within minutes and you can manage it from your client area.",
  },
  {
    q: "Can I transfer a domain I already own?",
    a: "Yes. You'll need to unlock the domain at your current registrar and obtain an authorization (EPP) code. Contact our support team and we'll walk you through the transfer — it typically completes within 5-7 days with no downtime.",
  },
  {
    q: "What's included with every domain?",
    a: "Every domain includes free DNS management, domain forwarding, privacy protection (where available), email forwarding, and easy management tools in your client portal.",
  },
  {
    q: "How long does it take for my domain to be active?",
    a: "Most domains are active within a few minutes of registration. Some country-code TLDs may require additional verification and can take a few hours.",
  },
  {
    q: "Do you support IDN (Arabic) domains?",
    a: "Yes, we support a wide range of IDN-enabled TLDs. Contact our support team if you need help registering an Arabic or mixed-script domain.",
  },
];

/* ---------------- Helpers ---------------- */

function formatPrice(price: string | null, currency: string | null): string {
  if (!price) return "Contact us";
  const num = parseFloat(price);
  if (Number.isNaN(num)) return price;
  const symbol =
    (currency || "").toUpperCase() === "USD"
      ? "$"
      : (currency || "").toUpperCase() === "SAR"
      ? "SAR "
      : (currency || "").toUpperCase() === "AED"
      ? "AED "
      : `${currency ? currency + " " : ""}`;
  return `${symbol}${num.toFixed(2)}`;
}

/* ---------------- Page ---------------- */

export default function DomainSearch() {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState<DomainAvailabilityItem[] | null>(null);
  const [searchedName, setSearchedName] = useState<string>("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [openFaq, setOpenFaq] = useState<number | null>(0);

  // Pre-fill query from ?q= for deep-linking from other pages
  useEffect(() => {
    if (typeof window === "undefined") return;
    const params = new URLSearchParams(window.location.search);
    const q = params.get("q");
    if (q) {
      setQuery(q);
      // Fire a search immediately so the user sees results on arrival.
      void runSearch(q);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const trimmedQuery = query.trim();
  const canSearch = trimmedQuery.length >= 2 && !loading;

  async function runSearch(raw: string) {
    const value = raw.trim();
    if (value.length < 2) {
      setError("Please enter at least 2 characters.");
      return;
    }
    setLoading(true);
    setError(null);
    setResults(null);
    try {
      const res = await postDomainCheck({
        domain: value,
        tlds: DEFAULT_TLDS,
      });
      setSearchedName(res.sld);
      setResults(res.results);
    } catch (err) {
      const msg =
        err instanceof Error
          ? err.message
          : "We couldn't check domains right now. Please try again.";
      setError(msg);
    } finally {
      setLoading(false);
    }
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!canSearch) return;
    void runSearch(trimmedQuery);
  };

  const handleRegister = (domain: string) => {
    // Route visitors to hosting page pre-filled with their chosen domain.
    window.location.href = `/hosting?domain=${encodeURIComponent(domain)}`;
  };

  return (
    <SiteLayout>
      {/* Hero + search */}
      <section className="relative overflow-hidden bg-gradient-to-br from-[#063019] via-[#0b6e3e] to-[#0e8f52] text-white">
        <div className="absolute inset-0 pointer-events-none" aria-hidden="true">
          <div className="absolute -top-24 -right-24 w-96 h-96 rounded-full bg-[#22c55e]/30 blur-3xl" />
          <div className="absolute -bottom-24 -left-24 w-96 h-96 rounded-full bg-[#f5c400]/20 blur-3xl" />
        </div>
        <div className="relative max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 pt-28 pb-16 md:pt-36 md:pb-24 text-center">
          <AnimateIn>
            <div className="inline-flex items-center gap-2 bg-white/10 backdrop-blur-sm border border-white/20 rounded-full px-4 py-1.5 text-sm font-medium mb-5">
              <Globe2 className="w-4 h-4 text-[#f5c400]" />
              <span>Domain Search &amp; Registration</span>
            </div>
            <h1 className="text-3xl sm:text-4xl md:text-5xl lg:text-6xl font-extrabold leading-tight mb-4">
              Find the perfect <span className="text-[#f5c400]">.domain</span>
              <br className="hidden md:block" />
              for your next big idea
            </h1>
            <p className="max-w-2xl mx-auto text-slate-100/90 text-base md:text-lg mb-8">
              Check real-time availability across popular TLDs and register in
              just a few clicks. Free DNS, email forwarding, and 24/7 support
              included with every domain.
            </p>
          </AnimateIn>

          {/* Search bar */}
          <AnimateIn delay={0.1}>
            <form
              onSubmit={handleSubmit}
              className="max-w-3xl mx-auto bg-white rounded-2xl shadow-2xl p-2 sm:p-3 flex flex-col sm:flex-row gap-2"
            >
              <div className="flex-1 flex items-center gap-3 px-4 py-2">
                <Search className="w-5 h-5 text-slate-400 shrink-0" />
                <input
                  type="text"
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  placeholder="e.g. mycompany or mycompany.com"
                  className="w-full bg-transparent outline-none text-slate-900 placeholder:text-slate-400 text-base sm:text-lg"
                  autoFocus
                  autoComplete="off"
                  spellCheck={false}
                />
              </div>
              <button
                type="submit"
                disabled={!canSearch}
                className="inline-flex items-center justify-center gap-2 px-6 sm:px-8 py-3 rounded-xl bg-[#f5c400] text-slate-900 font-bold hover:bg-yellow-400 transition disabled:opacity-60 disabled:cursor-not-allowed"
              >
                {loading ? (
                  <>
                    <Loader2 className="w-5 h-5 animate-spin" /> Searching…
                  </>
                ) : (
                  <>
                    <Search className="w-5 h-5" /> Search
                  </>
                )}
              </button>
            </form>
            <p className="text-sm text-slate-200/80 mt-3">
              Checking across:{" "}
              {DEFAULT_TLDS.map((t) => `.${t}`).join(" · ")}
            </p>
          </AnimateIn>
        </div>
      </section>

      {/* Results */}
      <section className="bg-slate-50 py-14 md:py-20">
        <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
          {error && (
            <div className="flex items-start gap-3 bg-red-50 border border-red-200 text-red-800 rounded-xl px-4 py-3 mb-8">
              <AlertCircle className="w-5 h-5 mt-0.5 shrink-0" />
              <p className="text-sm font-medium">{error}</p>
            </div>
          )}

          {!results && !loading && !error && (
            <AnimateIn>
              <div className="text-center text-slate-500">
                <Globe2 className="w-14 h-14 text-[#0b6e3e]/30 mx-auto mb-3" />
                <p className="text-lg">
                  Enter a name above to see which TLDs are available.
                </p>
              </div>
            </AnimateIn>
          )}

          {loading && (
            <div className="text-center py-12">
              <Loader2 className="w-10 h-10 animate-spin text-[#0b6e3e] mx-auto mb-3" />
              <p className="text-slate-600">
                Checking availability with the registry…
              </p>
            </div>
          )}

          {results && !loading && (
            <>
              <AnimateIn>
                <h2 className="text-2xl md:text-3xl font-bold text-slate-900 mb-1">
                  Results for{" "}
                  <span className="text-[#0b6e3e]">{searchedName}</span>
                </h2>
                <p className="text-slate-600 mb-8">
                  {results.filter((r) => r.available).length} available across
                  {" "}
                  {results.length} TLDs.
                </p>
              </AnimateIn>

              <div className="space-y-3">
                {results.map((item, idx) => (
                  <AnimateIn key={item.domain} delay={idx * 0.03}>
                    <div
                      className={`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 bg-white rounded-2xl border p-4 md:p-5 shadow-sm transition hover:shadow-md ${
                        item.available
                          ? "border-emerald-200"
                          : item.status === "taken"
                          ? "border-slate-200"
                          : "border-amber-200"
                      }`}
                    >
                      <div className="flex items-start gap-3 min-w-0 flex-1">
                        {item.available ? (
                          <CheckCircle2 className="w-6 h-6 text-emerald-600 mt-0.5 shrink-0" />
                        ) : item.status === "taken" ? (
                          <XCircle className="w-6 h-6 text-slate-400 mt-0.5 shrink-0" />
                        ) : (
                          <HelpCircle className="w-6 h-6 text-amber-500 mt-0.5 shrink-0" />
                        )}
                        <div className="min-w-0">
                          <p className="text-lg md:text-xl font-bold text-slate-900 truncate">
                            {item.domain}
                          </p>
                          <p className="text-sm font-medium">
                            {item.available && (
                              <span className="text-emerald-700">
                                Available to register
                              </span>
                            )}
                            {item.status === "taken" && (
                              <span className="text-slate-500">
                                Already taken
                              </span>
                            )}
                            {item.status === "unknown" && (
                              <span className="text-amber-600">
                                Status unknown — try again shortly
                              </span>
                            )}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-center gap-3 sm:gap-5 shrink-0">
                        {item.available && (
                          <div className="text-right">
                            <p className="text-xs uppercase tracking-wide text-slate-500">
                              From
                            </p>
                            <p className="text-lg font-bold text-slate-900">
                              {formatPrice(item.price, item.currency)}
                              <span className="text-xs text-slate-500 font-normal ml-1">
                                /yr
                              </span>
                            </p>
                          </div>
                        )}
                        {item.available ? (
                          <button
                            type="button"
                            onClick={() => handleRegister(item.domain)}
                            className="px-5 py-2.5 rounded-xl bg-[#0b6e3e] text-white font-bold hover:bg-[#0a8048] transition"
                          >
                            Register
                          </button>
                        ) : item.status === "taken" ? (
                          <a
                            href={`https://who.is/whois/${encodeURIComponent(item.domain)}`}
                            target="_blank"
                            rel="noreferrer noopener"
                            className="px-5 py-2.5 rounded-xl border-2 border-slate-300 text-slate-700 font-semibold hover:bg-slate-50 transition"
                          >
                            Whois
                          </a>
                        ) : (
                          <button
                            type="button"
                            onClick={() => void runSearch(trimmedQuery)}
                            className="px-5 py-2.5 rounded-xl border-2 border-amber-400 text-amber-700 font-semibold hover:bg-amber-50 transition"
                          >
                            Retry
                          </button>
                        )}
                      </div>
                    </div>
                  </AnimateIn>
                ))}
              </div>
            </>
          )}
        </div>
      </section>

      {/* Popular TLDs */}
      <section className="bg-white py-14 md:py-20">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn>
            <div className="text-center max-w-2xl mx-auto mb-10">
              <h2 className="text-2xl md:text-4xl font-extrabold text-slate-900 mb-3">
                Popular Top-Level Domains
              </h2>
              <p className="text-slate-600">
                From timeless classics like .com to industry-specific extensions
                like .store — find the perfect fit for your brand.
              </p>
            </div>
          </AnimateIn>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
            {POPULAR_TLDS.map((p, idx) => (
              <AnimateIn key={p.tld} delay={idx * 0.04}>
                <div
                  className={`h-full p-6 rounded-2xl border-2 transition hover:-translate-y-1 hover:shadow-lg ${
                    p.highlight
                      ? "bg-gradient-to-br from-[#0b6e3e] to-[#083d24] border-[#0b6e3e] text-white"
                      : "bg-slate-50 border-slate-200 text-slate-900 hover:border-[#0b6e3e]"
                  }`}
                >
                  <p
                    className={`text-3xl font-extrabold mb-2 ${
                      p.highlight ? "text-[#f5c400]" : "text-[#0b6e3e]"
                    }`}
                  >
                    .{p.tld}
                  </p>
                  <p
                    className={`text-sm leading-relaxed ${
                      p.highlight ? "text-slate-100/90" : "text-slate-600"
                    }`}
                  >
                    {p.desc}
                  </p>
                </div>
              </AnimateIn>
            ))}
          </div>
          <div className="text-center mt-10">
            <button
              type="button"
              onClick={() => {
                document
                  .getElementById("domain-faq")
                  ?.scrollIntoView({ behavior: "smooth" });
              }}
              className="inline-flex items-center gap-2 text-[#0b6e3e] font-semibold hover:underline"
            >
              Not sure which TLD to pick? Read the FAQ
              <ChevronDown className="w-4 h-4" />
            </button>
          </div>
        </div>
      </section>

      {/* Benefits */}
      <section className="bg-slate-50 py-14 md:py-20">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn>
            <div className="text-center max-w-2xl mx-auto mb-10">
              <h2 className="text-2xl md:text-4xl font-extrabold text-slate-900 mb-3">
                Every domain includes
              </h2>
              <p className="text-slate-600">
                We bundle the essentials, so you don't pay extra for features
                you should already have.
              </p>
            </div>
          </AnimateIn>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            {[
              {
                icon: ShieldCheck,
                title: "Free DNS Management",
                desc: "Fast global anycast DNS with unlimited records, included free.",
              },
              {
                icon: Zap,
                title: "Instant Activation",
                desc: "Most domains go live within minutes of registration — no waiting.",
              },
              {
                icon: Wallet,
                title: "Transparent Pricing",
                desc: "No hidden fees, no surprise renewals. You see the full price upfront.",
              },
              {
                icon: HeartHandshake,
                title: "24/7 Expert Support",
                desc: "Talk to a real person any time via ticket, email or our support portal.",
              },
            ].map((b, i) => (
              <AnimateIn key={b.title} delay={i * 0.05}>
                <div className="h-full bg-white rounded-2xl border border-slate-200 p-6 hover:-translate-y-1 hover:shadow-lg transition">
                  <div className="w-12 h-12 rounded-xl bg-[#0b6e3e]/10 text-[#0b6e3e] flex items-center justify-center mb-4">
                    <b.icon className="w-6 h-6" />
                  </div>
                  <h3 className="text-lg font-bold text-slate-900 mb-1.5">
                    {b.title}
                  </h3>
                  <p className="text-sm text-slate-600 leading-relaxed">
                    {b.desc}
                  </p>
                </div>
              </AnimateIn>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section id="domain-faq" className="bg-white py-14 md:py-20">
        <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
          <AnimateIn>
            <div className="text-center mb-10">
              <h2 className="text-2xl md:text-4xl font-extrabold text-slate-900 mb-3">
                Frequently Asked Questions
              </h2>
              <p className="text-slate-600">
                Everything you need to know about registering and managing your
                domain with us.
              </p>
            </div>
          </AnimateIn>
          <div className="space-y-3">
            {FAQ.map((item, idx) => {
              const isOpen = openFaq === idx;
              return (
                <AnimateIn key={item.q} delay={idx * 0.03}>
                  <div
                    className={`rounded-2xl border transition ${
                      isOpen
                        ? "border-[#0b6e3e] bg-emerald-50/40"
                        : "border-slate-200 bg-white"
                    }`}
                  >
                    <button
                      type="button"
                      onClick={() => setOpenFaq(isOpen ? null : idx)}
                      className="w-full flex items-center justify-between gap-4 text-left px-5 py-4"
                    >
                      <span className="font-semibold text-slate-900">
                        {item.q}
                      </span>
                      <ChevronDown
                        className={`w-5 h-5 text-[#0b6e3e] transition-transform shrink-0 ${
                          isOpen ? "rotate-180" : ""
                        }`}
                      />
                    </button>
                    {isOpen && (
                      <div className="px-5 pb-5 text-slate-600 leading-relaxed">
                        {item.a}
                      </div>
                    )}
                  </div>
                </AnimateIn>
              );
            })}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="relative overflow-hidden bg-gradient-to-br from-[#0b6e3e] to-[#063019] text-white py-14 md:py-20">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <AnimateIn>
            <h2 className="text-2xl md:text-4xl font-extrabold mb-3">
              Got a name in mind? Grab it before someone else does.
            </h2>
            <p className="text-slate-100/90 mb-8 max-w-2xl mx-auto">
              Every great website starts with a great domain. Search now and
              secure yours in minutes.
            </p>
            <button
              type="button"
              onClick={() =>
                document
                  .querySelector("input[type=text]")
                  ?.scrollIntoView({ behavior: "smooth", block: "center" })
              }
              className="inline-flex items-center gap-2 px-8 py-3.5 rounded-xl bg-[#f5c400] text-slate-900 font-bold hover:bg-yellow-400 transition"
            >
              <Search className="w-5 h-5" />
              Search another domain
            </button>
          </AnimateIn>
        </div>
      </section>
    </SiteLayout>
  );
}