import React from "react";
import { notFound } from "next/navigation";
import CardShortDetail from "@/components/customui/CardShortDetail";
// import CreditCardApplyForm from "@/components/customui/CreditCardApplyForm";
import { headers } from "next/headers";
interface Feature {
  id: number;
  details: string;
}

interface Offer {
  id: number;
  details: string;
}

interface CreditCard {
  id: number;
  name: string;
  bankname: string;
  minSalary: number;
  annualFee: string;
  image: string;
  features: Feature[];
  offers: Offer[];
}

async function fetchCardById(id: string): Promise<CreditCard | null> {
  try {
    // Use absolute URL for server-side fetch
    //const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';

    // const res = await fetch(`${baseUrl}/api/applycard/${id}`, {
    //   cache: "no-store",
    // });
       const headersList = await headers(); // ✅ Await it
    const host = headersList.get("host");
    const protocol = headersList.get("x-forwarded-proto") || "http";
    const baseUrl = `${protocol}://${host}`;

    const res = await fetch(`${baseUrl}/api/applycard/${id}`, {
      cache: "no-store",
    });


    
    if (!res.ok) return null;
    return await res.json();
  } catch (err) {
    console.error("Failed to fetch card details:", err);
    return null;
  }
}

// Make sure to await params here as this is a server component
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const vParams = await params;
  const { id } = vParams;

  const card = await fetchCardById(id);

  if (!card) return notFound();
//const headersList = headers();
  //const referer = await (await headersList).get("referer") || "/";
  return (
    <div className="max-w-4xl mx-auto px-4 py-6 flex flex-col gap-6">
      {/* Card Display */}
      <CardShortDetail card={card} />

      {/* Application Form */}
      <div className="mt-4">
        {/* <CreditCardApplyForm cardId={card.id} cardName={card.name}  /> */}
      </div>
    </div>
  );
}
