"use client";
import { useEffect, useState } from "react";

const SCALES = [113, 130, 150];

export default function FontSizeControl() {
  const [scaleIndex, setScaleIndex] = useState(1);

  useEffect(() => {
    const saved = localStorage.getItem("fontScale");
    if (saved) {
      const idx = SCALES.indexOf(parseFloat(saved));
      if (idx !== -1) { setScaleIndex(idx); document.documentElement.style.fontSize = `${saved}%`; return; }
    }
    fetch("/api/font-scale-default").then((r) => r.json()).then((d) => {
      const idx = typeof d.defaultFontScaleIndex === "number" ? d.defaultFontScaleIndex : 1;
      const clamped = Math.max(0, Math.min(SCALES.length - 1, idx));
      setScaleIndex(clamped);
      document.documentElement.style.fontSize = `${SCALES[clamped]}%`;
    }).catch(() => {});
  }, []);

  function apply(idx: number) {
    const clamped = Math.max(0, Math.min(SCALES.length - 1, idx));
    setScaleIndex(clamped);
    document.documentElement.style.fontSize = `${SCALES[clamped]}%`;
    localStorage.setItem("fontScale", String(SCALES[clamped]));
  }

  return (
    <div className="flex items-center bg-neutral-900 border border-neutral-800 rounded-full overflow-hidden">
      <button
        onClick={() => apply(scaleIndex - 1)}
        disabled={scaleIndex === 0}
        title="Smaller text"
        className="w-7 h-7 flex items-center justify-center text-neutral-400 hover:text-white hover:bg-neutral-800 disabled:opacity-30 text-[9px] font-bold transition-colors"
      >
        F-
      </button>
      <button
        onClick={() => apply(1)}
        title="Reset text size"
        className="w-7 h-7 flex items-center justify-center text-neutral-300 hover:text-white hover:bg-neutral-800 text-[10px] font-bold border-x border-neutral-800 transition-colors"
      >
        F
      </button>
      <button
        onClick={() => apply(scaleIndex + 1)}
        disabled={scaleIndex === SCALES.length - 1}
        title="Larger text"
        className="w-7 h-7 flex items-center justify-center text-neutral-400 hover:text-white hover:bg-neutral-800 disabled:opacity-30 text-[9px] font-bold transition-colors"
      >
        F+
      </button>
    </div>
  );
}
