'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { fmt, formatHour } from '@/lib/game/stores';
import { useGameStore } from '@/lib/game/stores';

interface GameOverScreenProps {
  day: number;
  hour: number;
  insightGained: number;
  totalInsight: number;
}

export function GameOverScreen({ day, hour, insightGained, totalInsight }: GameOverScreenProps) {
  const startNewLoop = () => {
    useGameStore.getState().startNewLoop();
  };

  // Defensive: ensure all values are valid numbers (guard against render-time edge cases)
  const safeDay = Number.isFinite(day) ? day : 0;
  const safeHour = Number.isFinite(hour) ? hour : 0;
  const safeInsightGained = Number.isFinite(insightGained) ? insightGained : 0;
  const safeTotalInsight = Number.isFinite(totalInsight) ? totalInsight : 0;

  return (
    <div className="fixed inset-0 game-overlay flex items-center justify-center z-50">
      <Card className="bg-gray-900 border-gray-600 max-w-md w-full mx-4 shadow-2xl">
        <CardHeader>
          <CardTitle className="text-3xl text-center game-title text-amber-400">
            LOOP ENDS
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <p className="text-center text-gray-400">
            The time loop resets... but you remember.
          </p>

          <div className="grid grid-cols-2 gap-3">
            <div className="p-3 bg-gray-800 rounded">
              <div className="text-xl font-bold text-amber-400 game-mono">{fmt(safeInsightGained)}</div>
              <div className="text-xs text-gray-400">Insight Gained</div>
            </div>
            <div className="p-3 bg-gray-800 rounded">
              <div className="text-xl font-bold text-blue-400 game-mono">{safeDay}</div>
              <div className="text-xs text-gray-400">Day Reached</div>
            </div>
            <div className="p-3 bg-gray-800 rounded">
              <div className="text-xl font-bold text-purple-400 game-mono">{formatHour(safeHour)}</div>
              <div className="text-xs text-gray-400">Hour</div>
            </div>
            <div className="p-3 bg-gray-800 rounded">
              <div className="text-xl font-bold text-green-400 game-mono">{fmt(safeTotalInsight)}</div>
              <div className="text-xs text-gray-400">Total Insight</div>
            </div>
          </div>

          <Button
            className="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700"
            size="lg"
            onClick={startNewLoop}
          >
            Begin New Loop
          </Button>
        </CardContent>
      </Card>
    </div>
  );
}
