import { useEffect, useState } from "react";
import { banners, businesses, categories } from "@/mocks/dshn";
import { guestOpportunityCategories } from "@/mocks/dshnGuestHome";
import { investorOpportunities } from "@/mocks/dshnInvestor";
import { products } from "@/mocks/dshnCommerce";
import { useWeb } from "../WebContext";
import AutoMarquee from "@/components/feature/AutoMarquee";
import { Container, SectionHead, WCard, cn, fmt } from "../WebUI";

const CAT_NAMES: Record<string, string> = {
  food: "أغذية ومشروبات",
  electronics: "إلكترونيات",
  fashion: "أزياء",
  beauty: "منتجات تجميل",
  industrial: "منتجات صناعية",
  furniture: "أثاث",
  services: "خدمات",
  digital: "منتجات رقمية",
};

const HERO_STATS = [
  { value: "1,250+", label: "منشأة مسجّلة" },
  { value: "8,400+", label: "منتج معروض" },
  { value: "340+", label: "فرصة استثمارية" },
];

/* ---------------- Hero ---------------- */
function Hero() {
  const { jump } = useWeb();
  return (
    <section className="relative rounded-[28px] overflow-hidden bg-primary-950">
      <img
        src="https://readdy.ai/api/search-image?query=Abstract%20premium%20fintech%20brand%20background%20with%20deep%20charcoal%20black%20and%20warm%20cream%20geometric%20shapes%2C%20subtle%20mint%20teal%20accents%2C%20soft%20gradient%2C%20elegant%20minimal%20composition%2C%20generous%20negative%20space%2C%20no%20text&width=1400&height=760&seq=dshn-web-hero-brand&orientation=landscape"
        alt="منصة دشن الرقمية"
        className="absolute inset-0 w-full h-full object-cover object-top"
      />
      <div className="absolute inset-0 bg-gradient-to-l from-black/85 via-black/60 to-black/25" />

      <div className="relative px-6 md:px-14 py-14 md:py-20">
        <div className="max-w-[640px]">
          <span className="inline-flex items-center gap-1.5 rounded-full bg-secondary-500 text-secondary-950 px-3.5 py-1.5 text-[12px] font-bold whitespace-nowrap">
            <i className="ri-flashlight-fill text-[13px] leading-none" />
            منصة دشن الرقمية
          </span>
          <h1 className="text-[34px] md:text-[50px] leading-[1.15] font-bold text-background-50 font-heading mt-5">
            منصة واحدة تجمع منشأتك ومنتجاتك وفرص الاستثمار
          </h1>
          <p className="text-[15px] md:text-[17px] text-background-50/85 mt-5 leading-relaxed max-w-[520px]">
            دشن تربط أصحاب البيزنس بالمستثمرين والعملاء في مكان واحد، بتجربة رقمية حديثة تناسب السوق السعودي.
          </p>

          <div className="flex flex-wrap items-center gap-3 mt-8">
            <button
              type="button"
              onClick={() => jump("authSelect")}
              className="h-12 px-7 rounded-[16px] bg-secondary-500 text-secondary-950 text-[15px] font-bold hover:bg-secondary-400 transition-colors cursor-pointer whitespace-nowrap active:scale-[0.99]"
            >
              ابدأ الآن
            </button>
            <button
              type="button"
              onClick={() => jump("businesses")}
              className="h-12 px-7 rounded-[16px] bg-background-50/10 border border-background-50/30 text-background-50 text-[15px] font-semibold hover:bg-background-50/20 transition-colors cursor-pointer whitespace-nowrap"
            >
              استكشف المنشآت
            </button>
          </div>

          <div className="flex flex-wrap items-center gap-x-10 gap-y-4 mt-10">
            {HERO_STATS.map((s) => (
              <div key={s.label}>
                <p className="text-[26px] font-bold text-background-50 font-heading leading-none">{s.value}</p>
                <p className="text-[12.5px] text-background-50/70 mt-1.5">{s.label}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ---------------- Promotional banners ---------------- */
function BannerCarousel() {
  const { navigate } = useWeb();
  const [index, setIndex] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setIndex((i) => (i + 1) % banners.length), 5000);
    return () => clearInterval(id);
  }, []);

  const open = (action: string, refId: string) => {
    if (action === "business") navigate("business", { businessId: refId });
    else if (action === "product") navigate("product", { productId: refId });
    else navigate("products", { categoryId: refId });
  };

  return (
    <div className="relative">
      <div dir="ltr" className="relative w-full h-[360px] rounded-[24px] overflow-hidden bg-background-200">
        <div
          className="flex h-full transition-transform duration-500 ease-out"
          style={{ transform: `translateX(-${index * 100}%)` }}
        >
          {banners.map((b) => (
            <button
              key={b.id}
              type="button"
              dir="rtl"
              onClick={() => open(b.action, b.refId)}
              className="relative w-full h-full shrink-0 text-start cursor-pointer"
            >
              <img src={b.image} alt={b.title} className="w-full h-full object-cover object-top" />
              <div className="absolute inset-0 bg-gradient-to-l from-foreground-950/80 via-foreground-950/45 to-foreground-950/5" />
              <div className="absolute inset-0 p-10 flex flex-col justify-center">
                <span className="self-start rounded-full bg-secondary-500 text-secondary-950 text-[12px] font-bold px-3.5 py-1.5 mb-3 whitespace-nowrap">
                  {b.tag}
                </span>
                <h3 className="text-[32px] font-bold text-background-50 leading-snug max-w-[60%] font-heading">{b.title}</h3>
                <p className="text-[15px] text-background-50/90 mt-2 max-w-[60%]">{b.subtitle}</p>
              </div>
            </button>
          ))}
        </div>

        <button
          type="button"
          aria-label="السابق"
          onClick={() => setIndex((i) => (i - 1 + banners.length) % banners.length)}
          className="absolute top-1/2 -translate-y-1/2 left-4 w-11 h-11 rounded-full bg-background-50/85 backdrop-blur flex items-center justify-center text-foreground-950 hover:bg-background-50 cursor-pointer"
        >
          <i className="ri-arrow-left-s-line text-[22px] leading-none" />
        </button>
        <button
          type="button"
          aria-label="التالي"
          onClick={() => setIndex((i) => (i + 1) % banners.length)}
          className="absolute top-1/2 -translate-y-1/2 right-4 w-11 h-11 rounded-full bg-background-50/85 backdrop-blur flex items-center justify-center text-foreground-950 hover:bg-background-50 cursor-pointer"
        >
          <i className="ri-arrow-right-s-line text-[22px] leading-none" />
        </button>
      </div>

      <div className="flex items-center justify-center gap-1.5 mt-4">
        {banners.map((b, i) => (
          <button
            key={b.id}
            type="button"
            aria-label={`الشريحة ${i + 1}`}
            onClick={() => setIndex(i)}
            className={cn("h-2 rounded-full transition-all cursor-pointer", i === index ? "w-7 bg-primary-500" : "w-2 bg-background-300")}
          />
        ))}
      </div>
    </div>
  );
}

/* ---------------- Category circles ---------------- */
function CategoryCircles() {
  const { jump } = useWeb();
  return (
    <div className="flex items-start justify-between gap-3">
      {categories.map((c) => (
        <button
          key={c.id}
          type="button"
          onClick={() => jump("products", { categoryId: c.id })}
          className="flex flex-col items-center gap-3 cursor-pointer group flex-1"
        >
          <span className="w-[92px] h-[92px] rounded-full overflow-hidden bg-background-100 border border-background-200 group-hover:border-foreground-400 transition-colors">
            <img src={c.image} alt={c.name} className="w-full h-full object-cover object-top" />
          </span>
          <span className="text-[13px] font-medium text-foreground-800 group-hover:text-foreground-950 text-center leading-tight">
            {c.name}
          </span>
        </button>
      ))}
    </div>
  );
}

/* ---------------- Product grid ---------------- */
function ProductSection() {
  const { navigate } = useWeb();
  const list = products.slice(0, 8);

  return (
    <section>
      <SectionHead title="المنتجات" actionLabel="عرض الكل" onAction={() => navigate("products")} />
      <div data-product-shop className="grid grid-cols-2 lg:grid-cols-4 gap-5">
        {list.map((p) => {
          const biz = businesses.find((b) => b.id === p.businessId);
          const out = p.stock === 0;
          return (
            <WCard key={p.id} className={cn("overflow-hidden", out && "opacity-60")} onClick={() => navigate("product", { productId: p.id })}>
              <div className="w-full aspect-square bg-background-200">
                <img src={p.image} alt={p.name} className="w-full h-full object-cover object-top" />
              </div>
              <div className="p-4">
                <h3 className="text-[13.5px] font-semibold text-foreground-950 leading-snug line-clamp-2 h-10">{p.name}</h3>
                <div className="mt-2.5">
                  {p.negotiable || p.price === null ? (
                    <span className="inline-flex items-center rounded-full bg-secondary-100 text-secondary-900 px-3 py-1 text-[12px] font-bold">
                      السعر حسب التفاوض
                    </span>
                  ) : (
                    <span className="text-[16px] font-bold text-foreground-950">
                      {fmt(p.price)} <span className="text-[13px] font-semibold">ر.س</span>
                    </span>
                  )}
                </div>
                <div className="mt-2.5 flex flex-col gap-0.5">
                  {biz && (
                    <span className="flex items-center gap-1 text-[11.5px] text-foreground-600">
                      <i className="ri-store-2-line text-[13px] leading-none shrink-0" />
                      <span className="underline underline-offset-2 break-words text-start">{biz.name}</span>
                    </span>
                  )}
                  <span className="text-[11px] text-foreground-500">{CAT_NAMES[p.categoryId] ?? p.categoryId}</span>
                </div>
              </div>
            </WCard>
          );
        })}
      </div>
    </section>
  );
}

export default function Home() {
  const { navigate, jump } = useWeb();
  const [opCat, setOpCat] = useState(guestOpportunityCategories[0]);

  const featuredOps = investorOpportunities.slice(0, 6);
  const featuredBiz = businesses.slice(0, 6);

  return (
    <div className="animate-fade-in">
      <Container className="pt-8 space-y-14 pb-4">
        <Hero />

        <BannerCarousel />

        <CategoryCircles />

        <ProductSection />

        {/* العروض والفرص */}
        <section>
          <SectionHead title="العروض والفرص" actionLabel="عرض الكل" onAction={() => jump("opportunities")} />
          <div className="flex items-center gap-2 flex-wrap mb-5">
            {guestOpportunityCategories.map((c) => (
              <button
                key={c}
                type="button"
                onClick={() => setOpCat(c)}
                className={cn(
                  "rounded-full px-4 py-2 text-[13px] font-medium whitespace-nowrap cursor-pointer transition-colors",
                  c === opCat ? "bg-primary-500 text-background-50" : "bg-background-100 border border-background-200 text-foreground-700 hover:border-background-300",
                )}
              >
                {c}
              </button>
            ))}
          </div>

          <AutoMarquee speed={62}>
            {featuredOps.map((op) => (
              <WCard key={op.id} className="p-5 flex flex-col w-[320px] shrink-0" onClick={() => navigate("opportunity", { opportunityId: op.id })}>
                <div className="flex items-center gap-3">
                  <span className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
                    <img src={op.businessLogo} alt={op.businessName} className="w-full h-full object-cover object-top" />
                  </span>
                  <h3 className="text-[15px] font-semibold text-foreground-950 leading-tight">{op.businessName}</h3>
                </div>

                <div className="mt-4 flex items-center justify-between gap-2">
                  <span className="text-[12px] text-foreground-600 whitespace-nowrap">تقييم المنشأة:</span>
                  <span className="text-[14px] font-bold text-foreground-950 whitespace-nowrap">{fmt(op.valuation)} ر.س</span>
                </div>

                <div className="mt-4 pt-4 border-t border-background-200 grid grid-cols-2 gap-2.5">
                  <div className="rounded-[14px] bg-background-200 px-2.5 py-3 text-center">
                    <p className="text-[11px] text-foreground-600 whitespace-nowrap">قيمة الاستثمار</p>
                    <p className="text-[14px] font-bold text-foreground-950 mt-1 whitespace-nowrap">{fmt(op.amount)} ر.س</p>
                  </div>
                  <div className="rounded-[14px] bg-secondary-100 px-2.5 py-3 text-center">
                    <p className="text-[11px] font-semibold text-secondary-900 whitespace-nowrap">النسبة المعروضة</p>
                    <p className="text-[16px] font-bold text-secondary-900 leading-tight mt-1">{op.equity}%</p>
                  </div>
                </div>
              </WCard>
            ))}
          </AutoMarquee>
        </section>

        {/* المنشآت */}
        <section>
          <SectionHead title="المنشآت" actionLabel="عرض الكل" onAction={() => jump("businesses")} />
          <AutoMarquee speed={66} gapClassName="gap-5">
            {featuredBiz.map((b) => (
              <WCard key={b.id} className="p-5 w-[320px] shrink-0" onClick={() => navigate("business", { businessId: b.id })}>
                <div className="flex items-center gap-3">
                  <span className="w-14 h-14 rounded-full overflow-hidden bg-background-200 shrink-0">
                    <img src={b.logo} alt={b.name} className="w-full h-full object-cover object-top" />
                  </span>
                  <div className="min-w-0">
                    <h3 className="text-[15px] font-semibold text-foreground-950 leading-tight">{b.name}</h3>
                    <p className="text-[12px] text-foreground-600 mt-0.5 leading-tight">
                      {b.activity} • {b.city}
                    </p>
                  </div>
                </div>

                <div className="mt-4 space-y-2">
                  <div className="flex items-center justify-between gap-2 text-[12px]">
                    <span className="text-foreground-600 whitespace-nowrap flex items-center gap-1" title="تقييم تقديري لقيمة المنشأة يُستخدم من المستثمرين لتقييم الفرصة">
                      التقييم السوقي
                      <i className="ri-information-line text-[11px] leading-none text-foreground-400" />
                    </span>
                    <span className="font-semibold text-foreground-900 whitespace-nowrap">{fmt(b.estimatedValue)} ر.س</span>
                  </div>
                  <div className="flex items-center justify-between gap-2 text-[12px]">
                    <span className="text-foreground-600 whitespace-nowrap">حجم المبيعات</span>
                    <span className="font-semibold text-foreground-900 whitespace-nowrap">{fmt(b.annualSales)} ر.س</span>
                  </div>
                </div>

                {b.seekingInvest && (
                  <div className="mt-4">
                    <span className="inline-flex items-center gap-1 rounded-full bg-secondary-100 text-secondary-900 px-2.5 py-1 text-[11px] font-bold whitespace-nowrap">
                      <i className="ri-seedling-line text-[12px] leading-none" />
                      تبحث عن استثمار
                    </span>
                  </div>
                )}
              </WCard>
            ))}
          </AutoMarquee>
        </section>
      </Container>
    </div>
  );
}