import Link from "next/link";
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { unstable_cache } from "next/cache";
import {
  ArrowRight,
  Check,
  Plus,
  Layers,
  Sliders,
  Upload,
  Share2,
  Layout,
  Palette,
  Sparkles,
  Music,
  BarChart3,
  MessageSquare,
} from "lucide-react";
import { DISCORD_INVITE_URL, SITE_NAME, getProfilePath } from "@/lib/constants";
import { isAccountRestricted } from "@/lib/moderation";
import { createAdminClient } from "@/lib/supabase/admin";
import { createClient } from "@/lib/supabase/server";
import LandingHeroContent from "@/components/LandingHeroContent";
import ProfileComparisonSlider from "@/components/ProfileComparisonSlider";
import ScrollReveal from "@/components/ScrollReveal";
import SiteHeader from "@/components/SiteHeader";
import LandingTransferCallout from "@/components/LandingTransferCallout";
import "./landing.css";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  alternates: { canonical: "/" },
};

const CAROUSEL_BADGE_IDS = new Set(["og", "donor", "donator", "premium"]);
const CAROUSEL_LIMIT = 18;

type CarouselProfile = {
  id: string;
  username: string;
  display_name?: string | null;
  avatar_url?: string | null;
  avatar_shape?: string | null;
  premium_until?: string | null;
  spotlight_until?: string | null;
  admin_badge_ids?: string[] | null;
  badges?: unknown;
  hide_views?: boolean | null;
  moderation_status?: string | null;
  suspended_until?: string | null;
};

function hasCarouselBadge(profile: CarouselProfile): boolean {
  const granted = Array.isArray(profile.admin_badge_ids) ? profile.admin_badge_ids : [];
  if (granted.some((id) => typeof id === "string" && CAROUSEL_BADGE_IDS.has(id))) return true;
  const saved = Array.isArray(profile.badges) ? profile.badges : [];
  return saved.some((badge) => {
    const id = typeof badge === "string" ? badge : (badge as { id?: unknown })?.id;
    return typeof id === "string" && CAROUSEL_BADGE_IDS.has(id);
  });
}

let memoryCarouselFallback: CarouselProfile[] = [];

const getCachedCarouselProfiles = unstable_cache(
  async (): Promise<CarouselProfile[]> => {
    try {
      const admin = createAdminClient();
      const now = Date.now();
      const result = await admin
        .from("profiles")
        .select(
          "id, username, display_name, avatar_url, avatar_shape, premium_until, spotlight_until, admin_badge_ids, badges, hide_views, moderation_status, suspended_until"
        )
        .order("views", { ascending: false, nullsFirst: false })
        .limit(80);

      const rows = (result.data || []) as CarouselProfile[];
      return rows
        .filter((profile) => {
          if (profile.hide_views) return false;
          if (isAccountRestricted(profile.moderation_status, profile.suspended_until)) return false;
          const premium = !!profile.premium_until && Date.parse(profile.premium_until) > now;
          const spotlight = !!profile.spotlight_until && Date.parse(profile.spotlight_until) > now;
          return spotlight || premium || hasCarouselBadge(profile);
        })
        .sort((a, b) => {
          const aSpot = !!a.spotlight_until && Date.parse(a.spotlight_until) > now ? 1 : 0;
          const bSpot = !!b.spotlight_until && Date.parse(b.spotlight_until) > now ? 1 : 0;
          return bSpot - aSpot;
        })
        .slice(0, CAROUSEL_LIMIT);
    } catch (err) {
      console.error("[getCarouselProfiles] fetch error:", err);
      return [];
    }
  },
  ["landing_carousel_profiles_v2"],
  { revalidate: 300, tags: ["landing_carousel"] }
);

async function getCarouselProfiles(): Promise<CarouselProfile[]> {
  try {
    const list = await getCachedCarouselProfiles();
    if (list && list.length > 0) {
      memoryCarouselFallback = list;
      return list;
    }
  } catch (err) {
    console.error("[getCarouselProfiles] cache error:", err);
  }
  return memoryCarouselFallback;
}

function ensureCarouselItems(items: CarouselProfile[], minCount = 24): CarouselProfile[] {
  if (items.length === 0) return [];
  let result = [...items];
  while (result.length < minCount) {
    result = result.concat(items);
  }
  return result;
}

function avatarShapeStyle(shape?: string | null) {
  if (shape === "square") return { borderRadius: 8 };
  if (shape === "rounded") return { borderRadius: 22 };
  if (shape === "hexagon")
    return {
      borderRadius: 0,
      clipPath: "polygon(25% 5%,75% 5%,100% 50%,75% 95%,25% 95%,0 50%)",
    };
  if (shape === "star")
    return {
      borderRadius: 0,
      clipPath:
        "polygon(50% 0%,61% 35%,98% 35%,68% 57%,79% 91%,50% 70%,21% 91%,32% 57%,2% 35%,39% 35%)",
    };
  return { borderRadius: "50%" };
}

function carouselName(profile: { username: string; display_name?: string | null }): string {
  const raw = profile.display_name || "";
  const visible = raw.replace(/[\s\u200b\u200c\u200d\ufeff\u3164\u2800]/g, "");
  return visible ? raw : profile.username;
}

function CarouselCard({
  profile,
  decorative,
}: {
  profile: CarouselProfile;
  decorative?: boolean;
}) {
  const isImage = /^https?:\/\//.test(profile.avatar_url || "");
  return (
    <Link
      href={getProfilePath(profile.username)}
      className="landingCarouselCard"
      tabIndex={decorative ? -1 : undefined}
    >
      <span className="landingCarouselAvatar" style={avatarShapeStyle(profile.avatar_shape)}>
        {isImage ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={profile.avatar_url || ""} alt="" loading="lazy" />
        ) : (
          profile.avatar_url || "👤"
        )}
      </span>
      <span className="landingCarouselMeta">
        <strong>{carouselName(profile)}</strong>
        <small>@{profile.username}</small>
      </span>
    </Link>
  );
}

const FEATURES = [
  {
    icon: Layout,
    title: "Six layouts",
    body: "Classic, portfolio, scroll, compact, minimal, or banner. Switch whenever you feel like it.",
  },
  {
    icon: Palette,
    title: "14 fonts, your colors",
    body: "Pick a typeface and custom accent color so your page looks like you, not a generic template.",
  },
  {
    icon: Sparkles,
    title: "Effects & cursors",
    body: "Particles, glow, snow, rain, Halloween effects, custom cursors, and click sounds.",
  },
  {
    icon: Music,
    title: "Music on your page",
    body: "Embed multiple audio tracks that start when someone visits your corner of the internet.",
  },
  {
    icon: BarChart3,
    title: "Views & analytics",
    body: "See exactly how many people visited your profile and what links they clicked.",
  },
  {
    icon: MessageSquare,
    title: "Discord presence",
    body: "Show your Discord activity, local clock, and rich about section, updated in real time.",
  },
];

const FAQS: { q: string; a: string }[] = [
  {
    q: "What is " + SITE_NAME + "?",
    a: "One personal page that holds your links, socials, music, and everything else you want people to find — at a clean URL you can remember and share anywhere.",
  },
  {
    q: "Is the free plan really free?",
    a: "Yes. Everything you need to build and share a page is free forever, with no credit card required. Premium is an optional one-time upgrade for extra power.",
  },
  {
    q: "What does Premium add?",
    a: "Five customizable profile slots, custom video and image backgrounds, custom badge creator, custom click sound, image hosting, and a featured spot on the landing page.",
  },
  {
    q: "Can I see who visits?",
    a: "Your dashboard shows view counts and estimated link activity, and the public leaderboard ranks the most visited pages on the site.",
  },
  {
    q: "Does it work well on mobile?",
    a: "Every layout is built mobile-first, ensuring your profile looks sharp on phones, tablets, and wide desktop displays alike.",
  },
];

export default async function Home() {
  const cookieStore = await cookies();
  const hasAuthCookie = cookieStore.getAll().some(
    (c) =>
      c.name.startsWith("sb-") ||
      c.name.includes("supabase-auth") ||
      c.name.includes("auth-token")
  );

  let user = null;
  let username = "";
  let userBio = "a little chaos, a lot of personality.";

  if (hasAuthCookie) {
    try {
      const supabase = await createClient();
      const authResult = await supabase.auth.getUser();
      user = authResult.data?.user ?? null;
      if (user) {
        const { data: profile } = await supabase
          .from("profiles")
          .select("username, bio")
          .eq("id", user.id)
          .maybeSingle();
        if (profile?.username) {
          username = profile.username;
          if (profile.bio) userBio = profile.bio;
        }
      }
    } catch (err) {
      console.error("[Home] auth check failed:", err);
      user = null;
    }
  }

  const carouselProfiles = await getCarouselProfiles();
  const displayProfiles = ensureCarouselItems(carouselProfiles, 24);

    const faqJsonLd = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: FAQS.map((item) => ({
      "@type": "Question",
      name: item.q,
      acceptedAnswer: {
        "@type": "Answer",
        text: item.a,
      },
    })),
  };

  return (
    <main className="landingShell">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }}
      />
      <SiteHeader user={user ? { id: user.id } : null} username={username ?? undefined} activePath="/" showThemeToggle={false} />

      <div className="landingHeroWrapper">
        <div className="landingContainer">

          <section className="landingHero">
            <div className="landingHeroCopy">
              <div className="landingEyebrow">One page for everything you share</div>

              <LandingHeroContent
                initialUser={user ? { id: user.id } : null}
                initialUsername={username}
              />
            </div>

            <div className="landingHeroVisual">
              <ProfileComparisonSlider
                username={username || "you"}
                bio={userBio}
              />
            </div>
          </section>

          <section className="landingPerks" aria-label="Key highlights">
            <div className="landingPerkItem">
              <Layers />
              <div>
                <strong>5 unique profiles</strong>
                <span>A different side of you, every time.</span>
              </div>
            </div>
            <div className="landingPerkItem">
              <Sliders />
              <div>
                <strong>Every effect, unlocked</strong>
                <span>Fine-tune every little detail.</span>
              </div>
            </div>
            <div className="landingPerkItem">
              <Upload />
              <div>
                <strong>Your own assets</strong>
                <span>Fonts, cursors, sounds. All yours.</span>
              </div>
            </div>
            <div className="landingPerkItem">
              <Share2 />
              <div>
                <strong>Made to be shared</strong>
                <span>Your presence, on your terms.</span>
              </div>
            </div>
          </section>
        </div>
      </div>

      {carouselProfiles.length > 0 && (
        <section className="landingCarousel" aria-label="Featured profiles">
          <div className="landingContainer">
            <div className="landingCarouselHead">
              <div>
                <div className="landingEyebrow">Community showcase</div>
                <h2 className="landingCarouselLabel">Featured on sinss.lol</h2>
              </div>
              <Link href="/leaderboard" className="landingTextLink">
                Browse all <ArrowRight size={13} />
              </Link>
            </div>
          </div>
          <div className="landingCarouselViewport">
            <div
              className="landingCarouselTrack"
              style={{
                animationDuration: `${Math.round(displayProfiles.length * 2.2)}s`,
              }}
            >
              <div className="landingCarouselGroup">
                {displayProfiles.map((profile, idx) => (
                  <CarouselCard key={`${profile.id}-${idx}`} profile={profile} />
                ))}
              </div>
              <div className="landingCarouselGroup" aria-hidden="true">
                {displayProfiles.map((profile, idx) => (
                  <CarouselCard
                    key={`${profile.id}-repeat-${idx}`}
                    profile={profile}
                    decorative
                  />
                ))}
              </div>
            </div>
          </div>
        </section>
      )}

      <div className="landingContainer">
        <ScrollReveal>
          <LandingTransferCallout />
        </ScrollReveal>

        <section className="landingFeaturesSection" id="features">
          <ScrollReveal>
            <div className="landingSectionTop">
              <div>
                <div className="landingEyebrow">The finishing touches</div>
                <h2>Make it look like you.</h2>
              </div>
              <p>Little customizations that make a huge difference.</p>
            </div>
          </ScrollReveal>

          <ScrollReveal stagger>
            <div className="landingFeaturesGrid">
              {FEATURES.map((feature) => {
                const IconComp = feature.icon;
                return (
                  <article className="landingFeatureCard" key={feature.title}>
                    <div className="landingFeatureIconWrap">
                      <IconComp size={18} />
                    </div>
                    <h3>{feature.title}</h3>
                    <p>{feature.body}</p>
                  </article>
                );
              })}
            </div>
          </ScrollReveal>
        </section>

        <section className="landingPricingSection" id="pricing">
          <ScrollReveal>
            <div className="landingSectionTop" style={{ justifyContent: "center", textAlign: "center" }}>
              <div>
                <div className="landingEyebrow" style={{ justifyContent: "center" }}>
                  Plans & upgrades
                </div>
                <h2>Start free. Upgrade when you want more.</h2>
              </div>
            </div>
          </ScrollReveal>

          <ScrollReveal stagger>
            <div className="landingPlansGrid">
              <article className="landingPlanCard">
                <h3>Free</h3>
                <div className="landingPlanPrice">
                  $0 <small>/ forever</small>
                </div>
                <p className="landingPlanSummary">
                  Everything you need to build and share your link-in-bio page.
                </p>
                <Link href="/signup" className="landingPlanBtn freeBtn">
                  Get started free
                </Link>
                <ul className="landingPlanFeatures">
                  <li>
                    <Check size={14} /> Your own {SITE_NAME} profile
                  </li>
                  <li>
                    <Check size={14} /> Social links & bio customization
                  </li>
                  <li>
                    <Check size={14} /> Background & visual effects
                  </li>
                  <li>
                    <Check size={14} /> Up to 2 music tracks
                  </li>
                  <li>
                    <Check size={14} /> Profile views & analytics
                  </li>
                </ul>
              </article>

              <article className="landingPlanCard premiumHighlight">
                <div className="landingPlanBadge">Lifetime</div>
                <h3>Premium</h3>
                <div className="landingPlanPrice">
                  $6.99 <small>/ one-time</small>
                </div>
                <p className="landingPlanSummary">
                  Every customization tool, five profiles, and exclusive badges.
                </p>
                <Link href="/premium" className="landingPlanBtn paidBtn">
                  Explore Premium
                </Link>
                <ul className="landingPlanFeatures">
                  <li>
                    <Check size={14} /> Everything included in Free
                  </li>
                  <li>
                    <Check size={14} /> 5 fully customizable profile slots
                  </li>
                  <li>
                    <Check size={14} /> Custom video & image backgrounds
                  </li>
                  <li>
                    <Check size={14} /> Custom click sounds & avatar frames
                  </li>
                  <li>
                    <Check size={14} /> Custom badge creator & Discord role
                  </li>
                  <li>
                    <Check size={14} /> Featured spot on the landing page
                  </li>
                </ul>
              </article>
            </div>
          </ScrollReveal>
        </section>

        <section className="landingFaqSection" id="faq">
          <ScrollReveal>
            <div className="landingFaqLayout">
              <div>
                <div className="landingEyebrow">Good to know</div>
                <h2>The little details.</h2>
                <p>A few quick answers before you get started.</p>
              </div>
              <div className="landingFaqList">
                {FAQS.map((item) => (
                  <details key={item.q}>
                    <summary>
                      {item.q}
                      <Plus size={14} />
                    </summary>
                    <p>{item.a}</p>
                  </details>
                ))}
              </div>
            </div>
          </ScrollReveal>
        </section>

        <ScrollReveal>
          <section className="landingCtaBanner">
            <div>
              <div className="landingEyebrow">Ready to build your page?</div>
              <h2>Claim your username today.</h2>
              <p>Free forever, no card required, live in seconds.</p>
            </div>
            <div className="landingCtaBtns">
              {user ? (
                <Link
                  href={username ? "/dashboard" : "/claim"}
                  className="landingPrimaryBtn"
                >
                  Open dashboard <ArrowRight size={14} />
                </Link>
              ) : (
                <Link href="/signup" className="landingPrimaryBtn">
                  Get started free <ArrowRight size={14} />
                </Link>
              )}
              <a
                href={DISCORD_INVITE_URL}
                className="landingSecondaryBtn"
                target="_blank"
                rel="noreferrer"
              >
                Join our Discord
              </a>
            </div>
          </section>
        </ScrollReveal>
      </div>

      <footer className="landingFooter">
        <div className="landingContainer landingFooterInner">
          <div className="landingFooterLeft">
            <Link href="/" className="landingBrand" aria-label={`${SITE_NAME} home`}>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src="/addons/logo.svg" alt="" width={24} height={24} />
              {SITE_NAME}
            </Link>
            <span>A space to be yourself.</span>
          </div>
          <div className="landingFooterRight">
            <Link href="/#features">Features</Link>
            <Link href="/premium">Premium</Link>
            <Link href="/addons">Add-ons</Link>
            <Link href="/leaderboard">Leaderboard</Link>
            <Link href="/compare">Compare</Link>
            <Link href="/transfer">Transfer</Link>
            <a href={DISCORD_INVITE_URL} target="_blank" rel="noreferrer">
              Community
            </a>
            <Link href="/privacy">Privacy</Link>
            <Link href="/terms">Terms</Link>
            <span>© {new Date().getFullYear()} {SITE_NAME}</span>
          </div>
        </div>
      </footer>
    </main>
  );
}
