"use client";

import { useState } from "react";
import { m, useReducedMotion } from "motion/react";

import { dossiers, type Dossier } from "@/lib/portfolio";

const activeText = "text-signal-green";
const activeBorder = "border-l-signal-green";
const activeGlow = "shadow-[0_0_32px_rgba(182,255,0,0.12)]";

function isLiveStatus(status: string) {
  return /\b(live|deployed)\b/i.test(status);
}

function headlineProof(dossier: Dossier) {
  return dossier.proof.find((proof) => proof.metric) ?? dossier.proof[0];
}

export function WorkIndex() {
  const shouldReduceMotion = useReducedMotion();
  const [activeId, setActiveId] = useState<string | null>(null);

  return (
    <section
      id="work"
      aria-labelledby="work-title"
      className="mx-auto max-w-7xl px-6 py-28 text-blacksite-text sm:px-8 sm:py-36 lg:px-12"
    >
      <p id="work-title" className="section-label mb-12 text-blacksite-muted">
        WORK /.02
      </p>

      <m.div
        initial={shouldReduceMotion ? false : { opacity: 0, y: 18 }}
        whileInView={shouldReduceMotion ? undefined : { opacity: 1, y: 0 }}
        viewport={{ once: true, margin: "-80px" }}
        transition={{ duration: 0.5, ease: "easeOut" }}
        className="overflow-hidden border-y border-blacksite-line bg-blacksite-bg2/70"
      >
        <div className="section-label grid grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)_minmax(0,0.8fr)_5rem] gap-4 border-b border-blacksite-line px-4 py-3 text-blacksite-muted max-md:hidden">
          <span>PROJECT</span>
          <span>PROOF</span>
          <span>TYPE</span>
          <span className="text-right">YEAR</span>
        </div>

        <div className="divide-y divide-blacksite-line">
          {dossiers.map((dossier, index) => {
            const isActive = activeId === dossier.id;
            const shouldDim = activeId !== null && !isActive;
            const proof = headlineProof(dossier);
            const detailsExpanded = shouldReduceMotion || isActive;
            const liveStatus = isLiveStatus(dossier.status);

            return (
              <article
                key={dossier.id}
                tabIndex={0}
                onMouseEnter={() => setActiveId(dossier.id)}
                onMouseLeave={() => setActiveId(null)}
                onFocus={() => setActiveId(dossier.id)}
                onBlur={(event) => {
                  if (
                    !event.currentTarget.contains(
                      event.relatedTarget as Node | null,
                    )
                  ) {
                    setActiveId(null);
                  }
                }}
                className={`group border-l-2 border-l-transparent bg-blacksite-bg2/20 px-4 py-6 outline-none transition duration-200 focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-signal-green ${
                  isActive ? `${activeBorder} bg-blacksite-surface/70 ${activeGlow}` : ""
                } ${shouldDim ? "opacity-45" : "opacity-100"}`}
              >
                <div className="grid gap-3 md:grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)_minmax(0,0.8fr)_5rem] md:items-start md:gap-4">
                  <div className="min-w-0">
                    <p className="section-label mb-1 text-blacksite-muted md:hidden">
                      PROJECT
                    </p>
                    <div className="flex items-baseline gap-3">
                      <span className="font-mono text-xs text-blacksite-muted">
                        {String(index + 1).padStart(2, "0")}
                      </span>
                      <h3
                        className={`font-display text-2xl leading-none tracking-[-0.03em] transition-colors duration-200 ${
                          isActive ? activeText : "text-blacksite-text"
                        }`}
                      >
                        {dossier.title}
                      </h3>
                      {dossier.accent === "green" ? (
                        <span aria-hidden="true" className="size-2 rounded-full bg-signal-green shadow-[0_0_14px_rgba(182,255,0,0.45)]" />
                      ) : null}
                    </div>
                  </div>

                  <div>
                    <p className="section-label mb-1 text-blacksite-muted md:hidden">
                      PROOF
                    </p>
                    <p className="font-mono text-xs uppercase tracking-[0.16em] text-signal-green">
                      {dossier.proofHeadline}
                    </p>
                  </div>

                  <div className="hidden md:block">
                    <p className="section-label mb-1 text-blacksite-muted md:hidden">
                      TYPE
                    </p>
                    <p className="text-sm leading-5 text-blacksite-muted">
                      {dossier.type}
                    </p>
                  </div>

                  <div className="md:text-right">
                    <p className="section-label mb-1 text-blacksite-muted md:hidden">
                      YEAR
                    </p>
                    <p className="font-mono text-xs text-blacksite-muted">
                      {dossier.year}
                    </p>
                  </div>
                </div>

                <m.div
                  initial={false}
                  animate={
                    detailsExpanded
                      ? { opacity: 1, height: "auto" }
                      : { opacity: 0, height: 0 }
                  }
                  transition={
                    shouldReduceMotion
                      ? { duration: 0 }
                      : { duration: 0.22, ease: "easeOut" }
                  }
                  className="overflow-hidden [@media_(hover:none)]:!h-auto [@media_(hover:none)]:!opacity-100"
                >
                  <div className="grid gap-5 pt-5 md:grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)_minmax(0,0.8fr)_5rem] md:gap-4">
                    <div className="space-y-2 md:col-span-2">
                      <p className="section-label">MISSION</p>
                      <p className="text-sm leading-6 text-blacksite-text">
                        {dossier.mission}
                      </p>
                      {dossier.constraint ? (
                        <p className="text-xs leading-5 text-blacksite-muted">
                          Constraint: {dossier.constraint}
                        </p>
                      ) : null}
                    </div>

                    <div className="space-y-2">
                      <p className="section-label">STATUS</p>
                      <p className="flex items-center gap-2 font-mono text-xs uppercase tracking-[0.16em] text-blacksite-muted">
                        {liveStatus ? (
                          <span aria-hidden="true" className="size-2 rounded-full bg-signal-green shadow-[0_0_14px_rgba(182,255,0,0.45)]" />
                        ) : null}
                        {dossier.status}
                      </p>
                    </div>

                    <div className="space-y-2">
                      <p className="section-label">STACK</p>
                      <div className="flex flex-wrap gap-2">
                        {dossier.stack.map((item) => (
                          <span
                            key={item}
                            className="border border-blacksite-line bg-blacksite-surface px-2 py-1 font-mono text-[11px] uppercase tracking-[0.14em] text-blacksite-muted"
                          >
                            {item}
                          </span>
                        ))}
                      </div>
                    </div>

                    <div className="space-y-2 md:text-right">
                      <p className="section-label">PROOF</p>
                      <p
                        className={`font-display text-xl leading-none ${activeText}`}
                      >
                        {proof?.metric ?? proof?.label ?? dossier.result}
                      </p>
                      <p className="text-xs leading-5 text-blacksite-muted">
                        {proof?.metric ? proof.label : dossier.result}
                      </p>
                    </div>

                    <div className="space-y-2 md:col-span-4">
                      <p className="section-label">LINKS</p>
                      {dossier.links.length > 0 ? (
                        <div className="flex flex-wrap gap-2">
                          {dossier.links.map((link) => (
                            <a
                              key={`${dossier.id}-${link.href}-${link.label}`}
                              href={link.href}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="border border-blacksite-line bg-blacksite-surface2 px-3 py-2 font-mono text-xs uppercase tracking-[0.14em] text-blacksite-text transition-colors hover:border-signal-green hover:text-signal-green focus-visible:outline-signal-green"
                            >
                              {link.label} ↗
                            </a>
                          ))}
                        </div>
                      ) : (
                        <p className="font-mono text-xs uppercase tracking-[0.14em] text-blacksite-muted">
                          Closed source
                        </p>
                      )}
                    </div>
                  </div>
                </m.div>
              </article>
            );
          })}
        </div>
      </m.div>
    </section>
  );
}
