import { useWeb } from "@/pages/web/WebContext";
import { Container, cn, fmt } from "@/pages/web/WebUI";
import InvHeader from "@/pages/web/components/InvHeader";
import InvFooter from "@/pages/web/components/InvFooter";
import {
  invHomeTicker,
  invHomeFeatured,
  invHomeSeeking,
  type InvHomeOpportunity,
  type InvHomeBusiness,
} from "@/mocks/dshnInvHome";

const HERO_IMAGE =
  "https://readdy.ai/api/search-image?query=Abstract%20luxury%20dark%20background%20with%20flowing%20golden%20silk%20waves%20and%20soft%20glowing%20bokeh%20particles%2C%20deep%20charcoal%20and%20warm%20amber%20gold%20tones%2C%20elegant%20premium%20fintech%20hero%20visual%2C%20cinematic%20soft%20lighting%2C%20rich%20high%20contrast%20surface%20for%20white%20text%20overlay%2C%20minimal%2C%20no%20text&width=1920&height=1080&seq=dshn-inv-hero-gold&orientation=landscape";

export default function InvHome() {
  const { jump, navigate } = useWeb();

  return (
    <div className="animate-fade-in bg-background-50">
      <InvHeader />

      {/* HERO */}
      <section className="relative w-full overflow-hidden">
        <div className="absolute inset-0">
          <img src={HERO_IMAGE} alt="دشن" className="w-full h-full object-cover object-top" />
          <div className="absolute inset-0 bg-gradient-to-b from-black/55 via-black/45 to-black/70" />
        </div>

        <div className="relative z-10 pt-10 pb-14">
          <Container>
            <Ticker />
          </Container>

          <Container className="mt-12">
            <p className="text-[13px] text-background-50/60">مرحبًا بك</p>
            <h1 className="text-[40px] md:text-[52px] leading-[1.12] font-bold text-background-50 font-heading mt-2">
              أهلًا فيصل
            </h1>
            <p className="text-[15px] md:text-[17px] text-background-50/80 mt-4 max-w-[560px] leading-relaxed">
              اكتشف الفرص الاستثمارية والمنشآت الواعدة في مختلف القطاعات.
            </p>
            <div className="flex flex-wrap items-center gap-3 mt-8">
              <button
                type="button"
                onClick={() => jump("invOpps")}
                className="h-[52px] px-7 rounded-[14px] bg-background-50 text-foreground-950 text-[15px] font-semibold flex items-center gap-2 hover:bg-background-100 transition-colors cursor-pointer whitespace-nowrap"
              >
                <i className="ri-line-chart-line text-[18px] leading-none" />
                الفرص الاستثمارية
              </button>
              <button
                type="button"
                onClick={() => jump("businesses")}
                className="h-[52px] px-7 rounded-[14px] bg-background-50/10 border border-background-50/40 text-background-50 text-[15px] font-semibold flex items-center gap-2 hover:bg-background-50/20 transition-colors cursor-pointer whitespace-nowrap"
              >
                <i className="ri-store-2-line text-[18px] leading-none" />
                المنشآت
              </button>
            </div>
          </Container>
        </div>
      </section>

      {/* FEATURED OPPORTUNITIES */}
      <section className="bg-background-50 py-14">
        <Container>
          <SectionHead title="الفرص المميزة" onViewAll={() => jump("invOpps")} />
          <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-5">
            {invHomeFeatured.map((op) => (
              <OpportunityCard
                key={op.id}
                op={op}
                onOpen={() => navigate("invOpp", { opportunityId: op.opportunityId })}
              />
            ))}
          </div>
        </Container>
      </section>

      {/* SEEKING INVESTMENT */}
      <section className="bg-background-100 py-14">
        <Container>
          <SectionHead title="المنشآت الباحثة عن استثمار" onViewAll={() => jump("businesses")} />
          <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-5">
            {invHomeSeeking.map((b) => (
              <BusinessCard
                key={b.id}
                biz={b}
                onOpen={() => navigate("business", { businessId: b.businessId })}
              />
            ))}
          </div>
        </Container>
      </section>

      <InvFooter />
    </div>
  );
}

/* ------------------------------------------------------------------ */

function Ticker() {
  const items = [...invHomeTicker, ...invHomeTicker];
  return (
    <div className="flex items-center gap-2 rounded-full bg-background-50/10 border border-background-50/15 backdrop-blur overflow-hidden h-11">
      <div className="flex items-center gap-1.5 bg-secondary-500 text-secondary-950 px-4 self-stretch shrink-0">
        <i className="ri-flashlight-fill text-[15px] leading-none" />
        <span className="text-[12px] font-bold whitespace-nowrap">آخر التدشينات</span>
      </div>
      <div className="flex-1 overflow-hidden">
        <div className="flex items-center gap-6 animate-ticker w-max">
          {items.map((n, i) => (
            <span
              key={`${n.id}-${i}`}
              className="flex items-center gap-6 text-[12.5px] text-background-50 whitespace-nowrap"
            >
              {n.text}
              <span className="w-1.5 h-1.5 rounded-full bg-secondary-500" />
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

function SectionHead({ title, onViewAll }: { title: string; onViewAll: () => void }) {
  return (
    <div className="flex items-end justify-between gap-4 mb-6">
      <h2 className="text-[24px] md:text-[27px] font-bold text-foreground-950 font-heading">
        <a href="#" onClick={(e) => e.preventDefault()} className="cursor-default">
          {title}
        </a>
      </h2>
      <button
        type="button"
        onClick={onViewAll}
        className="flex items-center gap-1 text-[13.5px] font-semibold text-foreground-600 hover:text-foreground-950 cursor-pointer whitespace-nowrap"
      >
        عرض الكل
        <i className="ri-arrow-left-line text-[16px] leading-none" />
      </button>
    </div>
  );
}

function OpportunityCard({ op, onOpen }: { op: InvHomeOpportunity; onOpen: () => void }) {
  return (
    <article
      onClick={onOpen}
      className="bg-background-100 border border-background-200 rounded-[20px] p-5 flex flex-col transition-colors hover:border-background-300 cursor-pointer"
    >
      <div className="flex items-center gap-3">
        <div className="w-12 h-12 rounded-full overflow-hidden bg-background-200 shrink-0">
          <img src={op.logo} alt={op.businessName} className="w-full h-full object-cover object-top" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-1.5">
            <h3 className="text-[15px] font-semibold text-foreground-950 truncate">{op.businessName}</h3>
            {op.verified && (
              <i className="ri-verified-badge-fill text-accent-600 text-[15px] leading-none shrink-0" />
            )}
          </div>
          <p className="text-[11.5px] text-foreground-600 mt-0.5 truncate">
            {op.activity} • {op.city}
          </p>
        </div>
      </div>

      <div className="flex flex-wrap items-center gap-2 mt-4">
        <span className="inline-flex items-center rounded-full bg-background-200 text-foreground-700 px-2.5 py-1 text-[11px] font-semibold whitespace-nowrap">
          {op.categoryBadge}
        </span>
        <span
          className={cn(
            "inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold whitespace-nowrap",
            op.statusTone === "mint" ? "bg-accent-100 text-accent-800" : "bg-secondary-100 text-secondary-900",
          )}
        >
          {op.statusBadge}
        </span>
      </div>

      <div className="grid grid-cols-2 gap-2.5 mt-4">
        <div className="rounded-[14px] bg-background-200/70 p-3">
          <p className="text-[10.5px] text-foreground-600 leading-snug">مبلغ الاستثمار المطلوب</p>
          <p className="text-[14.5px] font-bold text-foreground-950 mt-1">{fmt(op.amount)} ر.س</p>
        </div>
        <div className="rounded-[14px] bg-secondary-50 p-3">
          <p className="text-[10.5px] text-foreground-600 leading-snug">نسبة الملكية المعروضة</p>
          <p className="text-[14.5px] font-bold text-secondary-900 mt-1">{op.equity}%</p>
        </div>
      </div>

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

      {op.coinvest && (
        <div className="mt-4">
          <div className="flex items-center justify-between text-[11.5px] mb-1.5">
            <span className="text-accent-800 font-semibold">تم جمع {op.coinvest.percent}%</span>
            <span className="font-semibold text-foreground-900">
              {fmt(op.coinvest.collected)} / {fmt(op.coinvest.target)} ر.س
            </span>
          </div>
          <div className="h-2 rounded-full bg-accent-100 overflow-hidden">
            <div
              className="h-full bg-accent-500 rounded-full"
              style={{ width: `${op.coinvest.percent}%` }}
            />
          </div>
          <p className="flex items-center gap-1.5 text-[11.5px] text-foreground-600 mt-2.5">
            <i className="ri-time-line text-[14px] leading-none" />
            ينتهي خلال {op.coinvest.daysLeft} يوم
          </p>
        </div>
      )}

      <button
        type="button"
        onClick={(e) => {
          e.stopPropagation();
          onOpen();
        }}
        className="mt-5 w-full h-11 rounded-[12px] bg-primary-500 text-background-50 text-[13.5px] font-semibold hover:bg-primary-600 transition-colors cursor-pointer whitespace-nowrap active:scale-[0.99]"
      >
        عرض الفرصة
      </button>
    </article>
  );
}

function BusinessCard({ biz, onOpen }: { biz: InvHomeBusiness; onOpen: () => void }) {
  return (
    <article
      onClick={onOpen}
      className="bg-background-100 border border-background-200 rounded-[20px] p-5 flex flex-col transition-colors hover:border-background-300 cursor-pointer"
    >
      <div className="flex items-center gap-3">
        <div className="w-14 h-14 rounded-full overflow-hidden bg-background-200 shrink-0">
          <img src={biz.logo} alt={biz.name} className="w-full h-full object-cover object-top" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-1.5">
            <h3 className="text-[15px] font-semibold text-foreground-950 truncate">{biz.name}</h3>
            {biz.verified && (
              <span className="inline-flex items-center gap-0.5 rounded-full bg-accent-100 text-accent-800 px-2 py-0.5 text-[10px] font-bold whitespace-nowrap shrink-0">
                <i className="ri-checkbox-circle-fill text-[11px] leading-none" />
                موثّق
              </span>
            )}
          </div>
          <p className="text-[11.5px] text-foreground-600 mt-0.5 truncate">
            {biz.activity} • {biz.city}
          </p>
        </div>
      </div>

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

      <div className="mt-4 pt-4 border-t border-background-200">
        <span className="inline-flex items-center gap-1.5 rounded-full bg-secondary-100 text-secondary-900 px-3 py-1.5 text-[11.5px] font-bold whitespace-nowrap">
          <i className="ri-seedling-line text-[14px] leading-none" />
          تبحث عن استثمار
        </span>
      </div>
    </article>
  );
}