"use client";

import { useState } from "react";
import Scoreboard from "./Scoreboard";
import StudySheet from "./StudySheet";
import {
  renderStudySheetMarkdown,
  studySheetFileName
} from "../lib/study-sheet";

export default function Completion({
  xp,
  integrity,
  score,
  runId,
  runQuestionIds,
  mode,
  startedAt,
  outcomes,
  modeLabel,
  questionCount,
  results,
  sheet,
  onReview,
  onReset
}) {
  const totals = results.reduce(
    (summary, result) => ({
      clean: summary.clean + result.clean,
      mistakes: summary.mistakes + result.mistakes,
      hints: summary.hints + result.hints
    }),
    { clean: 0, mistakes: 0, hints: 0 }
  );
  const [showSheet, setShowSheet] = useState(false);

  function downloadSheet() {
    const blob = new Blob([renderStudySheetMarkdown(sheet)], {
      type: "text/markdown;charset=utf-8"
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = studySheetFileName(sheet);
    document.body.append(link);
    link.click();
    link.remove();
    URL.revokeObjectURL(url);
  }

  if (showSheet) {
    return <StudySheet sheet={sheet} onClose={() => setShowSheet(false)} />;
  }

  return (
    <section className="completion" aria-labelledby="completion-title">
      <div className="completion-scan" aria-hidden="true" />
      <div className="completion-fireworks" aria-hidden="true">
        {Array.from({ length: 18 }, (_, index) => (
          <span
            key={index}
            style={{
              "--spark-rotate": `${index * 20}deg`,
              "--spark-delay": `${index * 28}ms`
            }}
          />
        ))}
      </div>
      <div className="completion-badge" aria-hidden="true">
        <span>✓</span>
        <strong>SYSTEM ONLINE</strong>
      </div>
      <p className="project-label">SYSTEMBERICHT // BUILD ERFOLGREICH</p>
      <h1 id="completion-title">
        Dein Linux
        <br />
        <em>läuft.</em>
      </h1>
      <p>
        {modeLabel} abgeschlossen. Du hast das System über Signale, passende
        Werkzeuge und kontrollierte Entscheidungen aufgebaut.
      </p>

      <div className="completion-stats">
        <div>
          <span>Kapitel</span>
          <strong>10 / 10</strong>
        </div>
        <div>
          <span>Fragen</span>
          <strong>{questionCount}</strong>
        </div>
        <div>
          <span>Erfahrung</span>
          <strong>{xp} XP</strong>
        </div>
      </div>

      <div className="completion-recap">
        <strong>MISSION COMPLETE</strong>
        <p>
          Du hast alle zehn Linux-Bereiche aktiviert und {questionCount} echte
          Diagnoseentscheidungen getroffen.
        </p>
        <div>
          <span>{totals.clean} ohne Hilfe gelöst</span>
          <span>{totals.mistakes} Fehler korrigiert</span>
          <span>{totals.hints} Hinweise genutzt</span>
        </div>
      </div>

      <div className="chapter-results" aria-label="Ergebnis nach Kapiteln">
        {results.map((result) => (
          <div key={result.id}>
            <span>{result.number}</span>
            <strong>{result.topic}</strong>
            <small>
              {result.clean}/{result.total} ohne Hilfe · {result.mistakes} Fehler
            </small>
          </div>
        ))}
      </div>

      <Scoreboard
        score={score}
        runId={runId}
        runQuestionIds={runQuestionIds}
        mode={mode}
        startedAt={startedAt}
        outcomes={outcomes}
      />

      <div className="completion-actions">
        <button type="button" onClick={downloadSheet}>
          Spickzettel als .md laden
        </button>
        <button type="button" onClick={() => setShowSheet(true)}>
          Druckansicht öffnen
        </button>
        <button type="button" onClick={onReview}>
          Fragen nachlesen
        </button>
        <a
          href="/kernel-panic/kernel-panic-projektarbeit.pdf"
          target="_blank"
        >
          Projekt-PDF öffnen
        </a>
        <a href="/kernel-panic/kernel-panic-lpic-projekt.zip" download>
          Projekt als ZIP
        </a>
        <button type="button" className="quiet" onClick={onReset}>
          Neues Spiel
        </button>
      </div>

      <p className="completion-footnote">
        Integrität {integrity}% · Kursprojekt von André Stiebitz · LPIC-1
        Version 5.0 (101-500 / 102-500)
      </p>
    </section>
  );
}
