"use client";

import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import {
  ArrowRight,
  Boxes,
  Terminal,
  Monitor,
  ShieldCheck,
  Layers,
  ExternalLink,
  Code2,
  Smartphone,
  TrendingUp,
  Cpu,
  PackageCheck,
  Globe,
  Sparkles,
  Zap,
  CheckCircle2,
  Lock
} from "lucide-react";
import { SpotlightCard } from "@/components/ui/SpotlightCard";
import { SectionCorners } from "@/components/ui/SectionCorner";
import { ShinyButton } from "@/components/ui/ShinyButton";
import { CountUp } from "@/components/ui/CountUp";
import { Marquee } from "@/components/ui/Marquee";
import { DemoModal } from "@/components/ui/DemoModal";
import { PackagesSection } from "@/components/ui/PackagesSection";
import { QuoteCalculator } from "@/components/ui/QuoteCalculator";
import { SquaresTerminal } from "@/components/ui/SquaresTerminal";
import { BlinkingSquares } from "@/components/ui/BlinkingSquares";
import { SocialProof4 } from "@/components/ui/SocialProof4";
import { Showcase6 } from "@/components/ui/Showcase6";
import { useAppStore } from "@/lib/store";
import { SaaSProduct } from "@/types";

export default function HomePage() {
  const { services, products, portfolio, siteSettings, formatPrice, t } = useAppStore();
  const [selectedProduct, setSelectedProduct] = useState<SaaSProduct | null>(null);
  const [isDemoModalOpen, setIsDemoModalOpen] = useState(false);
  const [activeSaaSTab, setActiveSaaSTab] = useState<string>("pharmacore");

  const openDemo = (product: SaaSProduct) => {
    setSelectedProduct(product);
    setIsDemoModalOpen(true);
  };

  const techLogos = [
    "Next.js 14", "TypeScript", "Supabase", "Tailwind CSS", "GSAP Animations",
    "Electron Desktop", "Flutter", "PostgreSQL", "React Native", "Redis", "Figma", "Docker"
  ];

  const currentSaaS = products.find((p) => p.slug === activeSaaSTab) || products[0];

  return (
    <div className="mx-auto flex min-h-screen w-[calc(100%-1.5rem)] max-w-[1440px] flex-col border-x border-border sm:w-[calc(100%-2.5rem)] lg:w-[calc(100%-3rem)] bg-background text-foreground">
      {/* 1. HERO SECTION (Wireframe Split Grid) */}
      <section className="relative border-b border-border overflow-hidden">
        <SectionCorners />

        <div className="grid grid-cols-1 lg:grid-cols-2">
          {/* Left Hero Column with Blinking Squares Background */}
          <div className="relative flex min-h-[480px] flex-col justify-center px-6 py-16 sm:px-10 sm:py-20 lg:min-h-[580px] lg:border-r lg:border-border lg:px-14 lg:py-24 overflow-hidden">
            <BlinkingSquares
              squareSize={18}
              gap={8}
              color="#024d37"
              maxOpacity={0.35}
              minOpacity={0.03}
              blinkProbability={0.02}
              className="opacity-60"
            />
            <div className="inline-flex items-center gap-2 rounded-full border border-border bg-muted px-4 py-1.5 text-xs font-mono font-medium text-foreground w-fit mb-8 shadow-xs">
              <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
              <span className="text-foreground tracking-wider">
                {siteSettings?.badge_kicker || t("hero.badge")}
              </span>
            </div>

            <h1 className="text-4xl font-semibold leading-[1.08] tracking-tight text-foreground sm:text-5xl lg:text-[3.6rem] xl:text-[4.3rem]">
              {siteSettings?.hero_headline || t("hero.headline")}
            </h1>

            <p className="mt-6 max-w-lg text-sm sm:text-base leading-relaxed text-muted-foreground">
              {siteSettings?.hero_subtext || t("hero.subtext")}
            </p>

            <div className="mt-10 flex flex-wrap items-center gap-4">
              <ShinyButton href="/contact" size="lg" showArrow>
                {siteSettings?.hero_cta_text || t("hero.cta_start")}
              </ShinyButton>

              <Link
                href="/packages"
                className="inline-flex items-center gap-2 rounded-full border border-border px-6 py-3.5 font-mono text-xs font-semibold uppercase tracking-[0.12em] text-foreground transition-colors hover:bg-muted"
              >
                <PackageCheck className="h-4 w-4 text-[#024d37]" />
                {t("hero.cta_packages")}
              </Link>
            </div>
          </div>

          {/* Right Hero Column: Squares Terminal Animated Component */}
          <div className="relative min-h-[480px] lg:min-h-[580px] flex items-center justify-center p-0 border-t lg:border-t-0 lg:border-l border-border bg-card/40">
            <SquaresTerminal
              direction="diagonal"
              speed={0.6}
              squareSize={38}
              borderColor="rgba(2, 77, 55, 0.25)"
              hoverFillColor="rgba(2, 77, 55, 0.7)"
            />
          </div>
        </div>
      </section>

      {/* 2. TECH STACK MARQUEE */}
      <section className="relative border-b border-border py-4 bg-card overflow-hidden">
        <Marquee pauseOnHover className="[--duration:30s]">
          {techLogos.map((tech, i) => (
            <div
              key={i}
              className="flex items-center gap-3 px-6 text-xs font-mono text-muted-foreground uppercase tracking-widest"
            >
              <span>{tech}</span>
              <span className="text-[#024d37] font-bold">/</span>
            </div>
          ))}
        </Marquee>
      </section>

      {/* 3. CORE SERVICES GRID (Clean Wireframe Blueprint) */}
      <section className="relative border-b border-border p-6 sm:p-10 lg:p-14">
        <SectionCorners />

        <div className="max-w-3xl mb-12">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-muted px-3.5 py-1 text-xs font-mono font-medium text-foreground mb-4">
            <Boxes className="h-3.5 w-3.5" />
            // {t("services.badge")}
          </div>
          <h2 className="text-3xl sm:text-4xl font-medium tracking-tight text-foreground">
            {t("services.title")}
          </h2>
          <p className="mt-3 text-sm text-muted-foreground leading-relaxed">
            {t("services.desc")}
          </p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {services.map((srv, idx) => (
            <SpotlightCard
              key={srv.id}
              className="flex flex-col justify-between space-y-6"
            >
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="font-mono text-xs text-[#024d37]">// 0{idx + 1}</span>
                  {srv.popular && (
                    <span className="rounded-full border border-[#024d37]/40 bg-[#024d37]/10 px-2.5 py-0.5 font-mono text-[10px] text-[#024d37] font-semibold">
                      Featured Pod
                    </span>
                  )}
                </div>

                <h3 className="text-xl font-bold text-foreground">{srv.title}</h3>
                <p className="text-xs text-muted-foreground leading-relaxed">{srv.tagline}</p>

                <div className="space-y-1.5 pt-3 border-t border-border font-mono text-xs">
                  {srv.features.slice(0, 3).map((f, i) => (
                    <div key={i} className="flex items-center gap-2 text-foreground/80 text-[11px]">
                      <span className="text-[#024d37]">✓</span>
                      <span className="truncate">{f}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="pt-4 border-t border-border flex items-center justify-between font-mono text-xs">
                <div>
                  <span className="text-[10px] text-muted-foreground block">{t("services.starting_from")}</span>
                  <span className="font-bold text-foreground">{formatPrice(srv.starting_price)}</span>
                </div>
                <Link
                  href="/packages"
                  className="inline-flex items-center gap-1 text-[#024d37] hover:underline"
                >
                  View Packages →
                </Link>
              </div>
            </SpotlightCard>
          ))}
        </div>
      </section>

      {/* 4. PROPRIETARY SAAS PRODUCT ECOSYSTEM */}
      <section className="relative border-b border-border p-6 sm:p-10 lg:p-14 bg-muted/20">
        <SectionCorners />

        <div className="max-w-3xl mb-10">
          <div className="inline-flex items-center gap-2 rounded-full border border-[#024d37]/40 bg-card px-3.5 py-1 text-xs font-mono font-medium text-[#024d37] mb-4">
            <span className="h-1.5 w-1.5 rounded-full bg-[#024d37] animate-pulse" />
            // {t("saas.badge")}
          </div>
          <h2 className="text-3xl sm:text-4xl font-medium tracking-tight text-foreground">
            {t("saas.title")}
          </h2>
          <p className="mt-3 text-sm text-muted-foreground leading-relaxed">
            {t("saas.desc")}
          </p>
        </div>

        {/* Product selector tabs */}
        <div className="flex gap-2 mb-8 overflow-x-auto pb-2">
          {products.map((prod) => (
            <button
              key={prod.id}
              onClick={() => setActiveSaaSTab(prod.slug)}
              className={`rounded-full px-5 py-2 font-mono text-xs uppercase tracking-wider transition-all whitespace-nowrap cursor-pointer ${activeSaaSTab === prod.slug
                ? "bg-[#024d37] text-white font-bold shadow-sm"
                : "border border-border bg-card text-muted-foreground hover:text-foreground"
                }`}
            >
              {prod.name}
            </button>
          ))}
        </div>

        {/* Active SaaS Showcase Card */}
        {currentSaaS && (
          <article className="rounded-3xl border border-border bg-card p-6 sm:p-10 glow-card-green space-y-8">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pb-4 border-b border-border">
              <div className="flex items-center gap-4">
                <div className="relative h-14 w-14 sm:h-16 sm:w-16 shrink-0 overflow-hidden rounded-2xl border border-border bg-muted/60 p-2 flex items-center justify-center">
                  <Image
                    src={currentSaaS.logo_url || "/assets/logo/logo.png"}
                    alt={`${currentSaaS.name} Logo`}
                    width={52}
                    height={52}
                    className="object-contain"
                  />
                </div>
                <div>
                  <div className="flex items-center gap-2 font-mono text-xs">
                    <span className="text-[#024d37] font-semibold">// SAAS PLATFORM SPECIFICATION</span>
                    <span className="rounded-full border border-border bg-muted px-2.5 py-0.5 text-[10px] text-foreground">
                      v{currentSaaS.version}
                    </span>
                  </div>
                  <h3 className="text-2xl sm:text-3xl font-bold tracking-tight text-foreground mt-0.5">
                    {currentSaaS.name}
                  </h3>
                  <p className="text-xs font-mono text-[#024d37]">{currentSaaS.tagline}</p>
                </div>
              </div>

              <div className="flex items-center gap-2">
                <button
                  onClick={() => openDemo(currentSaaS)}
                  className="inline-flex items-center justify-center gap-2 rounded-full bg-[#024d37] px-5 py-2.5 text-xs font-mono font-bold uppercase tracking-[0.12em] text-white shadow-md shadow-[#024d37]/20 hover:bg-[#036549] transition-all cursor-pointer"
                >
                  <Terminal className="h-3.5 w-3.5" />
                  {t("saas.live_demo")}
                </button>
              </div>
            </div>

            {/* SaaS Interface Screenshot + Features */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
              {/* Left Column: UI Screenshot Preview */}
              <div className="lg:col-span-7 space-y-2">
                <div className="relative h-[240px] sm:h-[320px] w-full overflow-hidden rounded-2xl border border-border bg-muted">
                  <Image
                    src={currentSaaS.preview_image || "/assets/services/1.png"}
                    alt={`${currentSaaS.name} Preview`}
                    fill
                    className="object-cover object-top"
                  />
                </div>
                <div className="flex items-center justify-between text-[11px] font-mono text-muted-foreground px-1">
                  <span>LIVE PRODUCTION RUNTIME</span>
                  <span className="text-[#024d37] font-semibold">100% OFFLINE CAPABLE</span>
                </div>
              </div>

              {/* Right Column: Key Details & Architecture */}
              <div className="lg:col-span-5 space-y-4">
                <div>
                  <span className="font-mono text-[11px] text-muted-foreground uppercase tracking-wider block mb-1">
                    // CORE ARCHITECTURAL CAPABILITIES:
                  </span>
                  <div className="space-y-1.5 font-mono text-xs">
                    {(currentSaaS.features || []).map((feat, i) => (
                      <div key={i} className="flex items-start gap-2 text-foreground/90 text-[11px]">
                        <span className="text-[#024d37] font-bold">✓</span>
                        <span>{feat}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="rounded-xl border border-border bg-muted/60 p-4 font-mono text-xs space-y-2">
                  <div className="flex justify-between items-center">
                    <span className="text-muted-foreground text-[11px]">{t("saas.licensing")}</span>
                    <span className="font-bold text-foreground font-sans">{formatPrice(currentSaaS.pricing_model)}</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-muted-foreground text-[11px]">{t("saas.target")}</span>
                    <span className="text-foreground text-[11px] truncate max-w-[200px]">{currentSaaS.target_audience}</span>
                  </div>
                  <div className="flex justify-between items-center pt-2 border-t border-border">
                    <span className="text-muted-foreground text-[11px]">{t("saas.tech_runtime")}</span>
                    <span className="text-[#024d37] text-[11px] font-semibold">{currentSaaS.tech_stack.join(", ")}</span>
                  </div>
                </div>
              </div>
            </div>
          </article>
        )}
      </section>

      {/* 5. FIXED-PRICE MILESTONE PACKAGES */}
      <section id="packages" className="relative border-b border-border p-6 sm:p-10 lg:p-14">
        <SectionCorners />

        <div className="max-w-3xl mb-10">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-muted px-3.5 py-1 text-xs font-mono font-medium text-foreground mb-4">
            <PackageCheck className="h-3.5 w-3.5" />
            // {t("pkg.badge")}
          </div>
          <h2 className="text-3xl sm:text-4xl font-medium tracking-tight text-foreground">
            {t("pkg.title")}
          </h2>
          <p className="mt-3 text-sm text-muted-foreground leading-relaxed">
            {t("pkg.desc")}
          </p>
        </div>

        <PackagesSection />
      </section>

      {/* 6. INTERACTIVE SCOPE & BUDGET CALCULATOR */}
      <section className="relative border-b border-border p-6 sm:p-10 lg:p-14 bg-muted/20">
        <SectionCorners />

        <div className="max-w-3xl mb-10">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-3.5 py-1 text-xs font-mono font-medium text-foreground mb-4">
            <Sparkles className="h-3.5 w-3.5" />
            // {t("calc.badge")}
          </div>
          <h2 className="text-3xl sm:text-4xl font-medium tracking-tight text-foreground">
            {t("calc.title")}
          </h2>
          <p className="mt-3 text-sm text-muted-foreground leading-relaxed">
            {t("calc.desc")}
          </p>
        </div>

        <QuoteCalculator />
      </section>

      {/* 7. PORTFOLIO & RECENT CASE STUDIES */}
      <section className="relative border-b border-border p-6 sm:p-10 lg:p-14">
        <SectionCorners />

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-10">
          <div>
            <div className="inline-flex items-center gap-2 rounded-full border border-border bg-muted px-3.5 py-1 text-xs font-mono font-medium text-foreground mb-4">
              <Layers className="h-3.5 w-3.5" />
              // {t("portfolio.badge")}
            </div>
            <h2 className="text-3xl sm:text-4xl font-medium tracking-tight text-foreground">
              {t("portfolio.title")}
            </h2>
          </div>

          <Link
            href="/portfolio"
            className="inline-flex items-center gap-1.5 font-mono text-xs text-[#024d37] hover:underline font-semibold"
          >
            {t("portfolio.all_work")} →
          </Link>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {portfolio.map((item, idx) => (
            <article
              key={item.id}
              className="rounded-3xl border border-border bg-card overflow-hidden flex flex-col justify-between hover:border-[#024d37]/50 transition-all shadow-xs group"
            >
              <div className="relative h-48 w-full overflow-hidden bg-muted border-b border-border">
                <Image
                  src={item.image || "/assets/services/2.png"}
                  alt={`${item.name} Screenshot`}
                  fill
                  className="object-cover object-top group-hover:scale-105 transition-transform duration-500"
                />
              </div>

              <div className="p-6 space-y-3 flex-1 flex flex-col justify-between">
                <div>
                  <div className="flex items-center justify-between font-mono text-xs mb-2">
                    <span className="text-[#024d37] font-semibold">// CASE_0{idx + 1}</span>
                    <span className="rounded-full border border-border bg-muted px-2 py-0.5 text-[10px] text-foreground">
                      {item.category}
                    </span>
                  </div>

                  <h3 className="text-xl font-bold text-foreground group-hover:text-[#024d37] transition-colors">{item.name}</h3>
                  <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed mt-1">
                    {item.description}
                  </p>

                  <div className="space-y-1.5 pt-3 border-t border-border font-mono text-xs">
                    {item.results.slice(0, 2).map((res, i) => (
                      <div key={i} className="flex items-center gap-2 text-foreground/90 text-[11px]">
                        <span className="text-[#024d37] font-bold">✓</span>
                        <span className="truncate">{res}</span>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="pt-4 border-t border-border flex items-center justify-between font-mono text-xs text-muted-foreground">
                  <span>{item.tech_stack.slice(0, 2).join(" • ")}</span>
                  <Link href="/portfolio" className="text-[#024d37] font-semibold hover:underline">
                    {t("portfolio.deep_study")}
                  </Link>
                </div>
              </div>
            </article>
          ))}
        </div>
      </section>

      {/* 8. SCRAPBOOK STUDIO GALLERY TEAM (React Bits Pro Showcase 6) */}
      <Showcase6 />

      {/* 9. 3-COLUMN MARQUEE WALL OF LOVE & VERIFIED REVIEWS (React Bits Pro Social Proof 4) */}
      <SocialProof4 />

      {/* 10. BOTTOM CTA CALLOUT */}
      <section className="relative p-8 sm:p-14 lg:p-20 text-center overflow-hidden bg-muted/40">
        <SectionCorners />

        <div className="max-w-2xl mx-auto space-y-6">
          <div className="inline-flex items-center gap-2 rounded-full border border-border bg-card px-4 py-1.5 text-xs font-mono text-foreground">
            <span className="h-2 w-2 rounded-full bg-[#024d37] animate-pulse" />
            {t("cta.ready_badge")}
          </div>

          <h2 className="text-3xl sm:text-5xl font-medium tracking-tight text-foreground">
            {t("cta.ready_title")}
          </h2>

          <p className="text-sm text-muted-foreground leading-relaxed">
            {t("cta.ready_sub")}
          </p>

          <div className="pt-4 flex flex-wrap items-center justify-center gap-4">
            <ShinyButton href="/contact" showArrow>
              {t("cta.start_scoping")}
            </ShinyButton>

          </div>
        </div>
      </section>

      {/* Live Interactive Simulator Modal */}
      <DemoModal
        product={selectedProduct}
        isOpen={isDemoModalOpen}
        onClose={() => setIsDemoModalOpen(false)}
      />
    </div>
  );
}
