"use client";

import { motion, useReducedMotion, useScroll, useTransform } from "framer-motion";
import Image from "next/image";
import { useRef, useState } from "react";
import {
  ArrowUpRight,
  AwardIcon,
  CartIcon,
  DownloadIcon,
  GlobeIcon,
  InstagramIcon,
  LinkedInIcon,
  FacebookIcon,
  MailIcon,
  PhoneIcon,
  PinIcon,
} from "@/components/icons";
import { navigateToSection } from "@/components/Nav";
import { Reveal, SectionLabel } from "@/components/motion";
import { aspectOf, studio } from "@/lib/content";
import type { Award, Client, Exhibition, Project } from "@/lib/data";

/* ------------------------------------------------------------------ */
/* About                                                               */
/* ------------------------------------------------------------------ */

export function About() {
  const ref = useRef<HTMLDivElement>(null);
  const reduce = useReducedMotion();
  const { scrollYProgress } = useScroll({
    target: ref,
    offset: ["start end", "end start"],
  });
  const y = useTransform(scrollYProgress, [0, 1], [reduce ? 0 : -50, reduce ? 0 : 50]);

  return (
    <section id="about" ref={ref} className="relative border-t border-[#efefef] py-24 md:py-36">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <div className="grid grid-cols-1 gap-12 lg:grid-cols-12 lg:gap-16">
          <div className="lg:col-span-5">
            <Reveal>
              <SectionLabel>About the studio</SectionLabel>
              <h2 className="mt-6 max-w-[16ch] text-[clamp(2rem,4.4vw,3.6rem)] font-medium leading-[1.02] tracking-display text-balance">
                A carpenter&rsquo;s eye, a designer&rsquo;s restraint.
              </h2>
            </Reveal>

            <Reveal delay={0.1}>
              <div
                className="relative mt-10 w-full overflow-hidden bg-white"
                style={{ aspectRatio: String(aspectOf(studio.image)) }}
              >
                <Image
                  src={studio.image}
                  alt="Florian Gross Design Studio workspace in Barcelona"
                  fill
                  sizes="(max-width: 1024px) 100vw, 40vw"
                  quality={88}
                  className="object-contain"
                />
              </div>
            </Reveal>
          </div>

          <div className="lg:col-span-7 lg:pt-16">
            {studio.about.split("\n\n").map((paragraph, i) => (
              <Reveal key={i} delay={0.12 + i * 0.08}>
                <p className="mb-6 max-w-[62ch] text-[16px] leading-[1.75] text-ink-soft md:text-[17px]">
                  {paragraph}
                </p>
              </Reveal>
            ))}

            <Reveal delay={0.25}>
              <div className="mt-10 grid grid-cols-2 gap-x-8 gap-y-10 border-t border-[#efefef] pt-10 sm:grid-cols-4">
                {[
                  { value: "1982", label: "Born" },
                  { value: "2001", label: "Carpentry apprenticeship" },
                  { value: "2009", label: "Interior design degree" },
                  { value: "2011", label: "Studio founded" },
                ].map((stat) => (
                  <div key={stat.label}>
                    <p className="text-[26px] font-medium tabular-nums tracking-display md:text-[30px]">
                      {stat.value}
                    </p>
                    <p className="mt-2 text-[11px] uppercase leading-relaxed tracking-[0.18em] text-faint">
                      {stat.label}
                    </p>
                  </div>
                ))}
              </div>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* Konnex — available worldwide                                        */
/* ------------------------------------------------------------------ */

export function KonnexShop({ project }: { project: Project | undefined }) {
  const [active, setActive] = useState(0);
  if (!project) return null;

  const gallery = project.images.slice(0, 4);
  const shot = gallery[active] ?? project.cover;

  return (
    <section id="konnex" className="relative overflow-hidden py-24 md:py-32">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <div className="grid grid-cols-1 items-center gap-12 lg:grid-cols-12 lg:gap-16">
          <div className="order-2 lg:order-1 lg:col-span-7">
            <Reveal>
              <div
                className="relative w-full overflow-hidden bg-white transition-[aspect-ratio] duration-500 ease-out"
                style={{ aspectRatio: String(aspectOf(shot)) }}
              >
                <motion.div
                  key={shot}
                  initial={{ opacity: 0, scale: 1.02 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ duration: 0.75, ease: [0.16, 1, 0.3, 1] }}
                  className="absolute inset-0"
                >
                  <Image
                    src={shot}
                    alt="Konnex modular shelving system by Florian Gross for Müller Möbelwerkstätten"
                    fill
                    sizes="(max-width: 1024px) 100vw, 58vw"
                    quality={90}
                    className="object-contain"
                  />
                </motion.div>
              </div>

              <div className="mt-4 flex items-center gap-3">
                {gallery.map((src, i) => (
                  <button
                    key={src}
                    type="button"
                    onClick={() => setActive(i)}
                    aria-label={`Show Konnex view ${i + 1}`}
                    className={`relative h-16 w-24 shrink-0 overflow-hidden rounded-[3px] border transition-all duration-300 ${
                      i === active
                        ? "border-[#0a0a0a] opacity-100"
                        : "border-transparent opacity-45 hover:opacity-85"
                    }`}
                  >
                    <Image src={src} alt="" fill sizes="96px" quality={55} className="object-contain" />
                  </button>
                ))}
              </div>
            </Reveal>
          </div>

          <div className="order-1 lg:order-2 lg:col-span-5">
            <Reveal>
              <SectionLabel>Available worldwide</SectionLabel>
              <h2 className="mt-6 text-[clamp(2.2rem,5vw,4.2rem)] font-medium leading-[0.98] tracking-display">
                Konnex
              </h2>
              <p className="mt-3 text-[13px] uppercase tracking-[0.22em] text-faint">
                Modular slot-in shelving · {project.year}
              </p>

              <p className="mt-7 max-w-[52ch] text-[15.5px] leading-relaxed text-ink-soft">
                Three interlocking cubes, endlessly reconfigurable. Slot the comb-like
                slits into the side walls of another cube and the system grows with
                your space — no tools, no fixings, no limits. Manufactured in 6 mm
                high-pressure laminate by Müller Möbelwerkstätten.
              </p>

              <ul className="mt-8 space-y-2.5 border-t border-[#efefef] pt-8">
                {project.specs.map((spec) => (
                  <li key={spec} className="flex gap-3 text-[13.5px] text-mute">
                    <span className="mt-2 h-[3px] w-[3px] shrink-0 rounded-full bg-[#c6c6c6]" />
                    {spec}
                  </li>
                ))}
              </ul>

              <div className="mt-9 flex flex-col gap-3 sm:flex-row sm:items-center">
                <a
                  href={project.buyUrl ?? "https://www.muellermoebel.de/en/KONNEX-Set/KX200-312"}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group inline-flex items-center justify-between gap-4 rounded-full bg-[#0a0a0a] px-8 py-5 text-[11.5px] font-medium uppercase tracking-[0.22em] text-white transition-all duration-300 hover:bg-[#2a2a2a]"
                >
                  <span className="flex items-center gap-3">
                    <CartIcon className="h-4 w-4" />
                    Buy Konnex
                  </span>
                  <span className="flex items-center gap-2 text-[#9a9a9a]">
                    <GlobeIcon className="h-4 w-4" />
                    Worldwide
                    <ArrowUpRight className="h-4 w-4 text-white transition-transform duration-300 group-hover:-translate-y-0.5 group-hover:translate-x-0.5" />
                  </span>
                </a>

                {project.externalLinks.map((link) => (
                  <a
                    key={link.url}
                    href={link.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center justify-center gap-3 rounded-full border border-[#e0e0e0] px-8 py-5 text-[11.5px] uppercase tracking-[0.2em] text-ink-soft transition-all duration-300 hover:border-[#0a0a0a]"
                  >
                    <DownloadIcon className="h-4 w-4 text-[#b5b5b5]" />
                    Press kit
                  </a>
                ))}
              </div>

              <p className="mt-5 text-[12px] leading-relaxed text-faint">
                Produced by{" "}
                <a
                  href="https://www.muellermoebel.de/en/"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="link-underline text-mute"
                >
                  Müller Möbelwerkstätten
                </a>{" "}
                · Design by Florian Gross · Winner of the German Design Award nomination,
                Interior Innovation Award Best of Best and Good Design Chicago.
              </p>
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* Recognition — awards, exhibitions, clients                          */
/* ------------------------------------------------------------------ */

export function Recognition({
  awards,
  exhibitions,
  clients,
}: {
  awards: Award[];
  exhibitions: Exhibition[];
  clients: Client[];
}) {
  const [tab, setTab] = useState<"awards" | "exhibitions" | "clients">("awards");

  return (
    <section id="recognition" className="relative border-t border-[#efefef] py-24 md:py-32">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <Reveal className="flex flex-col gap-8 md:flex-row md:items-end md:justify-between">
          <div>
            <SectionLabel>Recognition</SectionLabel>
            <h2 className="mt-6 max-w-[20ch] text-[clamp(2rem,4.4vw,3.6rem)] font-medium leading-[1.02] tracking-display text-balance">
              Awarded and exhibited across Europe.
            </h2>
          </div>

          <div className="flex flex-wrap gap-2">
            {(
              [
                ["awards", `Awards ${awards.length}`],
                ["exhibitions", `Exhibitions ${exhibitions.length}`],
                ["clients", `Clients ${clients.length}`],
              ] as const
            ).map(([key, label]) => (
              <button
                key={key}
                type="button"
                onClick={() => setTab(key)}
                className="rounded-full border px-5 py-2.5 text-[11px] uppercase tracking-[0.18em] transition-colors duration-300"
                style={{
                  borderColor: tab === key ? "#0a0a0a" : "#e6e6e6",
                  color: tab === key ? "#0a0a0a" : "#9c9c9c",
                }}
              >
                {label}
              </button>
            ))}
          </div>
        </Reveal>

        <div className="mt-12 border-t border-[#efefef]">
          <motion.ul key={tab} initial="hidden" animate="show" className="divide-y divide-[#f2f2f2]">
            {(tab === "awards"
              ? awards.map((a) => ({
                  label: a.label,
                  url: a.url,
                  meta: "Award",
                }))
              : tab === "exhibitions"
                ? exhibitions.map((e) => ({ label: e.label, url: null, meta: "Exhibition" }))
                : clients.map((c) => ({ label: c.label, url: c.url, meta: "Client" }))
            ).map((item, i) => (
              <motion.li
                key={item.label}
                variants={{
                  hidden: { opacity: 0, y: 14 },
                  show: {
                    opacity: 1,
                    y: 0,
                    transition: { delay: Math.min(i * 0.035, 0.6), duration: 0.5 },
                  },
                }}
              >
                {item.url ? (
                  <a
                    href={item.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="group flex items-center justify-between gap-6 py-4 transition-colors hover:bg-[#fafafa]"
                  >
                    <span className="flex items-baseline gap-5">
                      <span className="w-8 shrink-0 text-[11px] tabular-nums text-[#c2c2c2]">
                        {String(i + 1).padStart(2, "0")}
                      </span>
                      <span className="text-[14.5px] text-ink-soft transition-opacity group-hover:opacity-65">
                        {item.label}
                      </span>
                    </span>
                    <ArrowUpRight className="h-4 w-4 shrink-0 text-[#c2c2c2] transition-colors group-hover:text-[#6e6e6e]" />
                  </a>
                ) : (
                  <div className="flex items-center justify-between gap-6 py-4">
                    <span className="flex items-baseline gap-5">
                      <span className="w-8 shrink-0 text-[11px] tabular-nums text-[#c2c2c2]">
                        {String(i + 1).padStart(2, "0")}
                      </span>
                      <span className="text-[14.5px] text-ink-soft">{item.label}</span>
                    </span>
                    <span className="hidden shrink-0 text-[10px] uppercase tracking-[0.2em] text-[#c2c2c2] sm:block">
                      {item.meta}
                    </span>
                  </div>
                )}
              </motion.li>
            ))}
          </motion.ul>
        </div>
      </div>
    </section>
  );
}

/* ------------------------------------------------------------------ */
/* Contact                                                             */
/* ------------------------------------------------------------------ */

const SUBJECTS = [
  "Product design enquiry",
  "Interior design project",
  "Licensing / edition",
  "Press request",
  "Other",
];

export function Contact() {
  const [status, setStatus] = useState<"idle" | "sending" | "sent" | "error">("idle");
  const [error, setError] = useState<string | null>(null);

  async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = event.currentTarget;
    const data = new FormData(form);
    setStatus("sending");
    setError(null);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: data.get("name"),
          email: data.get("email"),
          company: data.get("company"),
          subject: data.get("subject"),
          message: data.get("message"),
        }),
      });
      const json = (await res.json()) as { ok: boolean; error?: string };
      if (!res.ok || !json.ok) {
        setStatus("error");
        setError(json.error ?? "Something went wrong.");
        return;
      }
      setStatus("sent");
      form.reset();
    } catch {
      setStatus("error");
      setError("Network error — please try again or email the studio directly.");
    }
  }

  return (
    <section id="contact" className="relative border-t border-[#efefef] py-24 md:py-32">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <div className="grid grid-cols-1 gap-14 lg:grid-cols-12 lg:gap-16">
          <div className="lg:col-span-5">
            <Reveal>
              <SectionLabel>Contact</SectionLabel>
              <h2 className="mt-6 max-w-[14ch] text-[clamp(2rem,4.4vw,3.6rem)] font-medium leading-[1.02] tracking-display text-balance">
                Let&rsquo;s build something adaptable.
              </h2>
              <p className="mt-6 max-w-[46ch] text-[15px] leading-relaxed text-mute">
                For product design, lighting, licensing and interior commissions — or
                simply to say hello. The studio is based in Barcelona and works with
                clients and manufacturers worldwide.
              </p>
            </Reveal>

            <Reveal delay={0.12}>
              <ul className="mt-10 space-y-5">
                <li>
                  <a
                    href={`mailto:${studio.email}`}
                    className="group flex items-center gap-4 text-[15px] text-ink-soft transition-colors hover:text-mute"
                  >
                    <MailIcon className="h-5 w-5 text-[#c2c2c2]" />
                    <span className="link-underline">{studio.email}</span>
                  </a>
                </li>
                <li>
                  <a
                    href={studio.phoneHref}
                    className="group flex items-center gap-4 text-[15px] text-ink-soft transition-colors hover:text-mute"
                  >
                    <PhoneIcon className="h-5 w-5 text-[#c2c2c2]" />
                    <span className="link-underline">{studio.phone}</span>
                  </a>
                </li>
                <li className="flex items-center gap-4 text-[15px] text-ink-soft">
                  <PinIcon className="h-5 w-5 text-[#c2c2c2]" />
                  {studio.city} — {studio.country}
                </li>
              </ul>
            </Reveal>
          </div>

          <div className="lg:col-span-7">
            <Reveal delay={0.15}>
              {status === "sent" ? (
                <motion.div
                  initial={{ opacity: 0, y: 16 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="rounded-[4px] border border-[#efefef] bg-[#fafafa] p-10 text-center"
                >
                  <AwardIcon className="mx-auto h-8 w-8 text-[#c2c2c2]" />
                  <h3 className="mt-5 text-xl font-medium tracking-display">
                    Thank you — message received.
                  </h3>
                  <p className="mx-auto mt-3 max-w-[44ch] text-[14.5px] leading-relaxed text-mute">
                    Your enquiry has been logged. Florian will get back to you shortly
                    at the address you provided.
                  </p>
                  <button
                    type="button"
                    onClick={() => setStatus("idle")}
                    className="mt-7 rounded-full border border-[#e0e0e0] px-6 py-3 text-[11px] uppercase tracking-[0.2em] text-ink-soft transition-colors hover:border-[#0a0a0a]"
                  >
                    Send another message
                  </button>
                </motion.div>
              ) : (
                <form onSubmit={onSubmit} className="space-y-5" noValidate>
                  <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                    <Field label="Name" name="name" required placeholder="Your name" />
                    <Field
                      label="Email"
                      name="email"
                      type="email"
                      required
                      placeholder="you@studio.com"
                    />
                  </div>
                  <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
                    <Field label="Company" name="company" placeholder="Optional" />
                    <div>
                      <label
                        htmlFor="subject"
                        className="block text-[10.5px] uppercase tracking-[0.22em] text-faint"
                      >
                        Subject
                      </label>
                      <select
                        id="subject"
                        name="subject"
                        defaultValue={SUBJECTS[0]}
                        className="mt-2.5 w-full appearance-none border-b border-[#e4e4e4] bg-transparent pb-3 text-[15px] text-ink-soft outline-none transition-colors focus:border-[#0a0a0a]"
                      >
                        {SUBJECTS.map((s) => (
                          <option key={s} value={s}>
                            {s}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div>
                    <label
                      htmlFor="message"
                      className="block text-[10.5px] uppercase tracking-[0.22em] text-faint"
                    >
                      Message
                    </label>
                    <textarea
                      id="message"
                      name="message"
                      required
                      rows={5}
                      placeholder="Tell us about your project, timing and scope…"
                      className="mt-2.5 w-full resize-none border-b border-[#e4e4e4] bg-transparent pb-3 text-[15px] leading-relaxed text-ink-soft outline-none transition-colors placeholder:text-[#c9c9c9] focus:border-[#0a0a0a]"
                    />
                  </div>

                  {error && (
                    <p className="text-[13px] text-[#a33]">{error}</p>
                  )}

                  <div className="flex flex-wrap items-center gap-5 pt-2">
                    <button
                      type="submit"
                      disabled={status === "sending"}
                      className="group inline-flex items-center gap-3 rounded-full bg-[#0a0a0a] px-8 py-4.5 text-[11px] font-medium uppercase tracking-[0.22em] text-white transition-all duration-300 hover:bg-[#2a2a2a] disabled:opacity-50"
                    >
                      {status === "sending" ? "Sending…" : "Send enquiry"}
                      <ArrowUpRight className="h-4 w-4 transition-transform duration-300 group-hover:-translate-y-0.5 group-hover:translate-x-0.5" />
                    </button>
                    <span className="text-[12px] text-faint">
                      Or email{" "}
                      <a href={`mailto:${studio.email}`} className="link-underline text-mute">
                        {studio.email}
                      </a>
                    </span>
                  </div>
                </form>
              )}
            </Reveal>
          </div>
        </div>
      </div>
    </section>
  );
}

function Field({
  label,
  name,
  type = "text",
  required,
  placeholder,
}: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
  placeholder?: string;
}) {
  return (
    <div>
      <label
        htmlFor={name}
        className="block text-[10.5px] uppercase tracking-[0.22em] text-faint"
      >
        {label}
        {required ? " *" : ""}
      </label>
      <input
        id={name}
        name={name}
        type={type}
        required={required}
        placeholder={placeholder}
        className="mt-2.5 w-full border-b border-[#e4e4e4] bg-transparent pb-3 text-[15px] text-ink-soft outline-none transition-colors placeholder:text-[#c9c9c9] focus:border-[#0a0a0a]"
      />
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Footer                                                              */
/* ------------------------------------------------------------------ */

export function Footer() {
  return (
    <footer className="relative border-t border-[#efefef] pb-12 pt-16">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <div className="flex flex-col gap-10 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <p className="text-[13px] font-semibold uppercase tracking-[0.22em]">
              Florian Gross Design Studio
            </p>
            <p className="mt-2 text-[11px] uppercase tracking-[0.28em] text-faint">
              Product &amp; Interior Design · Barcelona
            </p>
            <a
              href="https://www.muellermoebel.de/en/KONNEX-Set/KX200-312"
              target="_blank"
              rel="noopener noreferrer"
              className="mt-6 inline-flex items-center gap-2.5 rounded-full border border-[#e0e0e0] px-5 py-3 text-[10.5px] uppercase tracking-[0.2em] text-ink-soft transition-colors hover:border-[#0a0a0a]"
            >
              <CartIcon className="h-3.5 w-3.5 text-[#b5b5b5]" />
              Buy Konnex — Worldwide
              <ArrowUpRight className="h-3.5 w-3.5" />
            </a>
          </div>

          <div className="flex gap-14">
            <div>
              <p className="text-[10px] uppercase tracking-[0.24em] text-[#c2c2c2]">
                Navigate
              </p>
              <ul className="mt-4 space-y-2.5 text-[13px]">
                    {[
                  ["#work", "Work"],
                  ["#konnex", "Konnex"],
                  ["#about", "About"],
                  ["#recognition", "Recognition"],
                  ["#journal", "Instagram"],
                  ["#contact", "Contact"],
                ].map(([href, label]) => (
                  <li key={href}>
                    <a
                      href={href}
                      onClick={(e) => {
                        e.preventDefault();
                        navigateToSection(href.replace("#", ""));
                      }}
                      className="link-underline text-mute"
                    >
                      {label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>

            <div>
              <p className="text-[10px] uppercase tracking-[0.24em] text-[#c2c2c2]">
                Follow
              </p>
              <ul className="mt-4 space-y-2.5 text-[13px]">
                <li>
                  <a
                    href={studio.instagram}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2.5 text-mute transition-colors hover:text-ink-soft"
                  >
                    <InstagramIcon className="h-4 w-4 text-[#c2c2c2]" />
                    {studio.instagramHandle}
                  </a>
                </li>
                <li>
                  <a
                    href={studio.linkedin}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2.5 text-mute transition-colors hover:text-ink-soft"
                  >
                    <LinkedInIcon className="h-4 w-4 text-[#c2c2c2]" />
                    LinkedIn
                  </a>
                </li>
                <li>
                  <a
                    href={studio.facebook}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex items-center gap-2.5 text-mute transition-colors hover:text-ink-soft"
                  >
                    <FacebookIcon className="h-4 w-4 text-[#c2c2c2]" />
                    Facebook
                  </a>
                </li>
                <li>
                  <a
                    href={`mailto:${studio.email}`}
                    className="flex items-center gap-2.5 text-mute transition-colors hover:text-ink-soft"
                  >
                    <MailIcon className="h-4 w-4 text-[#c2c2c2]" />
                    Email
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <div className="mt-14 flex flex-col gap-3 border-t border-[#f2f2f2] pt-7 text-[11px] text-faint sm:flex-row sm:items-center sm:justify-between">
          <p>
            © 2011–{new Date().getFullYear()} Florian Gross Design Studio. All rights
            reserved.
          </p>
          <p className="flex items-center gap-4">
            <span>Barcelona, Spain</span>
            <span className="h-[3px] w-[3px] rounded-full bg-[#d6d6d6]" />
            <a href="#top" className="link-underline">
              Back to top
            </a>
          </p>
        </div>
      </div>
    </footer>
  );
}
