"use client";

import Image from "next/image";
import { useEffect, useState } from "react";

type TopMarket = {
  id: string;
  assetTitle: string;
  crypto: string;
  price: number;
};

type Benefit = {
  title: string;
  description: string;
  cardBg: string;
  imageSrc?: string;
  imageAlt?: string;
};

const benefits: Benefit[] = [
  {
    title: "Instant Payout",
    description:
      "Get your money when you need it. Transfers and withdrawals are processed instantly, so you're never stuck waiting days to access your funds.",
    cardBg: "#D8E9FF",
    imageSrc: "/assets/images/instant.png",
    imageAlt: "Payment complete notification",
  },
  {
    title: "24/7 Dedicated support",
    description:
      "Day or night, our support team is always available to help you resolve issues, answer questions, and keep your transactions running smoothly.",
    cardBg: "#D5F0DD",
    imageSrc: "/assets/images/support.png",
    imageAlt: "Customer support contact card",
  },
  {
    title: "Safe and Secure",
    description:
      "Your money and data are protected with bank-grade security, encrypted transactions, and multi-layer authentication.",
    cardBg: "#E5DEFF",
    imageSrc: "/assets/images/secure.png",
    imageAlt: "100% Secure badge",
  },
  {
    title: "Easy to use Interface",
    description:
      "No clutter. No confusion. Coast.ng is designed to be simple and intuitive, so you can send, receive, and manage money in just a few taps.",
    cardBg: "#F5F7C8",
    imageSrc: "/assets/images/interface.png",
    imageAlt: "Wallet interface preview",
  },
  {
    title: "Upgrade Your Limits Easily",
    description:
      "Need higher limits? Upgrade your account seamlessly by completing verification — no paperwork, no long waits.",
    cardBg: "#D8D4FF",
    imageSrc: "/assets/images/upgrade.png",
    imageAlt: "Account level upgrade progress",
  },
  {
    title: "Best rates in the market",
    description:
      "Enjoy competitive exchange rates with full transparency. What you see is what you get — no hidden fees, no surprises.",
    cardBg: "#C8EBE0",
    imageAlt: "Bitcoin and Tether exchange rates",
  },
];

function RateRow({
  icon,
  name,
  ticker,
  price,
}: {
  icon: string;
  name: string;
  ticker: string;
  price: number | null;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <div className="flex items-center gap-3">
        <Image src={icon} alt={name} width={36} height={36} className="h-9 w-9 shrink-0" />
        <div>
          <p className="text-[14px] font-semibold text-coast-ink">{name}</p>
          <p className="text-[11px] font-medium text-coast-ink/50">{ticker}</p>
        </div>
      </div>
      <p className="text-[14px] font-bold text-coast-ink">
        {price !== null ? `${price.toLocaleString("en-US")}/$` : "—"}
      </p>
    </div>
  );
}

function BestRatesIllustration({ btc, usdt }: { btc: TopMarket | undefined; usdt: TopMarket | undefined }) {
  return (
    <div className="relative h-full w-full">
      <Image
        src="/assets/images/bestrate.png"
        alt=""
        fill
        aria-hidden
        className="object-cover object-center"
        sizes="(max-width: 768px) 100vw, (max-width: 1280px) 33vw, 400px"
      />
      <div className="relative z-10 flex h-full flex-col justify-center px-6 py-6">
        <div className="rounded-2xl bg-white p-4 shadow-[0_10px_30px_-12px_rgba(5,26,71,0.18)]">
          <p className="mb-4 text-[13px] font-semibold text-coast-ink">Showing best rates</p>
          <div className="flex flex-col gap-4">
            <RateRow
              icon="/assets/images/btc.png"
              name="Bitcoin"
              ticker="BTC"
              price={btc ? btc.price : null}
            />
            <RateRow
              icon="/assets/images/tether.png"
              name="Tether USD"
              ticker="USDT"
              price={usdt ? usdt.price : null}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

function BenefitCard({
  benefit,
  illustration,
}: {
  benefit: Benefit;
  illustration?: React.ReactNode;
}) {
  return (
    <article>
      <div
        className="relative aspect-[4/3] w-full overflow-hidden rounded-3xl"
        style={{ backgroundColor: benefit.cardBg }}
      >
        {illustration ?? (benefit.imageSrc ? (
          <Image
            src={benefit.imageSrc}
            alt={benefit.imageAlt ?? ""}
            fill
            quality={95}
            sizes="(max-width: 768px) 100vw, (max-width: 1280px) 33vw, 400px"
            className="object-cover"
          />
        ) : (
          <div className="flex h-full w-full items-center justify-center text-[12px] text-coast-ink/50">
            illustration →
          </div>
        ))}
      </div>
      <h3 className="mt-5 text-[18px] font-bold text-white md:text-[20px]">
        {benefit.title}
      </h3>
      <p className="mt-2 text-[14px] leading-relaxed text-white/65 md:text-[15px]">
        {benefit.description}
      </p>
    </article>
  );
}

export default function Benefits() {
  const [markets, setMarkets] = useState<TopMarket[]>([]);

  useEffect(() => {
    fetch("https://web-api.coast.ng/crypto/top-markets")
      .then((res) => res.json())
      .then((json) => setMarkets(json.data ?? []))
      .catch(() => { });
  }, []);

  const btc = markets.find((m) => m.crypto === "BTC");
  const usdt = markets.find((m) => m.crypto === "USDT");

  return (
    <section className="bg-coast-navy text-white">
      <div className="mx-auto max-w-[1280px] px-5 py-16 md:px-0 md:py-14">
        <div className="mx-auto max-w-[700px] text-center">
          <h2 className="text-[28px] font-bold leading-tight md:text-[36px]">
            The best platform to trade your digital assets for instant cash
          </h2>
          <p className="mt-4 text-[15px] leading-relaxed text-white/70 md:text-base">
            At Coast, we are 100% committed to providing you swift and secured exchange of your
            digital assets and cryptocurrencies.
          </p>
        </div>

        <div className="mt-12 grid gap-8 sm:grid-cols-2 md:gap-10 lg:grid-cols-3">
          {benefits.map((benefit) =>
            benefit.title === "Best rates in the market" ? (
              <BenefitCard
                key={benefit.title}
                benefit={benefit}
                illustration={<BestRatesIllustration btc={btc} usdt={usdt} />}
              />
            ) : (
              <BenefitCard key={benefit.title} benefit={benefit} />
            )
          )}
        </div>
      </div>
    </section>
  );
}
