// WORK + STATS

const WorkCard = ({ item, idx }) => {
  const [hover, setHover] = React.useState(false);
  const [imgFailed, setImgFailed] = React.useState(false);
  // Gradient acts as a fallback when the photo fails to load.
  const grads = [
    ["#d4ff3a", "#1a3300"],
    ["#ff5c2a", "#2a0e00"],
    ["#5b8cff", "#001a3a"],
    ["#ff7ad9", "#2a0019"],
    ["#7affd4", "#003322"],
    ["#ffd166", "#332300"],
  ];
  const [g1, g2] = grads[(item.hue - 1) % grads.length];
  return (
    <article
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      className="group relative rounded-[22px] overflow-hidden border border-white/10 card-hov reveal"
      style={{ transitionDelay: `${idx*0.05}s` }}
    >
      <div className="aspect-[4/5] relative" style={{
        background: `radial-gradient(80% 60% at 30% 25%, ${g1}55 0%, transparent 60%), linear-gradient(160deg, ${g2} 0%, #0a0a0b 70%)`
      }}>
        {/* Cover photo */}
        {item.image && !imgFailed && (
          <img
            src={item.image}
            alt={item.client}
            loading="lazy"
            decoding="async"
            onError={() => setImgFailed(true)}
            className={"absolute inset-0 w-full h-full object-cover transition-transform duration-700 ease-out " + (hover ? "scale-[1.04]" : "scale-100")}
          />
        )}

        {/* Bottom-up gradient for text legibility */}
        <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent" />

        {/* top label */}
        <div className="absolute top-4 left-4 right-4 flex items-start justify-between">
          <span className="font-mono text-[10.5px] tracking-[0.18em] text-white/85 bg-black/30 backdrop-blur-sm rounded-full px-2.5 py-1">CASE / 0{idx+1}</span>
          <span className="font-mono text-[10.5px] text-white/85 bg-black/30 backdrop-blur-sm rounded-full px-2.5 py-1">{item.cat}</span>
        </div>

        {/* big result */}
        <div className={"absolute left-5 right-5 bottom-5 transition-all duration-500 " + (hover ? "translate-y-0" : "translate-y-2")}>
          <div className="display text-[64px] sm:text-[72px] leading-[0.85] text-white drop-shadow-[0_2px_12px_rgba(0,0,0,0.5)]">{item.result}</div>
          <div className="mt-1 font-mono text-[11px] text-white/85 uppercase tracking-[0.14em]">{item.metric}</div>
        </div>

        {/* hover overlay */}
        <div className={"absolute inset-0 transition-opacity duration-500 bg-black/65 backdrop-blur-[3px] flex flex-col justify-between p-5 " + (hover ? "opacity-100" : "opacity-0")}>
          <div className="flex items-start justify-between">
            <span className="font-mono text-[10.5px] tracking-[0.18em] text-white/70">CASE / 0{idx+1}</span>
            <span className="h-9 w-9 rounded-full bg-accent text-black flex items-center justify-center">
              <Icon name="arrow-up-right" size={15} strokeWidth={2.4} />
            </span>
          </div>
          <div>
            <div className="font-mono text-[10.5px] tracking-[0.16em] text-white/55 uppercase">{item.cat}</div>
            <h3 className="mt-2 display text-[28px] leading-[1.05]">{item.client}</h3>
            <div className="mt-3 flex items-baseline gap-2">
              <span className="display text-[40px] text-accent">{item.result}</span>
              <span className="font-mono text-[10.5px] uppercase tracking-[0.14em] text-white/65">{item.metric}</span>
            </div>
            <div className="mt-3 text-[13px] text-white/70 leading-[1.5]">
              90-day engagement, embedded creative, weekly reporting cadence. Read the full case →
            </div>
          </div>
        </div>
      </div>
      <div className="px-5 py-4 flex items-center justify-between">
        <h4 className="font-medium text-[15px]">{item.client}</h4>
        <span className="font-mono text-[10.5px] text-white/40">2024–25</span>
      </div>
    </article>
  );
};

const Work = () => {
  return (
    <section id="work" className="relative py-24 lg:py-32 border-t border-white/8">
      <div className="max-w-[1320px] mx-auto px-6 lg:px-10">
        <div className="flex items-end justify-between gap-8 flex-wrap">
          <SectionHead
            kicker="SELECTED WORK · 24"
            title={<>Six recent <span className="font-serif italic font-normal">stories.</span></>}
            intro="A snapshot of brands we've built engines for. Hover any card to see the inside of the work."
          />
          <a href="#contact" className="btn-ghost hidden md:inline-flex items-center gap-2 px-4 py-2.5 rounded-full text-[13.5px] reveal">
            View the index
            <Icon name="arrow-up-right" size={14} />
          </a>
        </div>

        <div className="mt-16 grid sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {window.MERCENTA.WORK.map((w, i) => <WorkCard key={w.client} item={w} idx={i} />)}
        </div>
      </div>
    </section>
  );
};

// Animated counter
const useCountUp = (target, run, opts = {}) => {
  const { dur = 1600, decimals = 0 } = opts;
  const [val, setVal] = React.useState(0);
  React.useEffect(() => {
    if (!run) return;
    let raf, start;
    const step = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(target * eased);
      if (p < 1) raf = requestAnimationFrame(step);
      else setVal(target);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [run, target, dur]);
  return decimals > 0 ? val.toFixed(decimals) : Math.round(val).toLocaleString();
};

const StatTile = ({ stat, run, idx }) => {
  const value = useCountUp(stat.v, run, { decimals: stat.float ? 1 : 0 });
  return (
    <div className="reveal" style={{ transitionDelay: `${idx*0.06}s` }}>
      <div className="font-mono text-[10.5px] text-white/40 tracking-[0.18em]">/ 0{idx+1}</div>
      <div className="mt-3 flex items-baseline">
        <span className="display text-[72px] sm:text-[88px] lg:text-[104px] tracking-[-0.05em]">{value}</span>
        {stat.suf && <span className="display text-[44px] sm:text-[52px] text-accent ml-1">{stat.suf}</span>}
      </div>
      <div className="mt-2 text-[14px] text-white/55 max-w-[200px]">{stat.label}</div>
    </div>
  );
};

const Stats = () => {
  const ref = React.useRef(null);
  const [run, setRun] = React.useState(false);
  React.useEffect(() => {
    const io = new IntersectionObserver(([e]) => { if (e.isIntersecting) { setRun(true); io.disconnect(); } }, { threshold: 0.3 });
    if (ref.current) io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <section ref={ref} className="relative py-24 lg:py-32 border-t border-white/8 bg-gradient-to-b from-[var(--bg)] via-[var(--bg-2)] to-[var(--bg)]">
      <div className="max-w-[1320px] mx-auto px-6 lg:px-10">
        <div className="flex items-center gap-3 font-mono text-[11px] tracking-[0.2em] text-white/40 reveal">
          <span className="h-1.5 w-1.5 rounded-full bg-accent" />
          BY THE NUMBERS · UPDATED Q2 / 26
        </div>
        <div className="mt-12 grid sm:grid-cols-2 lg:grid-cols-4 gap-10 lg:gap-6">
          {window.MERCENTA.STATS.map((s, i) => <StatTile key={s.label} stat={s} idx={i} run={run} />)}
        </div>
      </div>
    </section>
  );
};

window.Work = Work;
window.Stats = Stats;
