import { Link } from "@tanstack/react-router";
import { ArrowUpRight, Calendar, EyeOff, Flag, Shield, Users } from "lucide-react";
import { CflMark } from "@/components/cfl-mark";
import { DisneyWalkCard } from "@/components/stadium/disney-walk";
import { BioLink } from "@/components/public-shell";
import { HonorGiftForm } from "@/components/honor-gift";
import { OpenDealRoom } from "@/components/stadium/deal-room";
import { StaffEditField } from "@/components/staff-edit";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { MISSION_TEXT, ORG_TYPE } from "@/lib/constants";
import { firstName } from "@/lib/identity";
import { useRoleStore } from "@/lib/role-store";
import type { PublicPerson, PublicTeam, PublicGameDay } from "@/lib/server/api-public";
import { formatDateTime } from "@/lib/utils";

export function PublicLanding({
  teams,
  bios,
  events,
}: {
  teams: PublicTeam[];
  bios: PublicPerson[];
  events: PublicGameDay[];
}) {
  const signedIn = useRoleStore((s) => s.signedIn);
  const role = useRoleStore((s) => s.role);
  const account = useRoleStore((s) => s.account());
  const publicMember = role === "public" && signedIn;

  return (
    <div className="stagger-in space-y-10">
      {publicMember ? (
        <section className="club-hero">
          <p className="text-[11px] font-medium tracking-[0.18em] text-primary uppercase">Public member desk</p>
          <h2 className="mt-2 font-display text-3xl">Welcome, {firstName(account.name)}</h2>
          <p className="mt-2 max-w-2xl text-sm text-muted-foreground sm:text-base">
            You are signed in as a public member — a fan and supporter. This is the same catalog anyone on the web can
            see: published teams, bios athletes choose to share, and open Game Days. Donor briefings, student
            coursework, and the grant-scout desk stay off this view.
          </p>
          <div className="mt-5 grid gap-3 sm:grid-cols-3">
            <div className="rounded-lg bg-muted/70 px-4 py-3">
              <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Teams</p>
              <p className="mt-1 font-display text-3xl tabular leading-none">{teams.length}</p>
              <p className="mt-1 text-xs text-muted-foreground">Public studio projects</p>
            </div>
            <div className="rounded-lg bg-muted/70 px-4 py-3">
              <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Bios</p>
              <p className="mt-1 font-display text-3xl tabular leading-none">{bios.length}</p>
              <p className="mt-1 text-xs text-muted-foreground">Athletes who opted in</p>
            </div>
            <div className="rounded-lg bg-muted/70 px-4 py-3">
              <p className="text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">Game days</p>
              <p className="mt-1 font-display text-3xl tabular leading-none">{events.length}</p>
              <p className="mt-1 text-xs text-muted-foreground">Open to the public</p>
            </div>
          </div>
          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div>
              <p className="text-[11px] font-medium tracking-[0.16em] text-primary uppercase">You can see</p>
              <ul className="mt-2 space-y-1 text-sm text-muted-foreground">
                <li>Studio teams and public project notes</li>
                <li>Bios only when the athlete publishes them</li>
                <li>Open Game Days on the public calendar</li>
                <li>How to become a donor or enroll</li>
              </ul>
            </div>
            <div>
              <p className="flex items-center gap-1.5 text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">
                <EyeOff className="size-3.5" />
                You cannot see
              </p>
              <ul className="mt-2 space-y-1 text-sm text-muted-foreground">
                <li>Donor-only project briefings</li>
                <li>Special sideline invites to Game Days</li>
                <li>Courses, assignments, or the coach roster</li>
                <li>Grant scout, pipeline, or the staff inbox</li>
              </ul>
            </div>
          </div>
        </section>
      ) : null}

      <section className="public-hero">
        <img src="/brand/cfl-hero.jpg" alt="" />
        <div className="public-hero-copy">
          <CflMark variant="hero" />
          <p className="mt-4 text-[11px] font-medium tracking-[0.18em] text-primary uppercase">Public view · {ORG_TYPE}</p>
          <h1 className="mt-3 max-w-2xl font-display text-3xl font-semibold text-sidebar-foreground sm:text-4xl lg:text-5xl">
            The ventures athletes build. The bios they choose to share.
          </h1>
          <p className="mt-3 max-w-xl text-sm text-sidebar-muted sm:text-base">
            Capital Forge League takes no equity in participant ventures. Enrollment is open. A bio appears here only
            when the athlete publishes it.
          </p>
          <div className="mt-6 flex flex-wrap gap-2">
            <Button asChild>
              <Link to="/public/stadium/$arena" params={{ arena: "football" }} search={{ walk: true }}>
                Walk into the stadium
                <ArrowUpRight className="size-4" />
              </Link>
            </Button>
            <Button asChild variant="secondary">
              <Link to="/public/teams">
                See the teams
              </Link>
            </Button>
            {publicMember ? (
              <Button asChild variant="secondary">
                <Link to="/login">Donor login</Link>
              </Button>
            ) : (
              <>
                <Button asChild variant="secondary">
                  <Link to="/login">Public login</Link>
                </Button>
                <Button asChild variant="outline">
                  <Link to="/login">Donor login</Link>
                </Button>
              </>
            )}
          </div>
        </div>
      </section>

      <p className="max-w-3xl text-sm leading-relaxed text-muted-foreground">{MISSION_TEXT}</p>

      <DisneyWalkCard audience="public" />


      <section>
        <div className="mb-4 flex items-end justify-between gap-3">
          <div>
            <p className="text-[11px] font-medium tracking-[0.16em] text-primary uppercase">Studio projects</p>
            <h2 className="font-display text-3xl">Teams on the field</h2>
          </div>
          <Link to="/public/teams" className="text-sm text-primary hover:underline">
            All teams
          </Link>
        </div>
        <div className="grid gap-4 lg:grid-cols-2">
          {teams.map((team) => (
            <TeamCard key={team.id} team={team} />
          ))}
        </div>
      </section>

      <section>
        <div className="mb-4 flex items-end justify-between gap-3">
          <div>
            <p className="text-[11px] font-medium tracking-[0.16em] text-primary uppercase">Published bios</p>
            <h2 className="font-display text-3xl">Athletes who opted in</h2>
          </div>
        </div>
        <Card>
          <CardContent className="pt-5">
            <ul className="divide-y divide-border">
              {bios.map((p) => (
                <li key={p.member_id} className="flex flex-col gap-2 py-3 first:pt-0 last:pb-0 sm:flex-row sm:items-center sm:justify-between">
                  <div className="flex min-w-0 items-center gap-3">
                    <span className="flex size-10 shrink-0 items-center justify-center rounded-full bg-secondary text-sm font-semibold">
                      {p.avatar_initials}
                    </span>
                    <div className="min-w-0">
                      <p className="font-medium">{p.full_name}</p>
                      <p className="truncate text-sm text-muted-foreground">
                        {[p.position, p.sport, p.school].filter(Boolean).join(" · ")}
                      </p>
                    </div>
                  </div>
                  <BioLink slug={p.public_slug} publicBio={p.public_bio} />
                </li>
              ))}
            </ul>
            {bios.length === 0 ? (
              <p className="text-sm text-muted-foreground">No public bios have been published yet.</p>
            ) : null}
          </CardContent>
        </Card>
      </section>

      <section className="grid gap-4 lg:grid-cols-3">
        <Card className="lg:col-span-2">
          <CardContent className="pt-5">
            <div className="mb-3 flex items-center gap-2">
              <Calendar className="size-4 text-primary" />
              <h2 className="font-display text-xl">Upcoming Game Days</h2>
            </div>
            <ul className="space-y-3">
              {events.map((e) => (
                <li key={e.id}>
                  <p className="text-sm font-semibold">{e.title}</p>
                  <p className="text-xs text-muted-foreground">
                    {formatDateTime(e.starts_at)} · {e.location}
                  </p>
                  {e.notes ? <p className="mt-1 text-sm text-muted-foreground">{e.notes}</p> : null}
                </li>
              ))}
              {events.length === 0 ? (
                <li className="text-sm text-muted-foreground">No public Game Days are on the board yet.</li>
              ) : null}
            </ul>
            <Button asChild variant="outline" className="mt-4">
              <Link to="/public/game-days">Full calendar</Link>
            </Button>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <div className="mb-3 flex items-center gap-2">
              <Shield className="size-4 text-primary" />
              <h2 className="font-display text-xl">For donors</h2>
            </div>
            <p className="text-sm text-muted-foreground">
              Donors who log in see featured project briefings and special invites to Game Days. The public page never
              shows a private bio.
            </p>
            <Button asChild className="mt-4 w-full">
              <Link to="/login">Open donor login</Link>
            </Button>
          </CardContent>
        </Card>
      </section>
    </div>
  );
}

export function TeamCard({ team, deep }: { team: PublicTeam; deep?: boolean }) {
  const signedIn = useRoleStore((s) => s.signedIn);
  const account = useRoleStore((s) => s.account());
  const filledName = signedIn ? account.name : undefined;
  const filledEmail = signedIn && account.role !== "public" ? account.email : signedIn ? account.email : undefined;
  return (
    <Card>
      <CardContent className="pt-5">
        <div className="mb-3 flex flex-wrap items-center gap-2">
          <Badge>{team.category}</Badge>
          {team.stage_label ? <Badge variant="outline">{team.stage_label}</Badge> : null}
        </div>
        <div className="flex items-start justify-between gap-3">
          <div className="min-w-0">
            <div className="flex items-center gap-2">
              <Flag className="size-4 text-primary" />
              <h3 className="font-display text-2xl">{team.name}</h3>
            </div>
            <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{team.venture_summary}</p>
            <div className="mt-2 flex flex-wrap gap-2">
              <StaffEditField table="teams" id={team.id} field="venture_summary" value={team.venture_summary} label="public summary" />
              <StaffEditField table="teams" id={team.id} field="public_impact" value={team.public_impact} label="public impact" />
            </div>
            {team.public_impact ? (
              <p className="mt-2 text-sm">{team.public_impact}</p>
            ) : null}
          </div>
        </div>
        <p className="mt-3 text-xs font-medium tracking-wide text-muted-foreground uppercase">
          CFL takes no equity · {team.yard_points} team points
        </p>
        {team.capstone_slug ? (
          <OpenDealRoom slug={team.capstone_slug} label={`Open ${team.name} deal room`} />
        ) : null}
        <HonorGiftForm
          email={filledEmail}
          donorName={filledName}
          projectName={team.name}
          teamId={team.id}
          professorExample={team.name.toLowerCase().includes("helmet") ? "Dr. Priya Shah" : "Dana Ortiz, Head coach"}
        />
        <Button asChild variant="outline" size="sm" className="mt-3">
          <Link to="/public/stadium">Watch in the stadium</Link>
        </Button>
        <ul className="mt-4 space-y-2">
          {team.roster.map((p) => (
            <li key={p.member_id} className="flex items-center gap-2.5">
              <span className="flex size-8 items-center justify-center rounded-full bg-secondary text-xs font-semibold">
                {p.avatar_initials}
              </span>
              <span className="min-w-0 flex-1 truncate text-sm">
                {p.full_name}
                {p.position ? <span className="text-muted-foreground"> · {p.position}</span> : null}
              </span>
              <BioLink slug={p.public_slug} publicBio={p.public_bio} />
            </li>
          ))}
        </ul>
        {deep && team.updates.length > 0 ? (
          <div className="mt-5 border-t border-border pt-4">
            <p className="mb-2 text-[11px] font-medium tracking-[0.16em] text-muted-foreground uppercase">
              Public notes
            </p>
            <ul className="space-y-3">
              {team.updates.map((u) => (
                <li key={u.id}>
                  <p className="text-sm font-semibold">{u.title}</p>
                  <p className="text-sm text-muted-foreground">{u.body}</p>
                </li>
              ))}
            </ul>
          </div>
        ) : null}
        {!deep ? (
          <Button asChild variant="outline" className="mt-4 w-full">
            <Link to="/public/teams/$slug" params={{ slug: team.slug }}>
              Open project
              <ArrowUpRight className="size-4" />
            </Link>
          </Button>
        ) : null}
      </CardContent>
    </Card>
  );
}

export function RosterNote() {
  return (
    <p className="flex items-start gap-2 text-sm text-muted-foreground">
      <Users className="mt-0.5 size-4 shrink-0 text-primary" />
      A Bio link appears only when the athlete has published their bio to this public view.
    </p>
  );
}
