---
import { marked } from "marked";
import BaseLayout from "../../layouts/BaseLayout.astro";
import IndexRow from "../../components/IndexRow.astro";
import { SITE } from "../../lib/blog-data.js";
import { getProjects } from "../../lib/projects.js";

export async function getStaticPaths() {
  const projects = await getProjects();
  return projects.map((project) => ({
    params: { slug: project.slug },
    props: { project, projects },
  }));
}

const { project, projects } = Astro.props;

const body = project.body ? marked.parse(project.body) : "";

// Everything else, so a visitor who reaches the end has somewhere to go.
const others = projects.filter((p) => p.slug !== project.slug).slice(0, 3);

const igHandle = project.links?.instagram
  ? "@" + project.links.instagram.replace(/^.*instagram\.com\//, "").replace(/\/$/, "")
  : null;

const statusLabel = {
  live: "Live",
  building: "In development",
  archived: "Archived",
  concept: "Concept",
}[project.status] ?? project.status;

const jsonLd = {
  "@context": "https://schema.org",
  "@type": "CreativeWork",
  name: project.title,
  description: project.summary,
  url: `${SITE.url}/projects/${project.slug}`,
  author: { "@type": "Person", name: SITE.name, url: SITE.url },
  keywords: (project.categories ?? []).join(", "),
};
---

<BaseLayout
  title={project.seoTitle ?? `${project.title} — ${SITE.name}`}
  description={project.seoDescription ?? project.summary}
  canonical={`/projects/${project.slug}`}
  jsonLd={jsonLd}
>
  <article>
    <!-- ---------- header ---------- -->
    <header class="mx-auto w-full max-w-6xl px-5 pt-16 pb-12 md:pt-24">
      <a href="/projects" class="ca-back">
        <span aria-hidden="true">&larr;</span> All projects
      </a>

      <div class="mt-8 flex flex-wrap items-center gap-3">
        <span class:list={["ca-status", `is-${project.status}`]}>{statusLabel}</span>
        {
          (project.categories ?? []).map((c) => (
            <a href={`/projects#${c.toLowerCase()}`} class="ca-chip">
              {c}
            </a>
          ))
        }
      </div>

      <h1
        class="mt-6 max-w-[16ch] font-serif text-[clamp(2.4rem,6vw,4rem)] leading-[1.05] tracking-tight text-balance"
      >
        {project.title}
      </h1>

      {
        project.lede && (
          <p class="mt-6 max-w-[52ch] font-serif text-[clamp(1.2rem,2.4vw,1.6rem)] leading-snug text-[var(--ca-ink-2)]">
            {project.lede}
          </p>
        )
      }
    </header>

    <!-- ---------- facts rail ---------- -->
    <section class="mx-auto w-full max-w-6xl px-5">
      <dl class="ca-facts">
        <div>
          <dt>Type</dt>
          <dd>{project.kind}</dd>
        </div>
        <div>
          <dt>Timeline</dt>
          <dd>{project.period}</dd>
        </div>
        {
          project.role && (
            <div>
              <dt>Role</dt>
              <dd>{project.role}</dd>
            </div>
          )
        }
        {
          project.links?.live && (
            <div>
              <dt>Live</dt>
              <dd>
                <a href={project.links.live} target="_blank" rel="noopener noreferrer" class="ca-quiet">
                  {project.links.live.replace(/^https?:\/\//, "").replace(/\/$/, "")}
                </a>
              </dd>
            </div>
          )
        }
        {
          project.links?.instagram && (
            <div>
              <dt>Instagram</dt>
              <dd>
                <a href={project.links.instagram} target="_blank" rel="noopener noreferrer" class="ca-quiet">
                  @{project.links.instagram.replace(/^.*instagram\.com\//, "").replace(/\/$/, "")}
                </a>
              </dd>
            </div>
          )
        }
        {
          project.links?.github && (
            <div>
              <dt>Code</dt>
              <dd>
                <a href={project.links.github} target="_blank" rel="noopener noreferrer" class="ca-quiet">
                  {project.links.github.replace(/^https?:\/\/(www\.)?github\.com\//, "").replace(/\/$/, "")}
                </a>
              </dd>
            </div>
          )
        }
      </dl>
    </section>

    <!-- ---------- metrics ---------- -->
    {
      (project.metrics ?? []).length > 0 && (
        <section class="mx-auto w-full max-w-6xl px-5 pt-14">
          <div class="ca-metrics">
            {project.metrics.map((m) => (
              <div class="ca-metric">
                <div class="ca-metric-value">{m.value}</div>
                <div class="ca-metric-label">{m.label}</div>
                {m.note && <div class="ca-metric-note">{m.note}</div>}
              </div>
            ))}
          </div>
        </section>
      )
    }

    <!-- ---------- gallery ---------- -->
    {
      (project.gallery ?? []).length > 0 && (
        <section class="mx-auto w-full max-w-6xl px-5 pt-16 md:pt-20">
          <h2 class="mb-6 font-mono text-[0.7rem] tracking-[0.18em] text-[var(--ca-ink-4)] uppercase">
            Gallery
          </h2>
          <div class="ca-gallery" data-gallery>
            {project.gallery.map((img, i) =>
              img.src ? (
                <button
                  type="button"
                  class="ca-gallery-item"
                  data-gallery-open
                  data-src={img.src}
                  data-caption={img.caption ?? ""}
                  aria-label={`Enlarge: ${img.caption ?? img.alt ?? `image ${i + 1}`}`}
                >
                  <img src={img.src} alt={img.alt ?? ""} loading="lazy" />
                  {img.caption && <span class="ca-gallery-cap">{img.caption}</span>}
                </button>
              ) : (
                <div class="ca-gallery-item is-empty" aria-hidden="true">
                  <span class="ca-gallery-glyph">+</span>
                  {img.caption && <span class="ca-gallery-cap">{img.caption}</span>}
                </div>
              ),
            )}
          </div>
        </section>
      )
    }

    <!-- ---------- body + social rail ---------- -->
    {
      body && (
        <section class="mx-auto w-full max-w-6xl px-5 pt-16 md:pt-20">
          <div class="ca-body-grid">
            <!-- left: sticky Instagram 9:16 placeholder -->
            <aside class="ca-body-rail">
              <figure class="ca-reel" aria-label="Instagram — placeholder">
                {/* Swap for a real Instagram Reel embed when ready. The 9:16
                    frame reserves the space, so the embed drops in without
                    reflowing the case study beside it. */}
                <div class="ca-reel-inner">
                  <span class="ca-reel-glyph" aria-hidden="true">
                    ▶
                  </span>
                  <span class="ca-reel-label">Instagram</span>
                  {igHandle && <span class="ca-reel-handle">{igHandle}</span>}
                </div>
                <span class="ca-hero-seal" aria-hidden="true">
                  印
                </span>
              </figure>
              {project.links?.instagram && (
                <a
                  href={project.links.instagram}
                  target="_blank"
                  rel="noopener noreferrer"
                  class="ca-quiet mt-4 inline-block font-mono text-[0.7rem] tracking-[0.12em] uppercase"
                >
                  Watch on Instagram &rarr;
                </a>
              )}
            </aside>

            <!-- right: the case study -->
            <div class="ca-body-main ca-prose" set:html={body} />
          </div>
        </section>
      )
    }

    <!-- ---------- skills applied (disciplines) ---------- -->
    {
      (project.skills ?? []).length > 0 && (
        <section class="ca-band mx-auto w-full max-w-6xl px-5">
          <h2 class="mb-8 font-serif text-[clamp(1.6rem,3.4vw,2.1rem)] leading-tight tracking-tight">
            <span class="ca-brushed">Skills applied</span>
          </h2>
          <div class="ca-skills">
            {project.skills.map((group) => (
              <div class="ca-skill-group">
                <h3>{group.group}</h3>
                <ul>
                  {(group.items ?? []).map((item) => (
                    <li>{item}</li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </section>
      )
    }

    <!-- ---------- built with (tech stack) ---------- -->
    {
      (project.stack ?? []).length > 0 && (
        <section class="mx-auto w-full max-w-6xl px-5 pt-4 pb-2">
          <h2 class="mb-4 font-mono text-[0.7rem] tracking-[0.18em] text-[var(--ca-ink-4)] uppercase">
            Built with
          </h2>
          <ul class="flex flex-wrap gap-2">
            {project.stack.map((s) => (
              <li class="rounded-[var(--radius)] border border-border px-2.5 py-1 font-mono text-[0.7rem] tracking-wide text-muted-foreground">
                {s}
              </li>
            ))}
          </ul>
        </section>
      )
    }

    <!-- ---------- next ---------- -->
    {
      others.length > 0 && (
        <section class="ca-band mx-auto w-full max-w-6xl px-5">
          <h2 class="mb-8 font-serif text-[clamp(1.6rem,3.4vw,2.1rem)] leading-tight tracking-tight">
            <span class="ca-brushed">More work</span>
          </h2>
          <div class="flex flex-col">
            {others.map((p, i) => (
              <IndexRow
                href={`/projects/${p.slug}`}
                title={p.title}
                meta={p.period}
                summary={p.summary}
                tags={p.categories}
                first={i === 0}
              />
            ))}
          </div>
        </section>
      )
    }

    <section class="ca-band mx-auto w-full max-w-6xl px-5">
      <h2
        class="max-w-[20ch] font-serif text-[clamp(1.8rem,4.5vw,3.1rem)] leading-tight tracking-tight text-balance"
      >
        Building something <span class="ca-brushed">like this?</span>
      </h2>
      <div class="mt-9 flex flex-wrap items-center gap-7">
        <a
          href="/contact"
          class="rounded-[var(--radius)] border border-primary bg-primary px-6 py-3 text-sm font-medium text-primary-foreground transition-colors hover:bg-transparent hover:text-primary"
        >
          Start a conversation
        </a>
        <a href="/projects" class="ca-quiet text-sm">See all projects</a>
      </div>
    </section>
  </article>

  <!-- Lightbox for the gallery. One overlay, reused for every image; only
       renders if the page has a gallery with real (non-placeholder) photos. -->
  <div class="ca-lightbox" data-lightbox hidden>
    <button type="button" class="ca-lightbox-close" data-lightbox-close aria-label="Close">
      &times;
    </button>
    <figure class="ca-lightbox-fig">
      <img data-lightbox-img src="" alt="" />
      <figcaption data-lightbox-cap></figcaption>
    </figure>
  </div>
</BaseLayout>

<script>
  const openers = document.querySelectorAll("[data-gallery-open]");
  const box = document.querySelector("[data-lightbox]");

  if (openers.length && box) {
    const img = box.querySelector("[data-lightbox-img]");
    const cap = box.querySelector("[data-lightbox-cap]");
    const closeBtn = box.querySelector("[data-lightbox-close]");
    let lastFocus = null;

    const open = (src, caption) => {
      lastFocus = document.activeElement;
      img.src = src;
      img.alt = caption || "";
      cap.textContent = caption || "";
      cap.hidden = !caption;
      box.hidden = false;
      document.body.style.overflow = "hidden";
      closeBtn.focus();
    };

    const close = () => {
      box.hidden = true;
      img.src = "";
      document.body.style.overflow = "";
      lastFocus?.focus();
    };

    for (const btn of openers) {
      btn.addEventListener("click", () =>
        open(btn.dataset.src, btn.dataset.caption),
      );
    }
    closeBtn.addEventListener("click", close);
    box.addEventListener("click", (e) => {
      if (e.target === box) close();
    });
    document.addEventListener("keydown", (e) => {
      if (e.key === "Escape" && !box.hidden) close();
    });
  }
</script>
