"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { motion } from "framer-motion";
import {
  ArrowRight, ChevronDown, Compass, Sparkles, Refresh, Users, Heart, Home, DollarSign, Book, Server,
} from "@/components/ui/icons";
import { useContactModal } from "@/components/providers/ContactModal";
import { Aurora, DotWave, Counter } from "../services/fx";
import {
  CAREERS_EMAIL, CAREER_STATS, VALUES, PERKS, HIRING_STEPS, ROLES, getDepartments,
} from "@/data/careers";

/**
 * Careers page (client). Hero → why-join values → perks → open roles (filterable)
 * → hiring process → life at Cerkel → CTA. Brand-strict: dark tokens, Google
 * Sans, orange/gold, animated counters + scroll reveals.
 */
const EASE = [0.21, 0.47, 0.32, 0.98];
const container = { hidden: {}, show: { transition: { staggerChildren: 0.1 } } };
const word = { hidden: { yPercent: 120 }, show: { yPercent: 0, transition: { duration: 0.7, ease: EASE } } };
const rise = { hidden: { opacity: 0, y: 28 }, show: { opacity: 1, y: 0, transition: { duration: 0.6, ease: EASE } } };

const ICONS = {
  compass: Compass, sparkles: Sparkles, refresh: Refresh, users: Users,
  heart: Heart, home: Home, dollar: DollarSign, book: Book, server: Server,
};
const Icon = ({ name, className }) => {
  const C = ICONS[name] || Sparkles;
  return <C className={className} />;
};

const HERO_LEAD = ["Build what", "matters,", "with people", "who"];
const LIFE_IMAGES = ["/images/opt/HeroBanner1.webp", "/images/opt/Pillar2.webp", "/images/opt/HeroBanner3.png", "/images/opt/Pillar1.webp"];
/* Balanced bento spans (fills a 4×2 grid with no gaps). */
const LIFE_SPANS = ["col-span-2 row-span-2", "col-span-2", "", ""];

function Eyebrow({ children }) {
  return <span className="font-heading text-sm font-semibold uppercase tracking-wider text-primary">{children}</span>;
}

function scrollToRoles(e) {
  e.preventDefault();
  const el = document.getElementById("roles");
  if (!el) return;
  if (typeof window !== "undefined" && window.lenis) window.lenis.scrollTo(el, { offset: -100 });
  else el.scrollIntoView({ behavior: "smooth" });
}

export default function CareersView() {
  const { open: openContact } = useContactModal();
  const departments = getDepartments();
  const [dept, setDept] = useState("All");
  const [openVal, setOpenVal] = useState(-1);
  const roles = dept === "All" ? ROLES : ROLES.filter((r) => r.department === dept);

  return (
    <>
      {/* ── 1 · Hero ──────────────────────────────────────────────────── */}
      <section className="relative isolate overflow-hidden bg-background pb-12 pt-20 text-foreground md:pb-16 md:pt-28">
        <Image src="/images/opt/HeroBanner2.webp" alt="" fill priority sizes="100vw" className="-z-20 object-cover opacity-40" />
        <span className="absolute inset-0 -z-10 bg-gradient-to-b from-background/40 via-background/70 to-background" />
        <Aurora className="opacity-50" />
        <DotWave />

        <div className="container relative">
          <motion.div variants={container} initial="hidden" animate="show" className="mx-auto max-w-3xl text-center">
            <motion.span variants={rise} className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
              <span className="h-1.5 w-1.5 rounded-full bg-primary" /> Careers at Cerkel
            </motion.span>

            <h1 className="mt-6 font-heading text-5xl font-bold leading-[1.05] tracking-tight sm:text-6xl md:text-7xl">
              {HERO_LEAD.map((w, i) => (
                <span key={i} className="inline-block overflow-hidden pb-[0.08em] align-bottom">
                  <motion.span variants={word} className="inline-block">{w}</motion.span>
                  <span>&nbsp;</span>
                </span>
              ))}
              <span className="inline-block overflow-hidden pb-[0.08em] align-bottom">
                <motion.span variants={word} className="animate-text-shimmer inline-block bg-gradient-to-r from-primary via-accent to-primary bg-[length:200%_auto] bg-clip-text text-transparent">care.</motion.span>
              </span>
            </h1>

            <motion.p variants={rise} className="mx-auto mt-6 max-w-2xl text-base leading-relaxed text-muted-foreground sm:text-lg">
              We&apos;re a remote-first team of senior builders shipping serious products for startups and
              enterprises. Small teams, real ownership, and work you&apos;ll be proud of.
            </motion.p>

            <motion.div variants={rise} className="mt-9 flex flex-wrap items-center justify-center gap-4">
              <button onClick={scrollToRoles} className="group inline-flex items-center gap-2.5 rounded-full bg-gradient-to-r from-primary to-accent px-7 py-3.5 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/30 transition-all duration-300 hover:-translate-y-0.5">
                See open roles
                <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
              </button>
              <a href={`mailto:${CAREERS_EMAIL}`} className="rounded-full border border-border bg-surface/50 px-7 py-3.5 text-sm font-semibold text-foreground backdrop-blur transition-colors duration-300 hover:border-primary/50">
                Send an open application
              </a>
            </motion.div>
          </motion.div>

          {/* Stats strip */}
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.4 }} className="mx-auto mt-16 grid max-w-5xl grid-cols-2 gap-px overflow-hidden rounded-2xl border border-border bg-border sm:grid-cols-4">
            {CAREER_STATS.map((s) => (
              <motion.div key={s.label} variants={rise} className="bg-surface/60 px-6 py-6 text-center backdrop-blur">
                <div className="font-heading text-3xl font-bold text-primary sm:text-4xl"><Counter end={s.value} suffix={s.suffix || ""} decimals={s.decimals || 0} /></div>
                <div className="mt-1 text-xs uppercase tracking-wider text-muted-foreground">{s.label}</div>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── 2 · Values (why join) ─────────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background py-16 text-foreground md:py-24">
        <div className="pointer-events-none absolute left-1/2 top-0 h-72 w-[44rem] -translate-x-1/2 rounded-full bg-primary/[0.05] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <Eyebrow>How we work</Eyebrow>
            <h2 className="mt-3 font-heading text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">The way we do things.</h2>
            <p className="mt-4 text-base leading-relaxed text-muted-foreground">Six principles that shape how we build, hire and treat each other.</p>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.1 }} className="mt-12 grid items-start gap-4 lg:grid-cols-2">
            {VALUES.map((v, i) => {
              const isOpen = i === openVal;
              return (
                <motion.div
                  key={v.title}
                  variants={rise}
                  className={
                    "overflow-hidden rounded-2xl border transition-all duration-300 " +
                    (isOpen
                      ? "border-primary/50 bg-surface shadow-xl shadow-primary/10"
                      : "border-border bg-surface/40 hover:border-primary/30 hover:bg-surface/70")
                  }
                >
                  <button
                    onClick={() => setOpenVal(isOpen ? -1 : i)}
                    aria-expanded={isOpen}
                    className="flex w-full items-center gap-4 px-6 py-5 text-left"
                  >
                    <span
                      className={
                        "flex h-11 w-11 shrink-0 items-center justify-center rounded-xl transition-colors duration-300 " +
                        (isOpen ? "bg-primary text-primary-foreground" : "bg-primary/10 text-primary")
                      }
                    >
                      <Icon name={v.icon} className="h-5 w-5" />
                    </span>
                    <h3
                      className={
                        "flex-1 font-heading text-lg font-semibold leading-snug transition-colors " +
                        (isOpen ? "text-primary" : "text-foreground")
                      }
                    >
                      {v.title}
                    </h3>
                    <span
                      className={
                        "flex h-8 w-8 shrink-0 items-center justify-center rounded-full border transition-all duration-300 " +
                        (isOpen
                          ? "rotate-180 border-primary/40 bg-primary/15 text-primary"
                          : "border-border text-muted-foreground")
                      }
                    >
                      <ChevronDown className="h-4 w-4" />
                    </span>
                  </button>

                  <motion.div
                    initial={false}
                    animate={{ height: isOpen ? "auto" : 0, opacity: isOpen ? 1 : 0 }}
                    transition={{ duration: 0.4, ease: EASE }}
                    className="overflow-hidden"
                  >
                    <p className="px-6 pb-6 pl-[5.75rem] text-sm leading-relaxed text-muted-foreground">
                      {v.desc}
                    </p>
                  </motion.div>
                </motion.div>
              );
            })}
          </motion.div>
        </div>
      </section>

      {/* ── 3 · Perks ─────────────────────────────────────────────────── */}
      <section className="relative bg-background py-16 text-foreground md:py-24">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <Eyebrow>Perks &amp; benefits</Eyebrow>
            <h2 className="mt-3 font-heading text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">Looked after, so you can build.</h2>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.1 }} className="mt-12 grid grid-cols-2 gap-px overflow-hidden rounded-3xl border border-border bg-border lg:grid-cols-4">
            {PERKS.map((p) => (
              <motion.div key={p.title} variants={rise} className="group relative bg-background p-7 transition-colors duration-300 hover:bg-surface/60">
                {/* top accent line on hover */}
                <span className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
                <span className="flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary transition-all duration-300 group-hover:scale-105 group-hover:bg-primary group-hover:text-primary-foreground">
                  <Icon name={p.icon} className="h-5 w-5" />
                </span>
                <h3 className="mt-4 font-heading text-base font-semibold">{p.title}</h3>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{p.desc}</p>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── 4 · Open roles ────────────────────────────────────────────── */}
      <section id="roles" className="relative scroll-mt-24 overflow-hidden bg-background py-16 text-foreground md:py-24">
        <div className="pointer-events-none absolute right-0 top-1/4 h-72 w-[36rem] rounded-full bg-primary/[0.06] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <Eyebrow>Open roles</Eyebrow>
            <h2 className="mt-3 font-heading text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">Find your seat.</h2>
          </motion.div>

          {/* Department filter */}
          <div className="mt-10 flex flex-wrap justify-center gap-2">
            {departments.map((d) => {
              const active = d === dept;
              return (
                <button
                  key={d}
                  onClick={() => setDept(d)}
                  className={"rounded-full border px-4 py-2 text-sm font-medium transition-all duration-300 " + (active ? "border-primary/50 bg-primary/15 text-primary" : "border-border bg-surface/40 text-muted-foreground hover:border-primary/30 hover:text-foreground")}
                >
                  {d}
                </button>
              );
            })}
          </div>

          {/* Role list */}
          <div className="mt-10 overflow-hidden rounded-3xl border border-border bg-surface/30">
            {roles.length === 0 && (
              <p className="px-6 py-10 text-center text-sm text-muted-foreground">No roles in this team right now — but we&apos;re always meeting great people.</p>
            )}
            {roles.map((r, i) => (
              <Link
                key={r.id}
                href={`/careers/${r.id}`}
                className={"group relative flex flex-col gap-3 p-6 transition-colors duration-300 hover:bg-surface/70 sm:flex-row sm:items-center sm:gap-6 sm:p-7 " + (i > 0 ? "border-t border-border/70" : "")}
              >
                <span className="pointer-events-none absolute inset-y-0 left-0 w-1 origin-top scale-y-0 bg-gradient-to-b from-primary to-accent transition-transform duration-300 group-hover:scale-y-100" />
                <div className="min-w-0 flex-1">
                  <h3 className="font-heading text-lg font-semibold transition-colors duration-300 group-hover:text-primary sm:text-xl">{r.title}</h3>
                  <p className="mt-1 text-sm text-muted-foreground">{r.summary}</p>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                  <span className="rounded-full border border-border bg-background/60 px-3 py-1 text-xs text-muted-foreground">{r.department}</span>
                  <span className="rounded-full border border-border bg-background/60 px-3 py-1 text-xs text-muted-foreground">{r.location}</span>
                  <span className="rounded-full border border-border bg-background/60 px-3 py-1 text-xs text-muted-foreground">{r.type}</span>
                </div>
                <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground transition-all duration-300 group-hover:border-primary group-hover:bg-primary group-hover:text-primary-foreground">
                  <ArrowRight className="h-4 w-4" />
                </span>
              </Link>
            ))}
          </div>
        </div>
      </section>

      {/* ── 5 · Hiring process ────────────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background py-16 text-foreground md:py-24">
        <div className="pointer-events-none absolute left-1/2 top-1/2 h-[22rem] w-[42rem] -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/[0.05] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <Eyebrow>Hiring process</Eyebrow>
            <h2 className="mt-3 font-heading text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">What to expect.</h2>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.1 }} className="relative mt-14 grid gap-6 sm:grid-cols-2 lg:grid-cols-5 lg:gap-4">
            <div className="pointer-events-none absolute left-0 right-0 top-7 hidden h-px bg-gradient-to-r from-primary/40 via-primary/20 to-accent/40 lg:block" />
            {HIRING_STEPS.map((step, i) => (
              <motion.div key={step.title} variants={rise} className="relative">
                <span className="relative z-10 flex h-14 w-14 items-center justify-center rounded-2xl border border-primary/30 bg-surface/70 font-heading text-base font-bold text-primary shadow-[0_0_22px_-6px_rgb(var(--primary)/0.5)] backdrop-blur">
                  {String(i + 1).padStart(2, "0")}
                </span>
                <h3 className="mt-4 font-heading text-base font-semibold">{step.title}</h3>
                <p className="mt-1.5 text-sm leading-relaxed text-muted-foreground">{step.desc}</p>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── 6 · Life at Cerkel ────────────────────────────────────────── */}
      <section className="relative bg-background py-16 text-foreground md:py-24">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="max-w-2xl">
            <Eyebrow>Life at Cerkel</Eyebrow>
            <h2 className="mt-3 font-heading text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl">A team that builds together.</h2>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.15 }} className="mt-10 grid auto-rows-[11rem] grid-cols-2 gap-4 lg:auto-rows-[14rem] lg:grid-cols-4">
            {LIFE_IMAGES.map((src, i) => (
              <motion.div key={src} variants={rise} className={"group relative overflow-hidden rounded-2xl border border-border " + LIFE_SPANS[i]}>
                <Image src={src} alt="Life at Cerkel" fill sizes="(min-width:1024px) 50vw, 100vw" className="object-cover transition-transform duration-700 group-hover:scale-105" />
                <span className="absolute inset-0 bg-gradient-to-t from-background/40 to-transparent" />
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── 7 · CTA ───────────────────────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background pb-16 md:pb-24">
        <div className="container">
          <div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-primary via-primary to-accent p-8 text-center sm:p-16">
            <div className="pointer-events-none absolute -right-10 -top-10 h-56 w-56 rounded-full bg-white/10 blur-2xl" />
            <div className="pointer-events-none absolute -bottom-12 -left-8 h-56 w-56 rounded-full bg-black/10 blur-2xl" />
            <div className="relative mx-auto max-w-2xl">
              <h2 className="font-heading text-3xl font-bold leading-tight tracking-tight text-background sm:text-5xl">Don&apos;t see your role?</h2>
              <p className="mt-4 text-base leading-relaxed text-background/80">We&apos;re always looking for exceptional people. Tell us what you do best and how you&apos;d add to the team.</p>
              <div className="mt-8 flex flex-wrap items-center justify-center gap-4">
                <a href={`mailto:${CAREERS_EMAIL}`} className="group inline-flex items-center gap-2.5 rounded-full bg-background px-7 py-3.5 text-sm font-semibold text-foreground shadow-xl shadow-black/25 transition-all duration-300 hover:-translate-y-0.5">
                  Send an open application
                  <span className="flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground transition-transform duration-300 group-hover:translate-x-0.5"><ArrowRight className="h-3.5 w-3.5" /></span>
                </a>
                <button onClick={openContact} className="rounded-full border border-background/40 px-7 py-3.5 text-sm font-semibold text-background transition-colors duration-300 hover:bg-background/10">
                  Get in touch
                </button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
