import type { Metadata } from "next";
import Link from "next/link";
import { Users, Briefcase, Stethoscope } from "lucide-react";
import { Container } from "@/components/Container";
import { PageHeader } from "@/components/PageHeader";
import { Button } from "@/components/Button";
import { FounderAvatar } from "@/components/FounderAvatar";
import { listActiveTeamMembers } from "@/lib/team/queries";
import { getViewer } from "@/lib/auth/viewer";

export const dynamic = "force-dynamic";

export const metadata: Metadata = {
  title: "Team",
  description:
    "The OrthoGlobe team — founder Prof Mohamed A. Imam, COO Dr Atef Hassan, and the steering committee of international orthopaedic surgeons and researchers who shape the collaboration.",
};

type Member = {
  name: string;
  credentials?: string;
  role?: string;
};

const steeringCommittee: Member[] = [
  { name: "Rawad Hammad" },
  { name: "Zahra Jaffry" },
  { name: "Ahmed Gebaly" },
  { name: "Mohamed Abdo Khalafallah" },
  { name: "Antony Yiu" },
  { name: "Ahmed Negida" },
  { name: "Asser Sallam" },
  { name: "Isaac John" },
  { name: "Hassan Abdalla" },
  { name: "Paolo Consigliere" },
  { name: "Hazem S. Ghaith" },
  { name: "Tony Antonios" },
  { name: "Ziad Harb" },
  { name: "Ash Evans" },
  { name: "Amit Vats" },
  { name: "Ali Narvani" },
  { name: "Anshul Sobti" },
  { name: "Duncan Muir" },
  { name: "Parth Patel" },
];

function Avatar({ label }: { label: string }) {
  const initials = label
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, 2)
    .map((w) => w[0]?.toUpperCase() ?? "")
    .join("");
  return (
    <div
      aria-hidden
      className="flex h-14 w-14 flex-none items-center justify-center rounded-full border border-[var(--color-line)] bg-gradient-to-br from-[var(--color-mist)] to-white font-display text-[15px] font-extrabold tracking-tight text-[var(--color-blue)]"
    >
      {initials || <Users className="h-5 w-5" />}
    </div>
  );
}

function LeadCard({
  name,
  role,
  credentials,
  blurb,
  initials,
  tone,
  photo,
}: {
  name: string;
  role: string;
  credentials?: string;
  blurb: string;
  initials: string;
  tone: "blue" | "ink";
  photo?: string;
}) {
  return (
    <article className="flex flex-col rounded-2xl border border-[var(--color-line)] bg-white p-6 shadow-[0_16px_40px_rgba(10,14,40,0.06)] md:p-8">
      <FounderAvatar name={name} initials={initials} tone={tone} photo={photo} />
      <div className="mt-6">
        <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
          {role}
        </div>
        <div className="mt-2 font-display text-[24px] font-extrabold leading-tight tracking-[-0.01em] text-[var(--color-ink)]">
          {name}
        </div>
        {credentials && (
          <div className="mt-1 text-[13px] font-semibold text-[var(--color-slate)]">
            {credentials}
          </div>
        )}
        <p className="mt-4 text-[15px] leading-relaxed text-[var(--color-slate)]">
          {blurb}
        </p>
      </div>
    </article>
  );
}

export default async function TeamPage() {
  const viewer = await getViewer();
  const signedIn = viewer.signedIn;
  let dbMembers: Awaited<ReturnType<typeof listActiveTeamMembers>> = [];
  try {
    dbMembers = await listActiveTeamMembers();
  } catch {
    dbMembers = [];
  }
  const dbCommittee = dbMembers.filter((m) => m.role === "committee");
  const committee: Member[] =
    dbCommittee.length > 0
      ? dbCommittee.map((m) => ({ name: m.name, role: m.title || undefined }))
      : steeringCommittee;

  return (
    <>
      <PageHeader
        eyebrow="Team"
        title="The people behind OrthoGlobe."
        lede="OrthoGlobe is a collaborative of practising orthopaedic surgeons, trainees, and researchers working across the UK, Europe, North Africa, the Middle East, and beyond."
      />

      <section className="bg-white py-12 md:py-16">
        <Container>
          <div className="max-w-2xl">
            <div className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              <Stethoscope className="h-3.5 w-3.5" aria-hidden />
              Founder &amp; leadership
            </div>
            <h2 className="mt-3 font-display text-[30px] md:text-[38px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
              Founder and COO.
            </h2>
          </div>
          <div className="mt-10 grid gap-6 md:grid-cols-2 md:gap-8">
            <LeadCard
              role="Founder · Principal Investigator"
              name="Professor Mohamed A. Imam"
              credentials="MD, MSc, D. SportMed, ELP (Oxon), PhD, FRCS (Tr &amp; Orth)"
              blurb="Prof Imam is a consultant orthopaedic surgeon and researcher based in the United Kingdom. He founded OrthoGlobe to advance musculoskeletal practice through international multicentre studies and leads the collaboration's clinical direction and the OrthoPrep question bank."
              initials="MI"
              tone="blue"
              photo="/photos/team/imam.jpg"
            />
            <LeadCard
              role="Chief Operating Officer"
              name="Dr Atef Abdelrahman Hassan"
              credentials="Clinical Researcher · AI &amp; ML Specialist in Healthcare"
              blurb="Dr Hassan is Chief Operating Officer at OrthoGlobe, leading platform engineering, product design, and the rollout of OrthoGlobe's surgical tools across the collaboration. His research spans clinical AI and machine-learning applications in orthopaedic care."
              initials="AH"
              tone="ink"
              photo="/photos/team/atef.jpg"
            />
          </div>
        </Container>
      </section>

      <section className="bg-[var(--color-mist)] py-12 md:py-16">
        <Container>
          <div className="max-w-2xl">
            <div className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              <Briefcase className="h-3.5 w-3.5" aria-hidden />
              Steering committee
            </div>
            <h2 className="mt-3 font-display text-[30px] md:text-[38px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
              {committee.length} surgeons &amp; researchers guiding the collaboration.
            </h2>
            <p className="mt-4 text-[16px] leading-relaxed text-[var(--color-slate)]">
              The steering committee shapes OrthoGlobe's research agenda, reviews
              protocols, and mentors early-career investigators across participating
              sites.
            </p>
          </div>
          <ul className="mt-10 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            {committee.map((m) => (
              <li
                key={m.name}
                className="flex items-center gap-4 rounded-xl border border-[var(--color-line)] bg-white p-4"
              >
                <Avatar label={m.name} />
                <div className="min-w-0">
                  <div className="font-display text-[15px] font-extrabold tracking-tight text-[var(--color-ink)]">
                    {m.name}
                  </div>
                  <div className="text-[12px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                    Steering committee
                  </div>
                </div>
              </li>
            ))}
          </ul>
          <p className="mt-8 text-[13px] text-[var(--color-slate)]">
            Full biographies, institutions, and headshots are added as each
            committee member supplies them through the admin portal.
          </p>
        </Container>
      </section>

      <section className="bg-white py-12 md:py-16">
        <Container>
          <div className="max-w-3xl">
            <div className="inline-flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
              <Users className="h-3.5 w-3.5" aria-hidden />
              Collaborators
            </div>
            <h2 className="mt-3 font-display text-[30px] md:text-[38px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
              An open network of contributors.
            </h2>
            <p className="mt-5 text-[17px] leading-relaxed text-[var(--color-slate)]">
              Beyond the steering committee, dozens of registrars, trainees, and
              research fellows contribute to OrthoGlobe studies, review atlas content,
              and help build the education layer. The full collaborator directory is
              rebuilt as members re-register through the new vetted membership flow.
            </p>
            <div className="mt-8 flex flex-wrap items-center gap-4">
              {!signedIn && <Button href="/join">Apply to join</Button>}
              <Link
                href="/contact"
                className="text-[14px] font-semibold text-[var(--color-blue)] underline underline-offset-4 hover:opacity-80"
              >
                Contact the team
              </Link>
            </div>
          </div>
        </Container>
      </section>
    </>
  );
}
