import "server-only";
import Link from "next/link";
import type { LucideIcon } from "lucide-react";
import { Lock, UserCheck, ArrowRight, Sparkles } from "lucide-react";
import { auth } from "@/lib/auth/auth";
import { Container } from "@/components/Container";

export type AccessTile = {
  href: string;
  label: string;
  description: string;
  Icon: LucideIcon;
};

type Props = {
  /** Short product label shown in the eyebrow, e.g. "Atlas" / "OrthoPrep". */
  productName: string;
  /** One-line description used in the guest hint. */
  productTagline: string;
  /** Quick-access tiles shown to signed-in members. 2–4 items works best. */
  tiles: AccessTile[];
  /**
   * When true, the product is members-only — guests see the sign-in strip and
   * the tiles are hidden. When false, tiles are shown to guests too (but with
   * the signed-in header swapped for a join prompt).
   */
  membersOnly?: boolean;
};

/**
 * Page-top rail that switches between two states:
 *
 * 1. **Member (signed in + active)** — brand-blue gradient card greeting the
 *    member by name with N quick-access tiles linking into the product's
 *    sub-routes. Replaces the need to scroll the marketing page to find the
 *    tool.
 * 2. **Guest (signed out)** — compact strip above the hero telling the guest
 *    which parts of this product need membership and pointing them at
 *    /login and /join. Still renders the tiles when `membersOnly` is false,
 *    but links them through a sign-in prompt path.
 *
 * Server component — reads the session directly so each product page stays
 * cacheable and we avoid a client-side flicker.
 */
export async function ProductAccessRail({
  productName,
  productTagline,
  tiles,
  membersOnly = false,
}: Props) {
  const session = await auth().catch(() => null);
  const user = session?.user as
    | { name?: string | null; role?: string; id?: string }
    | undefined;
  const isMember = Boolean(user?.id);

  if (isMember) {
    return (
      <section className="bg-white pt-6 md:pt-8">
        <Container>
          <div className="relative overflow-hidden rounded-2xl bg-[var(--color-blue)] text-white shadow-[0_24px_56px_-24px_rgba(30,64,255,0.45)]">
            <div
              aria-hidden
              className="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_at_top_right,rgba(255,255,255,0.18),transparent_58%),radial-gradient(ellipse_at_bottom_left,rgba(255,255,255,0.08),transparent_55%)]"
            />
            <div
              aria-hidden
              className="pointer-events-none absolute inset-0 opacity-[0.07]"
              style={{
                backgroundImage:
                  "linear-gradient(to right, white 1px, transparent 1px), linear-gradient(to bottom, white 1px, transparent 1px)",
                backgroundSize: "40px 40px",
              }}
            />

            <div className="relative flex flex-wrap items-center justify-between gap-3 border-b border-white/15 px-5 py-3.5 md:px-8">
              <div className="flex items-center gap-2">
                <span className="flex h-6 w-6 items-center justify-center rounded-full bg-white/15 text-white ring-1 ring-inset ring-white/25">
                  <UserCheck className="h-3.5 w-3.5" aria-hidden />
                </span>
                <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-white/85">
                  Member access · {productName}
                </span>
              </div>
              {user?.name && (
                <span className="text-[12px] font-semibold text-white/80">
                  Signed in as{" "}
                  <span className="text-white">{user.name}</span>
                </span>
              )}
            </div>

            <div className="relative grid gap-px bg-white/15 sm:grid-cols-2 lg:grid-cols-4">
              {tiles.map((tile) => (
                <Link
                  key={tile.href}
                  href={tile.href}
                  className="group flex flex-col gap-2 bg-[var(--color-blue)] px-5 py-6 transition-colors hover:bg-[var(--color-blue-deep)] md:px-6"
                >
                  <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-white/15 text-white ring-1 ring-inset ring-white/20">
                    <tile.Icon className="h-[18px] w-[18px]" aria-hidden />
                  </span>
                  <span className="font-display text-[16px] font-extrabold leading-tight tracking-tight text-white">
                    {tile.label}
                  </span>
                  <span className="text-[12px] leading-snug text-white/80">
                    {tile.description}
                  </span>
                  <span className="mt-auto inline-flex items-center gap-1 pt-1 text-[12px] font-semibold text-white/90">
                    Open
                    <ArrowRight className="h-3 w-3 transition-transform group-hover:translate-x-0.5" aria-hidden />
                  </span>
                </Link>
              ))}
            </div>
          </div>
        </Container>
      </section>
    );
  }

  // Guest state — slim sign-in strip above the marketing hero.
  return (
    <section className="bg-white pt-6 md:pt-8">
      <Container>
        <div className="flex flex-wrap items-center gap-4 rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/50 px-5 py-4 md:px-6">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-white text-[var(--color-blue)] ring-1 ring-[var(--color-line)]">
            {membersOnly ? (
              <Lock className="h-[18px] w-[18px]" aria-hidden />
            ) : (
              <Sparkles className="h-[18px] w-[18px]" aria-hidden />
            )}
          </span>
          <div className="min-w-0 flex-1">
            <div className="text-[11px] font-bold uppercase tracking-[0.18em] text-[var(--color-blue)]">
              {membersOnly ? "Members only" : "Sign in for full access"}
            </div>
            <p className="mt-0.5 text-[14px] leading-snug text-[var(--color-ink)]">
              {productTagline}
            </p>
          </div>
          <div className="flex shrink-0 flex-wrap items-center gap-2">
            <Link
              href="/login"
              className="inline-flex items-center rounded-lg border border-[var(--color-line)] bg-white px-4 py-2 text-[13px] font-semibold text-[var(--color-ink)] transition-colors hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
            >
              Sign in
            </Link>
            <Link
              href="/join"
              className="inline-flex items-center rounded-lg bg-[var(--color-blue)] px-4 py-2 text-[13px] font-semibold text-white shadow-sm transition-colors hover:bg-[var(--color-blue-deep)]"
            >
              Apply for membership
            </Link>
          </div>
        </div>
      </Container>
    </section>
  );
}
