"use client";

import gsap from "gsap";
import { useEffect, useLayoutEffect, useRef, useState } from "react";

type Token =
  | { kind: "digit"; value: string; slot: string }
  | { kind: "colon"; slot: string }
  | { kind: "period"; value: string; slot: string };

function tokenize(date: Date): Token[] {
  const hh = date.getHours();
  const h12 = ((hh + 11) % 12) + 1;
  const period = hh >= 12 ? "PM" : "AM";
  const mm = String(date.getMinutes()).padStart(2, "0");
  const ss = String(date.getSeconds()).padStart(2, "0");
  const hStr = String(h12).padStart(2, "0");

  return [
    { kind: "digit", value: hStr[0], slot: "h1" },
    { kind: "digit", value: hStr[1], slot: "h2" },
    { kind: "colon", slot: "c1" },
    { kind: "digit", value: mm[0], slot: "m1" },
    { kind: "digit", value: mm[1], slot: "m2" },
    { kind: "colon", slot: "c2" },
    { kind: "digit", value: ss[0], slot: "s1" },
    { kind: "digit", value: ss[1], slot: "s2" },
    { kind: "period", value: period, slot: "p" },
  ];
}

export function LiveClock() {
  const [now, setNow] = useState(() => new Date());

  useEffect(() => {
    const id = window.setInterval(() => setNow(new Date()), 1000);
    return () => window.clearInterval(id);
  }, []);

  const tokens = tokenize(now);

  return (
    <div className="relative shrink-0 rounded-2xl border border-slate-200/90 bg-white/85 px-5 py-4 shadow-sm backdrop-blur-md dark:border-white/15 dark:bg-white/10 dark:shadow-none">
      <div
        className="text-[11px] uppercase tracking-widest text-slate-500 dark:text-white/75"
        suppressHydrationWarning
      >
        {now.toLocaleDateString("en-US", {
          weekday: "long",
          month: "short",
          day: "numeric",
        })}
      </div>

      <div className="mt-1.5 flex items-baseline overflow-hidden font-mono text-3xl font-bold tabular-nums text-slate-900 dark:text-white">
        {tokens.map((t) => {
          if (t.kind === "digit") {
            return <Digit key={t.slot} value={t.value} />;
          }
          if (t.kind === "colon") {
            return (
              <span
                key={t.slot}
                className="inline-block px-0.5 text-slate-700 dark:text-white/90"
              >
                :
              </span>
            );
          }
          return (
            <span
              key={t.slot}
              className="ml-2 inline-block self-end pb-1 text-xs font-semibold tracking-[0.2em] text-slate-500 dark:text-white/70"
            >
              {t.value}
            </span>
          );
        })}
      </div>

      <div className="mt-2 flex items-center gap-2 text-xs text-slate-600 dark:text-white/75">
        <span className="relative flex size-2">
          <span className="relative inline-flex size-2 rounded-full bg-emerald-400" />
        </span>
        Pipeline online
      </div>
    </div>
  );
}

function Digit({ value }: { value: string }) {
  const ref = useRef<HTMLSpanElement>(null);
  const prev = useRef<string>(value);

  useLayoutEffect(() => {
    if (!ref.current) return;
    if (prev.current === value) return;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduced) {
      prev.current = value;
      return;
    }

    gsap.fromTo(
      ref.current,
      {
        y: 22,
        opacity: 0,
        rotateX: -85,
        filter: "blur(4px)",
      },
      {
        y: 0,
        opacity: 1,
        rotateX: 0,
        filter: "blur(0px)",
        duration: 0.55,
        ease: "back.out(2)",
      },
    );
    prev.current = value;
  }, [value]);

  return (
    <span
      ref={ref}
      className="relative inline-block min-w-[0.6em] text-center text-slate-900 will-change-transform dark:text-white"
      style={{ transformStyle: "preserve-3d" }}
    >
      {value}
    </span>
  );
}
