"use client";

import { useState } from "react";

type Category =
  | "Giftcard"
  | "Crypto"
  | "Registration"
  | "Withdrawals"
  | "Miscellaneous";

const ALL_CATEGORIES: Category[] = [
  "Giftcard",
  "Crypto",
  "Registration",
  "Withdrawals",
  "Miscellaneous",
];

type FaqItem = {
  question: string;
  answer: string;
};

const faqsByCategory: Record<Category, FaqItem[]> = {
  Giftcard: [
    {
      question: "How do I trade my gift cards on Coast?",
      answer:
        "Select the gift card type, upload clear images or details of your card, and submit. Once verified, your payout is processed.",
    },
    {
      question: "How long does verification take?",
      answer:
        "Most gift cards are verified within minutes. In some cases, it may take slightly longer depending on the card type.",
    },
    {
      question: "When will I receive my payment?",
      answer:
        "Once your gift card is verified, your payment is processed instantly.",
    },
    {
      question: "What types of gift cards do you accept?",
      answer:
        "We support a wide range of popular gift cards, including iTunes (Apple), Steam, RazerGold, Amazon, Sephora, and more.",
    },
    {
      question: "Why are gift card rates different?",
      answer:
        "Rates depend on market demand, card type, and region. Coast ensures you always get competitive value.",
    },
    {
      question: "What happens if my card is invalid?",
      answer:
        "If your card cannot be verified, the transaction will be declined, and you’ll be notified immediately.",
    },
  ],
  Crypto: [
    {
      question: "How do I sell crypto on Coast?",
      answer:
        "Simply open the Coast app, go to Trade Crypto, and select the coin you want to sell. Choose the right network, copy your wallet address, and send the amount you want to trade to that wallet address. Once confirmed, your payout is processed instantly.",
    },
    {
      question: "How long does it take to receive my payment?",
      answer:
        "As soon as your transaction is confirmed on the blockchain, your funds are credited instantly based on your selected settlement option. This takes seconds.",
    },
    {
      question: "Where will I receive my funds?",
      answer:
        "You can choose your preferred settlement option: Bank Account – funds are sent directly to your bank. Wallet Balance – funds are credited to your Coast wallet",
    },
    {
      question: "What is the minimum amount I can trade?",
      answer:
        "The minimum trade amount is $5 per transaction.",
    },
    {
      question: "Are your crypto rates competitive?",
      answer:
        "Yes. Coast offers competitive, real-time rates so you always get great value when you trade.",
    },
    {
      question: "What cryptocurrencies can I trade?",
      answer:
        "You can trade popular cryptocurrencies like Bitcoin (BTC), Ethereum (ETH), USDT, and USDC directly on the app.",
    },
  ],
  Registration: [
    {
      question: "How do I create an account on Coast?",
      answer:
        "Download the Coast app, sign up with your email and phone number, and follow the prompts to complete your registration.",
    },
    {
      question: "Do I need any documents to register?",
      answer:
        "Yes. We ask for a valid government-issued ID and a selfie for KYC compliance. This keeps your funds safe and your account compliant.",
    },
  ],
  Withdrawals: [
    {
      question: "How do I withdraw my funds?",
      answer:
        "Once your transaction is completed, your funds are automatically paid out based on your selected settlement option.",
    },
    {
      question: "Where will I receive my money?",
      answer:
        "You can choose your preferred payout method: Bank Account — direct transfer to your bank, Wallet Balance — funds stored in your Coast wallet",
    },
    {
      question: "How long do withdrawals take?",
      answer:
        "Withdrawals are processed instantly after your transaction is confirmed.",
    },
    {
      question: "Can I change my payout method?",
      answer:
        "Yes. Go to Account → Payment Method → Change Type in Settlement Type and select your preferred settlement option.",
    },
    {
      question: "Is there a withdrawal fee?",
      answer:
        "Fees (if any) depend on the transaction type and will always be shown before you complete your trade.",
    },
    {
      question: "Why is my withdrawal delayed?",
      answer:
        "Delays may occur due to: Network congestion (for crypto transactions), Incorrect account details, Additional verification checks.",
    },
    {
      question: "What happens if I enter the wrong bank details?",
      answer:
        "Your transaction may fail or be delayed. Always double-check your details before confirming. If an issue occurs, contact support immediately.",
    },
  ],
  Miscellaneous: [
    {
      question: "Is Coast safe to use?",
      answer:
        "Yes. Coast uses secure systems and processes to ensure all transactions are safe and reliable.",
    },
    {
      question: "How do I contact support?",
      answer:
        "You can reach our support team directly through the app or via our official support channels. Email us at admin@coastresources.io or chat with us on WhatsApp at +234 911 099 2663. Most queries are resolved within minutes.",
    },
    {
      question: "Do I need to verify my account?",
      answer:
        "Yes, account verification may be required to ensure security and enable full access to features.",
    },
    {
      question: "Is there a referral program?",
      answer:
        "Yes! Invite friends with your unique referral code and earn rewards when they complete their first trade.",
    },
  ],
};

function Chevron({ open }: { open: boolean }) {
  return (
    <svg
      width="14"
      height="14"
      viewBox="0 0 14 14"
      fill="none"
      aria-hidden
      className={`transition-transform ${open ? "rotate-180" : ""}`}
    >
      <path
        d="M3 5L7 9L11 5"
        stroke="#1f5cff"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function FaqRow({
  item,
  open,
  onToggle,
}: {
  item: FaqItem;
  open: boolean;
  onToggle: () => void;
}) {
  return (
    <div className="rounded-2xl bg-white shadow-[0_2px_10px_-4px_rgba(2,16,58,0.08)]">
      <button
        type="button"
        onClick={onToggle}
        aria-expanded={open}
        className="flex w-full items-center justify-between gap-6 px-6 py-5 text-left md:px-8 md:py-6"
      >
        <span className="text-[16px] font-bold text-coast-navy md:text-[18px]">
          {item.question}
        </span>
        <span
          className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-full ${open ? "bg-coast-blue-soft" : "bg-coast-blue-soft/60"
            }`}
        >
          <Chevron open={open} />
        </span>
      </button>
      <div
        className={`grid transition-all duration-300 ${open ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
          }`}
      >
        <div className="overflow-hidden">
          <p className="whitespace-pre-line px-6 pb-6 text-[15px] leading-relaxed text-coast-navy/85 md:px-8 md:pb-7 md:text-base">
            {item.answer}
          </p>
        </div>
      </div>
    </div>
  );
}

export default function FAQTabs({
  showHeading = false,
  categories = ALL_CATEGORIES,
}: {
  showHeading?: boolean;
  categories?: Category[];
}) {
  const [activeCategory, setActiveCategory] = useState<Category>(categories[0]);
  const [openIndex, setOpenIndex] = useState<number | null>(0);

  const items = faqsByCategory[activeCategory];

  return (
    <section className="bg-white">
      <div className="mx-auto max-w-[920px] px-5 py-10 md:px-10">
        {showHeading && (
          <h2 className="mb-10 text-center text-[28px] font-bold text-coast-navy md:mb-12 md:text-[36px]">
            Frequently Asked Questions
          </h2>
        )}

        <div className="flex w-full overflow-x-auto rounded-full border border-coast-blue/15 bg-white p-1 shadow-[0_10px_30px_-12px_rgba(2,16,58,0.18)] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
          {categories.map((cat) => {
            const isActive = activeCategory === cat;
            return (
              <button
                key={cat}
                type="button"
                onClick={() => {
                  setActiveCategory(cat);
                  setOpenIndex(0);
                }}
                className={`flex-1 whitespace-nowrap rounded-full px-5 py-3 text-[14px] font-semibold transition md:text-[15px] ${isActive
                  ? "bg-coast-blue text-white"
                  : "text-coast-navy hover:bg-coast-blue-soft/40"
                  }`}
              >
                {cat}
              </button>
            );
          })}
        </div>

        <div className="mt-8 flex flex-col gap-4">
          {items.map((item, i) => (
            <FaqRow
              key={`${activeCategory}-${i}`}
              item={item}
              open={openIndex === i}
              onToggle={() => setOpenIndex(openIndex === i ? null : i)}
            />
          ))}
        </div>
      </div>
    </section>
  );
}
