import Link from "next/link";
import { getProject } from "@/lib/api";

export const dynamic = "force-dynamic";

type Project = {
  slug: string;
  title: string;
  summary?: string | null;
  tags?: string[] | null;
  type?: string | null;
  industry?: string | null;
  cover_image?: string | null;
  timeline?: string | null;
  stack?: string[] | null;
  roles?: string[] | null;
  links?: { label: string; href: string }[] | null;
  problem?: string | null;
  approach?: string | null;
  outcome?: string | null;
  metrics?: string[] | null;
};

// --- Components ---

function TagPill({ children }: { children: React.ReactNode }) {
  return (
    <span className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/50 px-3 py-1 text-xs font-medium text-slate-700 backdrop-blur-sm">
      <span className="h-1.5 w-1.5 rounded-full bg-cyan-500/90" />
      {children}
    </span>
  );
}

// 1. Restored the "System Overview" SVG Placeholder you liked
function PlaceholderCover() {
  return (
    <div className="relative h-full w-full overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
      {/* Background Ambience */}
      <div className="absolute inset-0">
        <div className="absolute -top-10 -left-10 h-44 w-44 rounded-full bg-cyan-400/10 blur-3xl" />
        <div className="absolute -bottom-10 -right-10 h-44 w-44 rounded-full bg-blue-500/10 blur-3xl" />
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_25%_25%,rgba(34,211,238,0.10),transparent_55%),radial-gradient(circle_at_80%_30%,rgba(59,130,246,0.10),transparent_55%)]" />
      </div>

      {/* Grid Pattern */}
      <div className="absolute inset-0 opacity-60">
        <div className="absolute inset-0 bg-[linear-gradient(to_right,rgba(15,23,42,0.06)_1px,transparent_1px),linear-gradient(to_bottom,rgba(15,23,42,0.06)_1px,transparent_1px)] bg-[size:26px_26px]" />
        <div className="absolute inset-0 [mask-image:radial-gradient(65%_55%_at_50%_40%,black,transparent)] bg-white" />
      </div>

      {/* The Network Nodes SVG */}
      <svg
        className="absolute inset-0 h-full w-full"
        viewBox="0 0 800 360"
        preserveAspectRatio="xMidYMid slice"
        aria-hidden="true"
      >
        <g fill="none" stroke="rgba(15,23,42,0.18)" strokeWidth="1">
          <path d="M110 90 L260 90 L320 150 L520 150 L610 220" />
          <path d="M160 250 L260 210 L420 210 L520 260 L680 260" />
          <path d="M240 70 L240 150 L360 150" />
          <path d="M520 110 L520 190 L610 190" />
        </g>
        <g fill="rgba(34,211,238,0.45)">
          <circle cx="110" cy="90" r="6" />
          <circle cx="260" cy="90" r="6" />
          <circle cx="320" cy="150" r="6" />
          <circle cx="520" cy="150" r="6" />
          <circle cx="610" cy="220" r="6" />
        </g>
        <g fill="rgba(59,130,246,0.35)">
          <circle cx="160" cy="250" r="6" />
          <circle cx="260" cy="210" r="6" />
          <circle cx="420" cy="210" r="6" />
          <circle cx="520" cy="260" r="6" />
          <circle cx="680" cy="260" r="6" />
        </g>
      </svg>

      <div className="absolute left-5 top-5 inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/90 px-3 py-1 text-[11px] font-mono uppercase tracking-wider text-slate-600 backdrop-blur shadow-sm">
        <span className="h-1.5 w-1.5 rounded-full bg-cyan-500/90" />
        system overview
      </div>
    </div>
  );
}

function SpecRow({ label, value }: { label: string; value?: React.ReactNode }) {
  return (
    <div className="flex items-start justify-between gap-4 py-3 border-b border-slate-50 last:border-0">
      <div className="text-xs text-slate-500">{label}</div>
      <div className="text-sm font-semibold text-slate-900 text-right">
        {value ?? "—"}
      </div>
    </div>
  );
}

// 2. New Card Component for Problem/Approach/Outcome
function ContentCard({
  title,
  children,
  icon,
}: {
  title: string;
  children: React.ReactNode;
  icon?: React.ReactNode;
}) {
  return (
    <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm hover:shadow-md transition-shadow duration-300">
      <div className="flex items-center gap-3 mb-3">
        {icon && (
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-slate-50 text-slate-600">
            {icon}
          </div>
        )}
        <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide">{title}</h3>
      </div>
      <div className="text-sm leading-7 text-slate-600">
        {children}
      </div>
    </section>
  );
}

export default async function WorkDetail({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const project = (await getProject(slug)) as Project | null;

  if (!project) {
    return (
      <main className="bg-white min-h-screen">
        <section className="mx-auto max-w-5xl px-4 sm:px-6 lg:px-8 py-20 text-center">
          <div className="rounded-3xl border border-slate-200 bg-slate-50 p-12">
            <h1 className="text-2xl font-bold text-slate-900">Project not found</h1>
            <div className="mt-6">
              <Link href="/work" className="inline-flex items-center rounded-xl bg-slate-900 px-6 py-3 text-sm font-medium text-white hover:bg-slate-800">
                Back to work
              </Link>
            </div>
          </div>
        </section>
      </main>
    );
  }

  const typeLabel = project.type === "concept_demo" ? "Concept Demo" : "Case Study";
  const fallbackMetrics = [
    "Reduced manual ops with automation",
    "Faster workflows with clear roles",
    "Better visibility with analytics",
  ];

  return (
    <main className="bg-[#FAFAFA] min-h-screen">
      
      {/* ======= TOP BAR ======= */}
      <section className="sticky top-0 z-30 border-b border-slate-200 bg-white/80 backdrop-blur-md">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between gap-3">
            <Link
              href="/work"
              className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white px-4 py-1.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors"
            >
              <span aria-hidden="true">←</span> Back to work
            </Link>

            <div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-slate-50 px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-slate-500">
              <span className="h-1.5 w-1.5 rounded-full bg-cyan-500/90" />
              {typeLabel}
            </div>
          </div>
        </div>
      </section>

      {/* ======= HERO (Split Layout - Your Favorite) ======= */}
      <section className="relative overflow-hidden border-b border-slate-200 bg-white">
        <div className="pointer-events-none absolute inset-0">
           <div className="absolute top-[-20%] right-0 h-[500px] w-[500px] bg-cyan-50/50 blur-[100px]" />
        </div>

        <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-12 sm:py-16">
          <div className="grid gap-12 lg:grid-cols-12 lg:items-center">
            
            {/* Left: Text Info */}
            <div className="lg:col-span-6">
              <div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/80 px-3 py-1 text-[11px] font-mono uppercase tracking-widest text-slate-600 backdrop-blur">
                Adblast IT · Work
              </div>

              <h1 className="mt-6 text-4xl sm:text-5xl font-bold tracking-tighter text-slate-900 leading-[1.1]">
                {project.title}
              </h1>

              <p className="mt-6 text-lg leading-relaxed text-slate-600">
                {project.summary ?? "A production-grade system engineered for scale, security, and speed."}
              </p>

              <div className="mt-8 flex flex-wrap gap-2">
                {(project.tags ?? []).slice(0, 10).map((t) => (
                  <TagPill key={t}>{t}</TagPill>
                ))}
              </div>
            </div>

            {/* Right: Visual / Placeholder */}
            <div className="lg:col-span-6">
              <div className="aspect-[16/9] w-full shadow-2xl shadow-slate-200/50 rounded-2xl">
                {project.cover_image ? (
                  <div className="relative h-full w-full overflow-hidden rounded-2xl border border-slate-200 bg-white">
                    <img
                      src={project.cover_image}
                      alt={project.title}
                      className="h-full w-full object-cover"
                    />
                  </div>
                ) : (
                  <PlaceholderCover />
                )}
              </div>
            </div>

          </div>
        </div>
      </section>

      {/* ======= CONTENT ======= */}
      <section className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-12">
        <div className="grid gap-8 lg:grid-cols-12">
          
          {/* Main Narrative Area */}
          <div className="lg:col-span-8 space-y-6">
            
            {/* 3. Narrative Cards (Challenge, Approach, Outcome) */}
            {project.problem && (
              <ContentCard 
                title="The Challenge" 
                icon={<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>}
              >
                {project.problem}
              </ContentCard>
            )}

            {project.approach && (
              <ContentCard 
                title="Our Approach"
                icon={<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" /></svg>}
              >
                {project.approach}
              </ContentCard>
            )}

            {project.outcome && (
              <ContentCard 
                title="The Outcome"
                icon={<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>}
              >
                {project.outcome}
              </ContentCard>
            )}

            {/* Key Outcomes Box (Dark Style for Contrast) */}
            <section className="rounded-2xl bg-slate-900 p-8 text-white shadow-xl shadow-slate-900/10">
              <div className="flex items-center gap-3 mb-6">
                <span className="h-2 w-2 rounded-full bg-cyan-400 animate-pulse" />
                <h3 className="text-sm font-bold uppercase tracking-widest text-slate-200">
                  Measurable Impact
                </h3>
              </div>

              <ul className="grid gap-4 sm:grid-cols-2">
                {(project.metrics?.length ? project.metrics : fallbackMetrics)
                  .slice(0, 4)
                  .map((m) => (
                    <li key={m} className="flex items-start gap-3">
                      <svg className="w-5 h-5 text-cyan-400 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
                      <span className="text-sm leading-relaxed text-slate-300">{m}</span>
                    </li>
                  ))}
              </ul>
            </section>

            {/* CTA */}
            <section className="rounded-2xl border border-slate-200 bg-white p-8 text-center sm:text-left sm:flex sm:items-center sm:justify-between gap-6">
              <div>
                <div className="text-base font-bold text-slate-900">Want something similar?</div>
                <p className="mt-1 text-sm text-slate-600">We can scope it fast and propose a clean delivery plan.</p>
              </div>
              <Link
                href="/contact"
                className="inline-flex shrink-0 items-center justify-center rounded-xl bg-slate-900 px-6 py-3 text-sm font-bold text-white hover:bg-slate-800 transition-all shadow-lg shadow-slate-900/20"
              >
                Discuss a project
              </Link>
            </section>
          </div>

          {/* Sidebar */}
          <aside className="lg:col-span-4">
            <div className="sticky top-24 space-y-6">
              
              {/* Specs Card */}
              <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                   <h3 className="text-sm font-bold text-slate-900 uppercase tracking-widest">Project Specs</h3>
                </div>
                <div className="divide-y divide-slate-100">
                  <SpecRow label="Industry" value={project.industry} />
                  <SpecRow label="Timeline" value={project.timeline} />
                  <SpecRow
                    label="Stack"
                    value={
                      project.stack?.length ? (
                        <span className="flex flex-wrap justify-end gap-1.5">
                          {project.stack.slice(0, 4).map((s) => (
                            <span key={s} className="rounded-md bg-slate-100 px-2 py-0.5 text-[10px] font-bold text-slate-600 border border-slate-200">
                              {s}
                            </span>
                          ))}
                        </span>
                      ) : "—"
                    }
                  />
                  <SpecRow
                    label="Role"
                    value={
                      project.roles?.length ? (
                        <span className="text-sm font-semibold text-slate-900">
                          {project.roles.slice(0, 2).join(", ")}
                        </span>
                      ) : "—"
                    }
                  />
                </div>
              </div>

              {/* Links */}
              {project.links?.length ? (
                <div className="grid gap-2">
                  {project.links.slice(0, 3).map((l) => (
                    <a
                      key={l.href}
                      href={l.href}
                      target="_blank"
                      rel="noreferrer"
                      className="group flex items-center justify-between rounded-xl border border-slate-200 bg-white px-5 py-4 text-sm font-bold text-slate-700 hover:border-cyan-500/30 hover:shadow-md transition-all"
                    >
                      <span>{l.label}</span>
                      <svg className="h-4 w-4 text-slate-400 group-hover:text-cyan-600 transition-colors" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" /></svg>
                    </a>
                  ))}
                </div>
              ) : null}

              {/* Confidential Badge */}
              <div className="rounded-xl border border-slate-200 bg-slate-50 p-5">
                <div className="flex items-center gap-2 text-xs font-bold text-slate-900 uppercase tracking-wider mb-2">
                   <svg className="w-4 h-4 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                   Secure Work
                </div>
                <p className="text-xs leading-5 text-slate-500">
                  If a system includes sensitive details, we summarize outcomes without exposing private data.
                </p>
              </div>

            </div>
          </aside>
        </div>
      </section>

      {/* Footer */}
      <footer className="border-t border-slate-200 bg-white">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8 text-center">
          <div className="font-mono text-xs text-slate-500 uppercase tracking-wider">
            Built for scale · security · speed
          </div>
        </div>
      </footer>
    </main>
  );
}