"use client";

import Link from "next/link";
import { useEffect, useRef } from "react";

import { useGameStore } from "@/store/gameStore";
import type { ProblemCount } from "@/store/gameStore";

const problemCounts: ProblemCount[] = [5, 10];

export default function StartControls() {
  const startLinkRef = useRef<HTMLAnchorElement>(null);
  const selectedProblemCount = useGameStore(
    (state) => state.selectedProblemCount,
  );
  const setProblemCount = useGameStore((state) => state.setProblemCount);
  const initSession = useGameStore((state) => state.initSession);

  useEffect(() => {
    startLinkRef.current?.focus();
  }, []);

  return (
    <div className="flex flex-col gap-5">
      <div>
        <Link
          ref={startLinkRef}
          href={`/play?count=${selectedProblemCount}`}
          onClick={() => initSession(selectedProblemCount)}
          className="inline-flex h-12 items-center justify-center rounded-md bg-emerald-700 px-6 text-base font-semibold text-white transition hover:bg-emerald-800 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
        >
          연습 시작
        </Link>
      </div>

      <fieldset className="space-y-3">
        <legend className="text-sm font-semibold text-slate-700">
          문제 수
        </legend>
        <div
          className="inline-flex gap-1 rounded-md border border-slate-300 bg-white p-1 shadow-sm"
          role="group"
          aria-label="문제 수 선택"
        >
          {problemCounts.map((count) => {
            const selected = selectedProblemCount === count;

            return (
              <button
                key={count}
                type="button"
                onClick={() => setProblemCount(count)}
                aria-pressed={selected}
                className={`h-10 min-w-16 rounded px-4 text-base font-semibold transition focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 ${
                  selected
                    ? "bg-emerald-700 text-white"
                    : "text-slate-700 hover:bg-slate-100"
                }`}
              >
                {count}
              </button>
            );
          })}
        </div>
      </fieldset>
    </div>
  );
}
