"use client";

import { useEffect, useState } from "react";
import { Card } from "@/components/ui/Primitives";
import { getPalaceStats, type PalaceStats as PalaceStatsData } from "@/lib/palace-client";

export function PalaceStats() {
  const [stats, setStats] = useState<PalaceStatsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void (async () => {
      try {
        const data = await getPalaceStats();
        setStats(data);
      } catch {
        setError("Failed to load palace stats");
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  if (loading) return <div style={{ color: "var(--nl-text-secondary)" }}>Loading stats...</div>;
  if (error) return <div style={{ color: "var(--nl-status-error)" }}>{error}</div>;
  if (!stats) return null;

  const items = [
    { label: "Wings", value: stats.wings },
    { label: "Rooms", value: stats.rooms },
    { label: "Memories", value: stats.memories },
    { label: "KG Triples", value: stats.kgTriples },
  ];

  return (
    <Card padding="md">
      <div className="mb-3 text-[length:var(--nl-text-lg)] font-bold">Memory Palace</div>
      <div className="grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(100px,1fr))]">
        {items.map(({ label, value }) => (
          <div
            key={label}
            className="rounded-[var(--nl-radius-md)] border border-[color:var(--nl-border-subtle)] p-3 text-center"
          >
            <div className="text-2xl font-bold text-[color:var(--nl-accent-primary)]">{value}</div>
            <div className="text-xs text-[color:var(--nl-text-secondary)]">{label}</div>
          </div>
        ))}
      </div>
    </Card>
  );
}
