'use client';

// Countdown Timer — NiceUI (MIT) · https://niceui.dev/c/components/countdown-timer
// One self-contained file: needs only React and Tailwind CSS. Nothing else to install.

import { useEffect, useRef, useState, createElement, type SVGProps } from 'react';

function cn(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(' ');
}

// Icons from Lucide (ISC licence, lucide.dev), inlined so there is nothing to install.
type NiceIconProps = SVGProps<SVGSVGElement> & { size?: number | string; absoluteStrokeWidth?: boolean };
type LucideIcon = (props: NiceIconProps) => JSX.Element;
type LucideProps = NiceIconProps;
const niceIcon = (node: Array<[string, Record<string, string>]>): LucideIcon =>
  function Icon({ size = 24, strokeWidth = 2, absoluteStrokeWidth, children, ...rest }: NiceIconProps) {
    const sw = absoluteStrokeWidth ? (Number(strokeWidth) * 24) / Number(size) : strokeWidth;
    return createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: sw, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, ...rest }, ...node.map(([tag, attrs], i) => createElement(tag, { key: i, ...attrs })), children);
  };
const Pause = niceIcon([["rect",{"x":"14","y":"4","width":"4","height":"16","rx":"1"}],["rect",{"x":"6","y":"4","width":"4","height":"16","rx":"1"}]]);
const Play = niceIcon([["polygon",{"points":"6 3 20 12 6 21 6 3"}]]);
const RotateCcw = niceIcon([["path",{"d":"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{"d":"M3 3v5h5"}]]);
const SkipForward = niceIcon([["polygon",{"points":"5 4 15 12 5 20 5 4"}],["line",{"x1":"19","x2":"19","y1":"5","y2":"19"}]]);

// NiceUI animations and helper classes, injected once so no CSS setup is needed.
const NICEUI_CSS = ".focus-ring{outline:none}.focus-ring:focus-visible{box-shadow:0 0 0 2px #000,0 0 0 4px rgba(14,165,233,.6)}";
if (typeof document !== 'undefined' && !document.getElementById('niceui-css-10x759f')) {
  const el = document.createElement('style');
  el.id = 'niceui-css-10x759f';
  el.textContent = NICEUI_CSS;
  document.head.appendChild(el);
}

// ── components/controls/CountdownTimer.tsx ──────────────────────
const pad = (n: number) => String(n).padStart(2, '0');

/** One digit that rolls to its next value. */
function Digit({ d }: { d: string }) {
  return (
    <span className="relative inline-block h-[1.15em] w-[0.62em] overflow-hidden align-top" aria-hidden>
      <span className="cd-roll absolute inset-x-0 top-0 flex flex-col transition-transform duration-500 ease-[cubic-bezier(.2,.8,.2,1)] motion-reduce:transition-none" style={{ transform: `translateY(-${Number(d) * 10}%)` }}>
        {Array.from({ length: 10 }, (_, i) => (
          <span key={i} className="block h-[1.15em] text-center leading-[1.15em]">
            {i}
          </span>
        ))}
      </span>
    </span>
  );
}

function Unit({ value, label }: { value: number; label: string }) {
  const s = pad(value);
  return (
    <div className="flex flex-col items-center gap-2">
      <div className="flex whitespace-nowrap rounded-xl border border-white/[.08] bg-gradient-to-b from-[#1c1e22] to-[#0b0c0e] px-2.5 py-1.5 text-[34px] font-semibold leading-none tracking-tight text-[#f3f4f6] tabular-nums shadow-[inset_0_1px_0_rgba(255,255,255,.06)] sm:px-3.5 sm:text-[52px]">
        {[...s].map((d, i) => (
          <Digit key={i} d={d} />
        ))}
      </div>
      <span className="font-mono text-[10px] uppercase tracking-[0.16em] text-[#6b7079]">{label}</span>
    </div>
  );
}

export type CountdownTimerProps = {
  /** The moment to count down to. */
  to: Date | number;
  onDone?: () => void;
  className?: string;
};

/** A countdown timer to a date with rolling digits for days, hours, minutes and seconds. */
export function CountdownTimer({ to, onDone, className }: CountdownTimerProps) {
  const target = typeof to === 'number' ? to : to.getTime();
  const [now, setNow] = useState(() => Date.now());
  const done = useRef(false);
  useEffect(() => {
    const id = window.setInterval(() => setNow(Date.now()), 1000);
    return () => window.clearInterval(id);
  }, []);
  const left = Math.max(0, target - now);
  useEffect(() => {
    if (left === 0 && !done.current) {
      done.current = true;
      onDone?.();
    }
  }, [left, onDone]);
  const s = Math.floor(left / 1000);
  const parts = [
    { v: Math.min(99, Math.floor(s / 86400)), l: 'Days' },
    { v: Math.floor(s / 3600) % 24, l: 'Hours' },
    { v: Math.floor(s / 60) % 60, l: 'Minutes' },
    { v: s % 60, l: 'Seconds' },
  ];
  return (
    <div className={cn('flex items-start gap-2 sm:gap-3', className)} role="timer" aria-label={`${parts[0].v} days, ${parts[1].v} hours, ${parts[2].v} minutes left`}>
      {parts.map((p, i) => (
        <div key={p.l} className="flex items-start gap-2 sm:gap-3">
          <Unit value={p.v} label={p.l} />
          {i < parts.length - 1 && <span className="mt-2 text-[28px] font-light text-[#4b5058] sm:mt-3 sm:text-[40px]">:</span>}
        </div>
      ))}
    </div>
  );
}

export type FocusTimerProps = {
  /** Focus and break lengths in seconds. */
  focus?: number;
  rest?: number;
  className?: string;
};

/** A pomodoro-style ring timer that alternates focus and break sessions. */
export function FocusTimer({ focus = 25 * 60, rest = 5 * 60, className }: FocusTimerProps) {
  const [mode, setMode] = useState<'focus' | 'break'>('focus');
  const [left, setLeft] = useState(focus);
  const [running, setRunning] = useState(false);
  const [rounds, setRounds] = useState(0);
  const total = mode === 'focus' ? focus : rest;

  useEffect(() => {
    if (!running) return;
    const id = window.setInterval(() => setLeft((l) => Math.max(0, l - 1)), 1000);
    return () => window.clearInterval(id);
  }, [running]);

  useEffect(() => {
    if (left > 0) return;
    const next = mode === 'focus' ? 'break' : 'focus';
    if (mode === 'focus') setRounds((r) => r + 1);
    setMode(next);
    setLeft(next === 'focus' ? focus : rest);
  }, [left, mode, focus, rest]);

  const R = 84;
  const C = 2 * Math.PI * R;
  const k = 1 - left / total;
  return (
    <div className={cn('flex flex-col items-center gap-5', className)}>
      <div className="relative h-52 w-52">
        <svg viewBox="0 0 200 200" className="h-full w-full -rotate-90" aria-hidden>
          <circle cx="100" cy="100" r={R} fill="none" stroke="rgba(255,255,255,.07)" strokeWidth="8" />
          <circle cx="100" cy="100" r={R} fill="none" stroke={mode === 'focus' ? '#7dd3fc' : '#86efac'} strokeWidth="8" strokeLinecap="round" strokeDasharray={C} strokeDashoffset={C * (1 - k)} className="transition-[stroke-dashoffset] duration-1000 ease-linear motion-reduce:transition-none" />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center" role="timer" aria-live="off" aria-label={`${mode} ${Math.floor(left / 60)} minutes ${left % 60} seconds left`}>
          <span className={cn('font-mono text-[10px] uppercase tracking-[0.18em]', mode === 'focus' ? 'text-[#7dd3fc]' : 'text-emerald-300')}>{mode === 'focus' ? 'Focus' : 'Break'}</span>
          <span className="mt-1 text-[44px] font-semibold tabular-nums tracking-tight text-[#f3f4f6]">
            {pad(Math.floor(left / 60))}:{pad(left % 60)}
          </span>
          <span className="mt-1 flex gap-1" aria-label={`${rounds % 4} of 4 rounds`}>
            {Array.from({ length: 4 }, (_, i) => (
              <span key={i} className={cn('h-1.5 w-1.5 rounded-full', i < rounds % 4 ? 'bg-[#7dd3fc]' : 'bg-white/15')} />
            ))}
          </span>
        </div>
      </div>
      <div className="flex items-center gap-2">
        <button onClick={() => (setRunning(false), setLeft(total))} aria-label="Reset" className="focus-ring grid h-10 w-10 place-items-center rounded-full text-[#8b9099] hover:bg-white/[.05] hover:text-[#f3f4f6]">
          <RotateCcw className="h-4 w-4" />
        </button>
        <button onClick={() => setRunning((r) => !r)} aria-label={running ? 'Pause' : 'Start'} className="focus-ring grid h-12 w-12 place-items-center rounded-full bg-[#38bdf8] text-[#000000] shadow-[0_8px_24px_-8px_rgba(56,189,248,.7)] transition-transform active:scale-95">
          {running ? <Pause className="h-5 w-5" /> : <Play className="ml-0.5 h-5 w-5" />}
        </button>
        <button onClick={() => setLeft(0)} aria-label="Skip to next session" className="focus-ring grid h-10 w-10 place-items-center rounded-full text-[#8b9099] hover:bg-white/[.05] hover:text-[#f3f4f6]">
          <SkipForward className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}

export function CountdownTimerDemo() {
  const [target] = useState(() => Date.now() + ((3 * 24 + 7) * 3600 + 42 * 60 + 18) * 1000);
  return (
    <div className="flex w-full max-w-3xl flex-col items-center gap-10 lg:flex-row lg:justify-center">
      <div className="flex flex-col items-center gap-4">
        <p className="text-[13px] text-[#8b9099]">Launch in</p>
        <CountdownTimer to={target} />
      </div>
      <FocusTimer focus={25 * 60} rest={5 * 60} />
    </div>
  );
}
