import { useEffect, useState } from "react";
import { useApp } from "../AppContext";
import { banners, categories, type Banner } from "@/mocks/dshn";
import {
  guestBusinesses,
  guestOpportunityCategories,
  guestOpportunities,
  guestTicker,
} from "@/mocks/dshnGuestHome";
import { SeekingBadge } from "../components/BusinessCard";
import ProductCard from "../components/ProductCard";
import AutoMarquee from "@/components/feature/AutoMarquee";
import { products } from "@/mocks/dshnCommerce";
import { Chip, SectionHeader, cn } from "../components/ui";

function fmt(n: number) {
  return n.toLocaleString("en-US");
}

/* ---------------- News ticker ---------------- */
function GuestTicker() {
  const items = [...guestTicker, ...guestTicker];
  return (
    <div className="h-10 bg-secondary-100 flex items-center overflow-hidden">
      <div className="h-full shrink-0 flex items-center gap-1 bg-secondary-500 px-3 z-10">
        <i className="ri-flashlight-fill text-[13px] leading-none text-secondary-950" />
        <span className="text-[11px] font-bold text-secondary-950 whitespace-nowrap">
          آخر التدشينات
        </span>
      </div>
      <div className="flex-1 overflow-hidden">
        <div className="flex items-center w-max animate-ticker">
          {items.map((t, i) => (
            <span key={`${t}-${i}`} className="flex items-center">
              <span className="px-3 text-[12px] font-medium text-secondary-900 whitespace-nowrap">
                {t}
              </span>
              <span className="w-1 h-1 rounded-full bg-secondary-700/50 shrink-0" />
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

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

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

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

  return (
    <div className="px-4">
      <div
        dir="ltr"
        className="relative w-full h-[180px] rounded-[20px] 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)}
              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-5 flex flex-col justify-center">
                <span className="self-start rounded-full bg-secondary-500 text-secondary-950 text-[10.5px] font-bold px-2.5 py-1 mb-2 whitespace-nowrap">
                  {b.tag}
                </span>
                <h3 className="text-[19px] font-bold text-background-50 leading-snug max-w-[72%]">
                  {b.title}
                </h3>
                <p className="text-[12.5px] text-background-50/90 mt-1 max-w-[72%]">{b.subtitle}</p>
              </div>
            </button>
          ))}
        </div>
      </div>
      <div className="flex items-center justify-center gap-1.5 mt-3">
        {banners.map((b, i) => (
          <button
            key={b.id}
            type="button"
            aria-label={`الشريحة ${i + 1}`}
            onClick={() => setIndex(i)}
            className={cn(
              "h-1.5 rounded-full transition-all cursor-pointer",
              i === index ? "w-5 bg-foreground-950" : "w-1.5 bg-background-300",
            )}
          />
        ))}
      </div>
    </div>
  );
}

/* ---------------- Category circles ---------------- */
function CategoryCircles() {
  const { navigate } = useApp();
  return (
    <div className="flex gap-4 overflow-x-auto no-scrollbar px-4 pb-1">
      {categories.map((c) => (
        <button
          key={c.id}
          type="button"
          onClick={() => navigate("products", { categoryId: c.id })}
          className="shrink-0 flex flex-col items-center gap-2 w-[80px] cursor-pointer"
        >
          <span className="w-[72px] h-[72px] rounded-full overflow-hidden bg-background-100 border border-background-200">
            <img src={c.image} alt={c.name} className="w-full h-full object-cover object-top" />
          </span>
          <span className="text-[12.5px] text-foreground-700 text-center leading-tight">
            {c.name}
          </span>
        </button>
      ))}
    </div>
  );
}

/* ---------------- Opportunities & offers ---------------- */
function Opportunities() {
  const { navigate } = useApp();
  const cats = guestOpportunityCategories;
  const [cat, setCat] = useState(cats[0]);

  return (
    <div>
      <SectionHeader
        title="العروض والفرص"
        actionLabel="عرض الكل"
        onAction={() => navigate("businesses")}
        className="px-4"
      />
      <div className="flex gap-2 overflow-x-auto no-scrollbar px-4 mt-3">
        {cats.map((c) => (
          <Chip key={c} active={c === cat} onClick={() => setCat(c)}>
            {c}
          </Chip>
        ))}
      </div>

      <div className="mt-3 pb-1">
        <AutoMarquee speed={54}>
          {guestOpportunities.map((o) => (
          <button
            key={o.id}
            type="button"
            onClick={() => navigate("business")}
            className="shrink-0 w-[272px] text-start rounded-[20px] bg-background-100 border border-background-200 p-4 cursor-pointer hover:border-background-300 transition-colors"
          >
            <div className="flex items-center gap-3">
              <span className="w-11 h-11 rounded-full overflow-hidden bg-background-200 shrink-0">
                <img src={o.logo} alt={o.name} className="w-full h-full object-cover object-top" />
              </span>
              <h3 className="text-[14.5px] font-semibold text-foreground-950 leading-tight">
                {o.name}
              </h3>
            </div>

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

            <div className="mt-3 pt-3 border-t border-background-200 grid grid-cols-2 gap-2">
              <div className="rounded-[12px] bg-background-200 px-2.5 py-2 text-center">
                <p className="text-[10px] text-foreground-600 whitespace-nowrap">قيمة الاستثمار</p>
                <p className="text-[13px] font-bold text-foreground-950 mt-0.5 whitespace-nowrap">
                  {fmt(o.investValue)} ر.س
                </p>
              </div>
              <div className="rounded-[12px] bg-secondary-100 px-2.5 py-2 text-center">
                <p className="text-[10px] font-semibold text-secondary-900 whitespace-nowrap">
                  النسبة المعروضة
                </p>
                <p className="text-[15px] font-bold text-secondary-900 leading-tight mt-0.5">
                  {o.equity}%
                </p>
              </div>
            </div>
          </button>
        ))}
        </AutoMarquee>
      </div>
    </div>
  );
}

/* ---------------- Products ---------------- */
function GuestProducts() {
  const { navigate } = useApp();
  const list = products.slice(0, 6);

  return (
    <div>
      <SectionHeader
        title="المنتجات"
        actionLabel="عرض الكل"
        onAction={() => navigate("products")}
        className="px-4"
      />
      <div data-product-shop className="grid grid-cols-2 gap-3 px-4 mt-3 pb-1">
        {list.map((p) => (
          <ProductCard
            key={p.id}
            product={p}
            onClick={() => navigate("product", { productId: p.id })}
            onClickBusiness={() => navigate("business", { businessId: p.businessId })}
          />
        ))}
      </div>
    </div>
  );
}

/* ---------------- Businesses ---------------- */
function BusinessStrip() {
  const { navigate } = useApp();

  return (
    <div>
      <SectionHeader
        title="المنشآت"
        actionLabel="عرض الكل"
        onAction={() => navigate("businesses")}
        className="px-4"
      />
      <div className="mt-3 pb-1">
        <AutoMarquee speed={58}>
          {guestBusinesses.map((b) => (
          <button
            key={b.id}
            type="button"
            onClick={() => navigate("business", { businessId: b.id })}
            className="shrink-0 w-[252px] text-start bg-background-100 border border-background-200 rounded-[20px] p-4 cursor-pointer hover:border-background-300 transition-colors"
          >
            <div className="flex items-center gap-3">
              <span className="w-12 h-12 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-[14px] font-semibold text-foreground-950 leading-tight">
                  {b.name}
                </h3>
                <p className="text-[11px] text-foreground-600 mt-0.5 leading-tight">
                  {b.activity} • {b.city}
                </p>
              </div>
            </div>

            <div className="mt-3 space-y-1.5">
              <div className="flex items-center justify-between gap-2 text-[11px]">
                <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-[11px]">
                <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-3">
                <SeekingBadge />
              </div>
            )}
          </button>
        ))}
        </AutoMarquee>
      </div>
    </div>
  );
}

export default function GuestHome() {
  return (
    <div className="pb-6">
      <GuestTicker />
      <div className="pt-4 space-y-6">
        <BannerCarousel />
        <CategoryCircles />
        <GuestProducts />
        <Opportunities />
        <BusinessStrip />
      </div>
    </div>
  );
}