import React, { useMemo } from "react";
import { Text, ScrollArea } from "@mantine/core";
import { BracketData } from "../types";
import { Bracket } from "./bracket";
import useAppShellHeight from "@/hooks/use-appshell-height";
import { Match } from "@/features/matches/types";

interface BracketViewProps {
  bracket: BracketData;
  showControls?: boolean
}

const BracketView: React.FC<BracketViewProps> = ({ bracket, showControls }) => {
  const height = useAppShellHeight();
  const orders = useMemo(() => {
    const map: Record<number, number> = {};
    bracket.winners.flat().forEach(match => map[match.lid] = match.order);
    bracket.losers.flat().forEach(match => map[match.lid] = match.order);
    return map;
  }, [bracket.winners, bracket.losers]);

  return <ScrollArea
      h={`calc(${height})`}
      className="bracket-container"
      style={{
        backgroundImage: `radial-gradient(circle, var(--mantine-color-default-border) 1px, transparent 1px)`,
        backgroundSize: "16px 16px",
        backgroundPosition: "0 0, 8px 8px",
      }}
    >
      <div>
        <Text fw={600} size="md" m={16}>
          Winners Bracket
        </Text>
        <Bracket rounds={bracket.winners} orders={orders} showControls={showControls} />
      </div>
      {bracket.losers && (
        <div>
          <Text fw={600} size="md" m={16}>
            Losers Bracket
          </Text>
        <Bracket rounds={bracket.losers} orders={orders} showControls={showControls} />
        </div>
      )}
    </ScrollArea>
};

export default BracketView;
