"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Header from "@/sections/Header";
import Hero from "@/sections/Hero";
import Product from "@/sections/Product";
import ProudProjects from "@/sections/ProudProjects";
import Pricing from "@/sections/Pricing";
import Stats from "@/sections/Stats";
import Security from "@/sections/Security";
import FAQ from "@/sections/FAQ";
import Contact from "@/sections/Contact";
import ScrollProgress from "@/components/ScrollProgress";
import { GrainOverlay } from "@/components/GrainOverlay";

const LANDING_SECTIONS = [
  Hero,
  Stats,
  Product,
  Pricing,
  ProudProjects,
  Security,
  FAQ,
  Contact,
] as const;

/** Subdomains of oxyfinz.com that are allowed to show the landing page. */
const OXY_SUBDOMAINS_SHOW_LANDING = ["nfs", "akaza"];

function isTenantSubdomainOxy(hostname: string): boolean {
  if (typeof hostname !== "string") return false;
  const normalized = hostname.replace(/^www\./i, "");
  if (!normalized.endsWith(".oxyfinz.com")) return false;
  if (normalized === "oxyfinz.com") return false;
  const sub = normalized.replace(/\.oxyfinz\.com$/i, "");
  return !OXY_SUBDOMAINS_SHOW_LANDING.includes(sub);
}

function App() {
  const router = useRouter();
  const [shouldShowLanding, setShouldShowLanding] = useState<boolean | null>(null);

  useEffect(() => {
    const hostname = window.location.hostname ?? "";
    if (isTenantSubdomainOxy(hostname)) {
      router.replace("/login");
      return;
    }
    setShouldShowLanding(true);
  }, [router]);

  if (shouldShowLanding === null) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-white">
        <div className="h-10 w-10 animate-spin rounded-full border-2 border-[#428B4D] border-t-transparent" />
      </div>
    );
  }

  return (
    <div className="relative bg-white min-h-screen">
      <GrainOverlay />
      <ScrollProgress />
      <Header />

      <main className="relative">
        {LANDING_SECTIONS.map((Section, index) => (
          <Section key={index} />
        ))}
      </main>
    </div>
  );
}

export default App;
