import { Box, LinearProgress, Paper, Typography } from "@mui/material";
import type { LoadProgress } from "../types";

function bytesPretty(n: number): string {
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
  return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

export function LoadingPanel({ progress }: { progress: LoadProgress }) {
  const pct =
    progress.loaded && progress.total
      ? Math.min(100, Math.round((progress.loaded / progress.total) * 100))
      : null;
  return (
    <Paper
      elevation={0}
      sx={{
        p: 4,
        maxWidth: 520,
        mx: "auto",
        mt: { xs: 6, md: 12 },
        textAlign: "center",
      }}
    >
      <Typography variant="overline" color="text.secondary">
        {progress.phase}
      </Typography>
      <Typography variant="h6" sx={{ mt: 0.5 }}>
        {progress.message}
      </Typography>
      <Box sx={{ mt: 3 }}>
        <LinearProgress
          variant={pct === null ? "indeterminate" : "determinate"}
          value={pct ?? 0}
        />
      </Box>
      {progress.loaded !== undefined && (
        <Typography variant="caption" color="text.secondary" sx={{ mt: 1.5, display: "block" }}>
          {bytesPretty(progress.loaded)}
          {progress.total ? ` / ${bytesPretty(progress.total)}` : ""}
        </Typography>
      )}
    </Paper>
  );
}
