import { useMemo, useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import {
  ArrowRight,
  Check,
  CloudDownload,
  FileCheck2,
  Mail,
  ShieldCheck,
  CreditCard,
  Layers,
  Building2,
  Workflow,
  Landmark,
} from "lucide-react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { toast } from "sonner";
import { SiteHeader } from "@/components/site-header";
import { SiteFooter } from "@/components/site-footer";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { CATEGORIES, PRODUCTS, money, type Category, type Product } from "@/lib/catalog";
import { useCart } from "@/lib/cart";
import { COMPANY } from "@/lib/company";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Phoenix Clarity — Operational Systems & Workspaces for B2B Teams" },
      {
        name: "description",
        content:
          "50 digital templates, website kits, marketing resources and business tools for growing companies. Instant digital delivery, secure PayPal checkout.",
      },
      { property: "og:title", content: "Phoenix Clarity — Operational Systems for Growing Teams" },
      {
        property: "og:description",
        content: "Business toolkits, SOPs and financial models built to streamline modern digital companies.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: Store,
});

type Sort = "popular" | "price-asc" | "price-desc";

function ProductCard({ p, onOpen }: { p: Product; onOpen: () => void }) {
  const cart = useCart();
  const inCart = cart.has(p.id);
  return (
    <div className="group flex flex-col rounded-xl border border-border bg-card p-5 shadow-[var(--shadow-card)] transition-colors hover:border-primary/40">
      <div className="flex items-center justify-between gap-2">
        <Badge variant="secondary" className="font-medium">{p.category}</Badge>
        {p.tier === "Enterprise" && (
          <span className="text-[11px] font-semibold uppercase tracking-wider text-primary">Enterprise</span>
        )}
      </div>
      <button onClick={onOpen} className="mt-4 text-left">
        <h3 className="text-[15px] font-semibold leading-snug group-hover:text-primary">{p.title}</h3>
      </button>
      <p className="mt-2 flex-1 text-sm leading-relaxed text-muted-foreground">{p.summary}</p>
      <div className="mt-4 flex items-center gap-1.5 text-xs text-muted-foreground">
        <CloudDownload className="size-3.5" /> Instant Download · {p.formats.join(" ")}
      </div>
      <div className="mt-4 flex items-center justify-between border-t border-border pt-4">
        <span className="text-xl font-semibold tabular-nums">{money(p.price)}</span>
        <div className="flex gap-2">
          <Button variant="ghost" size="sm" onClick={onOpen}>Details</Button>
          <Button
            size="sm"
            variant={inCart ? "secondary" : "default"}
            onClick={() => {
              if (inCart) return cart.setOpen(true);
              cart.add(p.id);
              toast.success("Added to cart", { description: p.title });
            }}
          >
            {inCart ? "In cart" : "Add to Cart"}
          </Button>
        </div>
      </div>
    </div>
  );
}

function ProductDialog({ p, onClose }: { p: Product | null; onClose: () => void }) {
  const cart = useCart();
  return (
    <Dialog open={!!p} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
        {p && (
          <>
            <DialogHeader>
              <Badge variant="secondary" className="w-fit">{p.category}</Badge>
              <DialogTitle className="text-left text-xl leading-snug">{p.title}</DialogTitle>
              <DialogDescription className="text-left">{p.summary}</DialogDescription>
            </DialogHeader>
            <div className="space-y-5 text-sm">
              <div>
                <h4 className="font-semibold">What is included</h4>
                <ul className="mt-2 space-y-1.5">
                  {p.includes.map((i) => (
                    <li key={i} className="flex gap-2 text-muted-foreground">
                      <Check className="mt-0.5 size-4 shrink-0 text-primary" /> {i}
                    </li>
                  ))}
                </ul>
                <div className="mt-3 flex flex-wrap gap-1.5">
                  {p.formats.map((f) => (
                    <span key={f} className="rounded border border-border bg-muted px-2 py-0.5 font-mono text-xs">{f}</span>
                  ))}
                </div>
              </div>
              <div>
                <h4 className="font-semibold">License terms</h4>
                <div className="mt-2 grid gap-2 sm:grid-cols-2">
                  <div className="rounded-lg border border-primary/40 bg-accent/40 p-3">
                    <p className="font-medium">Single-user license</p>
                    <p className="mt-1 text-xs text-muted-foreground">Included. One named user, unlimited internal projects.</p>
                  </div>
                  <div className="rounded-lg border border-border p-3">
                    <p className="font-medium">Commercial team license</p>
                    <p className="mt-1 text-xs text-muted-foreground">Up to 25 seats. Email {COMPANY.email} for a team invoice.</p>
                  </div>
                </div>
              </div>
              <div className="rounded-lg bg-muted p-3 text-muted-foreground">
                <span className="font-medium text-foreground">How delivery works: </span>
                Immediate download link on receipt + backup email dispatched in under 60 seconds.
              </div>
              <div className="flex items-center justify-between border-t border-border pt-4">
                <span className="text-2xl font-semibold tabular-nums">{money(p.price)}</span>
                <Button
                  onClick={() => {
                    cart.add(p.id);
                    onClose();
                    cart.setOpen(true);
                  }}
                >
                  Buy Now <ArrowRight />
                </Button>
              </div>
            </div>
          </>
        )}
      </DialogContent>
    </Dialog>
  );
}

const TRUST = [
  { icon: CloudDownload, label: "Instant Digital Delivery (ZIP & Cloud Access)" },
  { icon: FileCheck2, label: "Enterprise-Grade Documentation" },
  { icon: ShieldCheck, label: "Secure Checkout via PayPal" },
];

const SOLUTIONS = [
  { icon: Workflow, title: "Operations", body: "SOP libraries, audits and process maps that make work repeatable." },
  { icon: Landmark, title: "Finance", body: "Unit economics, valuation and cash-flow engines built by operators." },
  { icon: Layers, title: "Workspaces", body: "Notion and Figma systems your team can adopt on day one." },
  { icon: Building2, title: "Governance", body: "Legal vaults, compliance suites and board-ready governance kits." },
];

const STEPS = [
  { icon: CreditCard, title: "Checkout securely", body: "Pay with PayPal or any major card. No account required." },
  { icon: CloudDownload, title: "Download instantly", body: "Your download link appears on the receipt screen immediately." },
  { icon: Mail, title: "Backup email in 60s", body: "Links, invoice and license are emailed to you as a permanent copy." },
];

const FAQS = [
  {
    q: "What license do I receive?",
    a: "Every purchase includes a single-user license for unlimited internal use. Commercial team licenses (up to 25 seats) are available on request. Resale or redistribution of the files is not permitted.",
  },
  {
    q: "Do I get an invoice for procurement?",
    a: `Yes. A PDF invoice issued by ${COMPANY.legalName} is emailed with your delivery. We can reissue invoices with your company name, VAT ID or PO number — email ${COMPANY.email}.`,
  },
  {
    q: "What is your refund policy?",
    a: "If a product is defective, incomplete or doesn't match its description, you can request a full refund within 14 days. See our Refund Policy for details.",
  },
  {
    q: "Which formats and tools are supported?",
    a: "Files are delivered as .xlsx (Excel & Google Sheets), .docx (Word & Google Docs), .pdf, .fig (Figma) and Notion duplicate links. Everything works on macOS, Windows and the web.",
  },
  {
    q: "How fast is delivery?",
    a: "Immediately. Your download link is shown right after payment and a backup email is dispatched in under 60 seconds.",
  },
];

function Store() {
  const [cat, setCat] = useState<Category | "All">("All");
  const [sort, setSort] = useState<Sort>("popular");
  const [active, setActive] = useState<Product | null>(null);

  const list = useMemo(() => {
    const l = PRODUCTS.filter((p) => cat === "All" || p.category === cat);
    return [...l].sort((a, b) =>
      sort === "price-asc" ? a.price - b.price : sort === "price-desc" ? b.price - a.price : b.popularity - a.popularity,
    );
  }, [cat, sort]);

  const bundles = PRODUCTS.filter((p) => p.price >= 990);

  return (
    <div className="min-h-screen bg-background">
      <SiteHeader />
      <main>
        <section className="relative overflow-hidden border-b border-border">
          <div className="bg-grid pointer-events-none absolute inset-0 opacity-40 [mask-image:radial-gradient(ellipse_at_top,black,transparent_70%)]" />
          <div className="relative mx-auto w-full max-w-7xl px-5 pb-20 pt-20 sm:pt-28">
            <Badge variant="secondary" className="mb-6">50 digital resources · Instant delivery</Badge>
            <h1 className="max-w-4xl text-4xl font-semibold leading-[1.05] sm:text-6xl">
              Scalable Operational Systems &amp; Workspaces for{" "}
              <span className="text-primary">Growing Teams</span>
            </h1>
            <p className="mt-6 max-w-2xl text-lg text-muted-foreground">
              Production-ready business toolkits, standard operating procedures (SOPs), and financial
              models built to streamline modern digital companies.
            </p>
            <div className="mt-9 flex flex-wrap gap-3">
              <Button asChild size="lg">
                <a href="#catalog">Explore Catalog <ArrowRight /></a>
              </Button>
              <Button asChild size="lg" variant="outline">
                <a href="#bundles">View Enterprise Suites</a>
              </Button>
            </div>
            <div className="mt-12 grid gap-3 sm:grid-cols-3">
              {TRUST.map((t) => (
                <div key={t.label} className="flex items-center gap-3 rounded-lg border border-border bg-card/80 px-4 py-3 text-sm">
                  <t.icon className="size-4 shrink-0 text-primary" />
                  <span className="font-medium">{t.label}</span>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section id="solutions" className="mx-auto w-full max-w-7xl scroll-mt-20 px-5 py-20">
          <h2 className="text-3xl font-semibold">Solutions by function</h2>
          <p className="mt-2 text-muted-foreground">Systems designed for every layer of a scaling company.</p>
          <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {SOLUTIONS.map((s) => (
              <div key={s.title} className="rounded-xl border border-border bg-card p-5">
                <s.icon className="size-5 text-primary" />
                <h3 className="mt-4 font-semibold">{s.title}</h3>
                <p className="mt-1.5 text-sm text-muted-foreground">{s.body}</p>
              </div>
            ))}
          </div>
        </section>

        <section id="catalog" className="scroll-mt-16 border-y border-border bg-muted/50">
          <div className="mx-auto w-full max-w-7xl px-5 py-20">
            <div className="flex flex-wrap items-end justify-between gap-4">
              <div>
                <h2 className="text-3xl font-semibold">Product catalog</h2>
                <p className="mt-2 text-muted-foreground">{list.length} systems · Prices in USD</p>
              </div>
              <Select value={sort} onValueChange={(v) => setSort(v as Sort)}>
                <SelectTrigger className="w-52 bg-card" aria-label="Sort products">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="popular">Popularity</SelectItem>
                  <SelectItem value="price-asc">Price: Low to High</SelectItem>
                  <SelectItem value="price-desc">Price: High to Low</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="mt-6 flex flex-wrap gap-2">
              {(["All", ...CATEGORIES] as const).map((c) => (
                <button
                  key={c}
                  onClick={() => setCat(c)}
                  className={
                    "rounded-full border px-3.5 py-1.5 text-sm transition-colors " +
                    (cat === c
                      ? "border-charcoal bg-charcoal text-charcoal-foreground"
                      : "border-border bg-card text-muted-foreground hover:text-foreground")
                  }
                >
                  {c}
                </button>
              ))}
            </div>
            <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {list.map((p) => (
                <ProductCard key={p.id} p={p} onOpen={() => setActive(p)} />
              ))}
            </div>
          </div>
        </section>

        <section id="bundles" className="scroll-mt-16 bg-charcoal text-charcoal-foreground">
          <div className="mx-auto w-full max-w-7xl px-5 py-20">
            <h2 className="text-3xl font-semibold">Enterprise bundles</h2>
            <p className="mt-2 max-w-2xl opacity-70">
              Complete, multi-department infrastructure for companies scaling across teams, entities and markets.
            </p>
            <div className="mt-8 grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              {bundles.map((p) => (
                <button
                  key={p.id}
                  onClick={() => setActive(p)}
                  className="rounded-xl border border-charcoal-foreground/15 p-5 text-left transition-colors hover:border-charcoal-foreground/40"
                >
                  <span className="text-xs uppercase tracking-wider opacity-60">{p.category}</span>
                  <h3 className="mt-2 font-semibold leading-snug">{p.title}</h3>
                  <p className="mt-2 text-sm opacity-70">{p.summary}</p>
                  <p className="mt-4 text-xl font-semibold tabular-nums">{money(p.price)}</p>
                </button>
              ))}
            </div>
          </div>
        </section>

        <section className="mx-auto w-full max-w-7xl px-5 py-20">
          <h2 className="text-3xl font-semibold">How instant delivery works</h2>
          <div className="mt-8 grid gap-4 md:grid-cols-3">
            {STEPS.map((s, i) => (
              <div key={s.title} className="rounded-xl border border-border bg-card p-6">
                <div className="flex items-center gap-3">
                  <span className="flex size-8 items-center justify-center rounded-md bg-secondary text-sm font-semibold text-secondary-foreground">{i + 1}</span>
                  <s.icon className="size-5 text-primary" />
                </div>
                <h3 className="mt-4 font-semibold">{s.title}</h3>
                <p className="mt-1.5 text-sm text-muted-foreground">{s.body}</p>
              </div>
            ))}
          </div>
        </section>

        <section id="faq" className="mx-auto w-full max-w-3xl scroll-mt-20 px-5 pb-24">
          <h2 className="text-center text-3xl font-semibold">Frequently asked questions</h2>
          <Accordion type="single" collapsible className="mt-8 w-full">
            {FAQS.map((item, i) => (
              <AccordionItem key={item.q} value={`item-${i}`}>
                <AccordionTrigger className="text-left text-base">{item.q}</AccordionTrigger>
                <AccordionContent className="text-sm leading-relaxed text-muted-foreground">{item.a}</AccordionContent>
              </AccordionItem>
            ))}
          </Accordion>
          <p className="mt-8 text-center text-sm text-muted-foreground">
            Still have questions?{" "}
            <Link to="/contact" className="text-primary hover:underline">Contact our team</Link>.
          </p>
        </section>
      </main>
      <ProductDialog p={active} onClose={() => setActive(null)} />
      <SiteFooter />
    </div>
  );
}
