"use client";

import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { CalendarCheck, X } from "lucide-react";

export interface Pulse {
  bookings30: number;
  guests30: number;
  byApartment: Record<string, number>;
  recent: { apartmentId: string; apartment: string; at: number; nights: number }[];
}

function ago(at: number) {
  const m = Math.max(1, Math.round((Date.now() - at) / 60_000));
  if (m < 60) return `${m} min ago`;
  const h = Math.round(m / 60);
  if (h < 48) return `${h} h ago`;
  return `${Math.round(h / 24)} days ago`;
}

/**
 * Real recent bookings, anonymised, shown one at a time in the corner. Only
 * events from the last 3 days, at most three per visit, never while a sheet
 * is open, dismissable in one tap. Social proof that is true.
 */
export function PulseToasts({ pulse, suspended, onPick }: { pulse: Pulse | undefined; suspended: boolean; onPick: (apartmentId: string) => void }) {
  const reduced = useReducedMotion();
  const [idx, setIdx] = React.useState(-1);
  const [visible, setVisible] = React.useState(false);
  const shown = React.useRef(0);
  const items = React.useMemo(() => (pulse?.recent ?? []).filter((r) => Date.now() - r.at < 3 * 86_400_000).slice(0, 3), [pulse]);
  const susp = React.useRef(suspended);
  susp.current = suspended;

  React.useEffect(() => {
    if (!items.length) return;
    let t: ReturnType<typeof setTimeout>;
    const next = () => {
      if (shown.current >= items.length) return;
      if (susp.current) {
        t = setTimeout(next, 8_000);
        return;
      }
      setIdx(shown.current);
      setVisible(true);
      shown.current += 1;
      t = setTimeout(() => {
        setVisible(false);
        t = setTimeout(next, 22_000);
      }, 7_000);
    };
    t = setTimeout(next, 9_000);
    return () => clearTimeout(t);
  }, [items]);

  const it = idx >= 0 ? items[idx] : null;
  return (
    <div className="pointer-events-none fixed bottom-24 left-3 z-30 md:bottom-6 md:left-6" aria-live="polite">
      <AnimatePresence>
        {visible && it ? (
          <motion.div key={idx} initial={reduced ? false : { opacity: 0, y: 16, scale: 0.96 }} animate={{ opacity: 1, y: 0, scale: 1 }} exit={{ opacity: 0, y: 10 }} transition={{ type: "spring", stiffness: 380, damping: 30 }} className="glass pointer-events-auto flex max-w-[300px] items-center gap-3 rounded-2xl p-3 pr-2 shadow-xl">
            <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-positive-500/15 text-positive-600"><CalendarCheck className="size-4" /></span>
            <button type="button" onClick={() => onPick(it.apartmentId)} className="min-w-0 flex-1 text-left">
              <span className="block truncate text-sm font-semibold">Someone booked {it.apartment}</span>
              <span className="block text-2xs text-fg-muted">{it.nights} night{it.nights > 1 ? "s" : ""} · {ago(it.at)} · tap to see it</span>
            </button>
            <button type="button" onClick={() => setVisible(false)} className="flex size-7 shrink-0 items-center justify-center rounded-full text-fg-subtle transition hover:bg-surface-2 hover:text-fg" aria-label="Dismiss"><X className="size-3.5" /></button>
          </motion.div>
        ) : null}
      </AnimatePresence>
    </div>
  );
}
