// Football Field component — realistic field with player chips at formation positions
// Window globals: React, useState, useMemo

const { useState, useMemo } = React;

// ─── Personnel packages (Adjusted for each orientation, depth chart field) ───────────────────────
// Each position: key (unique), label (chip text), dataKey (depthChart key),
// dataIndex (0=starter, 1=backup), x/y (horizontal field coords pre-rotation)

const OFFENSE_PERSONNEL = {
  '11 (3 WR)': [
    { key: 'WR2',     label: 'WR',   dataKey: 'WR2',     dataIndex: 0, x: 39, y: 80 }, // Wide Receiver 2
    { key: 'LT',      label: 'LT',   dataKey: 'LT',      dataIndex: 0, x: 39, y: 36 }, // Left Tackle
    { key: 'LG',      label: 'LG',   dataKey: 'LG',      dataIndex: 0, x: 39, y: 43 }, // Left Guard
    { key: 'C',       label: 'C',    dataKey: 'C',       dataIndex: 0, x: 40, y: 50 }, // Center
    { key: 'RG',      label: 'RG',   dataKey: 'RG',      dataIndex: 0, x: 39, y: 57 }, // Right Guard
    { key: 'RT',      label: 'RT',   dataKey: 'RT',      dataIndex: 0, x: 39, y: 64 }, // Right Tackle
    { key: 'TE',      label: 'TE',   dataKey: 'TE',      dataIndex: 0, x: 35, y: 71 }, // Tight End
    { key: 'WR Slot', label: 'SLOT', dataKey: 'WR Slot', dataIndex: 0, x: 35, y: 25 }, // Slot Wide Receiver
    { key: 'WR1',     label: 'WR',   dataKey: 'WR1',     dataIndex: 0, x: 39, y: 18 }, // Wide Receiver 1
    { key: 'QB',      label: 'QB',   dataKey: 'QB',      dataIndex: 0, x: 25, y: 50 }, // Quarterback
    { key: 'RB',      label: 'HB',   dataKey: 'RB',      dataIndex: 0, x: 20, y: 56 }, // Running Back
  ],
  '12 (2 WR, 2 TE)': [
    { key: 'WR2',  label: 'WR',  dataKey: 'WR2', dataIndex: 0, x: 39, y: 82 }, // Wide Receiver 2
    { key: 'TE2',  label: 'TE',  dataKey: 'TE',  dataIndex: 1, x: 35, y: 35 }, // Tight End 2
    { key: 'LT',   label: 'LT',  dataKey: 'LT',  dataIndex: 0, x: 39, y: 40 }, // Left Tackle
    { key: 'LG',   label: 'LG',  dataKey: 'LG',  dataIndex: 0, x: 39, y: 45 }, // Left Guard
    { key: 'C',    label: 'C',   dataKey: 'C',   dataIndex: 0, x: 40, y: 50 }, // Center
    { key: 'RG',   label: 'RG',  dataKey: 'RG',  dataIndex: 0, x: 39, y: 55 }, // Right Guard
    { key: 'RT',   label: 'RT',  dataKey: 'RT',  dataIndex: 0, x: 39, y: 60 }, // Right Tackle
    { key: 'TE',   label: 'TE',  dataKey: 'TE',  dataIndex: 0, x: 35, y: 68 }, // Tight End
    { key: 'WR1',  label: 'WR',  dataKey: 'WR1', dataIndex: 0, x: 39, y: 18 }, // Wide Receiver 1
    { key: 'QB',   label: 'QB',  dataKey: 'QB',  dataIndex: 0, x: 25, y: 50 }, // Quarterback
    { key: 'RB',   label: 'HB',  dataKey: 'RB',  dataIndex: 0, x: 20, y: 56 }, // Running Back
  ],
  '21 (2 WR, 1 TE, 2 RB)': [
    { key: 'WR2',  label: 'WR',  dataKey: 'WR2', dataIndex: 0, x: 39, y: 80 }, // Wide Receiver 2
    { key: 'LT',   label: 'LT',  dataKey: 'LT',  dataIndex: 0, x: 39, y: 40 }, // Left Tackle
    { key: 'LG',   label: 'LG',  dataKey: 'LG',  dataIndex: 0, x: 39, y: 45 }, // Left Guard
    { key: 'C',    label: 'C',   dataKey: 'C',   dataIndex: 0, x: 40, y: 50 }, // Center
    { key: 'RG',   label: 'RG',  dataKey: 'RG',  dataIndex: 0, x: 39, y: 55 }, // Right Guard
    { key: 'RT',   label: 'RT',  dataKey: 'RT',  dataIndex: 0, x: 39, y: 60 }, // Right Tackle
    { key: 'TE',   label: 'TE',  dataKey: 'TE',  dataIndex: 0, x: 35, y: 68 }, // Tight End
    { key: 'WR1',  label: 'WR',  dataKey: 'WR1', dataIndex: 0, x: 39, y: 18 }, // Wide Receiver 1
    { key: 'QB',   label: 'QB',  dataKey: 'QB',  dataIndex: 0, x: 25, y: 50 }, // Quarterback
    { key: 'FB',   label: 'FB',  dataKey: 'RB',  dataIndex: 1, x: 20, y: 44 }, // Fullback
    { key: 'RB',   label: 'HB',  dataKey: 'RB',  dataIndex: 0, x: 20, y: 58 }, // Running Back
  ],
  '22 (1 WR, 2 TE, 2 RB)': [
    { key: 'TE2',  label: 'TE',  dataKey: 'TE',  dataIndex: 1, x: 35, y: 35 }, // Tight End 2
    { key: 'LT',   label: 'LT',  dataKey: 'LT',  dataIndex: 0, x: 39, y: 40 }, // Left Tackle
    { key: 'LG',   label: 'LG',  dataKey: 'LG',  dataIndex: 0, x: 39, y: 45 }, // Left Guard
    { key: 'C',    label: 'C',   dataKey: 'C',   dataIndex: 0, x: 40, y: 50 }, // Center
    { key: 'RG',   label: 'RG',  dataKey: 'RG',  dataIndex: 0, x: 39, y: 55 }, // Right Guard
    { key: 'RT',   label: 'RT',  dataKey: 'RT',  dataIndex: 0, x: 39, y: 60 }, // Right Tackle
    { key: 'TE',   label: 'TE',  dataKey: 'TE',  dataIndex: 0, x: 35, y: 68 }, // Tight End
    { key: 'WR1',  label: 'WR',  dataKey: 'WR1', dataIndex: 0, x: 39, y: 18 }, // Wide Receiver 1
    { key: 'QB',   label: 'QB',  dataKey: 'QB',  dataIndex: 0, x: 25, y: 50 }, // Quarterback
    { key: 'FB',   label: 'FB',  dataKey: 'RB',  dataIndex: 1, x: 20, y: 44 }, // Fullback
    { key: 'RB',   label: 'HB',  dataKey: 'RB',  dataIndex: 0, x: 20, y: 58 }, // Running Back
  ],
};

const DEFENSE_PERSONNEL = {
    'Base': [
    // 3-4: 3 DL, 4 LBs (2 ILBs, 2 OLBs), 4 DBs
    { key: 'DE1',    label: 'DE',   dataKey: 'DE',    dataIndex: 0, x: 59,   y: 57.5 },  // Defensive End
    { key: 'NT',    label: 'NT',   dataKey: 'NT',    dataIndex: 0, x: 59,   y: 50 },    // Nose Tackle
    { key: 'DT1',    label: 'DT',   dataKey: 'DT',    dataIndex: 0, x: 59,   y: 42.5, allowedSwaps: ['DT', 'DE'] },  // Defensive Tackle
    { key: 'OLB-L', label: 'LOLB', dataKey: 'OLB-L', dataIndex: 0, x: 62.5, y: 35 },    // Left Outside Linebacker
    { key: 'OLB-R', label: 'ROLB', dataKey: 'OLB-R', dataIndex: 0, x: 62.5, y: 65 },    // Right Outside Linebacker
    { key: 'LB1',   label: 'LILB', dataKey: 'LB1',   dataIndex: 0, x: 70,   y: 56 },    // Left Inside Linebacker
    { key: 'LB2',   label: 'RILB', dataKey: 'LB2',   dataIndex: 0, x: 72,   y: 45 },    // Right Inside Linebacker
    { key: 'CB2',   label: 'CB',   dataKey: 'CB2',   dataIndex: 0, x: 65,   y: 86 },    // Cornerback
    { key: 'CB1',   label: 'CB',   dataKey: 'CB1',   dataIndex: 0, x: 65,   y: 18 },    // Cornerback
    { key: 'SS',    label: 'SS',   dataKey: 'SS',    dataIndex: 0, x: 82,   y: 62 },    // Strong Safety
    { key: 'FS',    label: 'FS',   dataKey: 'FS',    dataIndex: 0, x: 85,   y: 36 },    // Free Safety
  ],
  'Nickel': [
    // 3-4 Nickel: drop one ILB (LB2), add slot CB — 5 DBs total
    { key: 'D1T',      label: 'DT',   dataKey: 'DT',      dataIndex: 0, x: 59,   y: 47 }, // Defensive Tackle
    { key: 'DT2',      label: 'DT',   dataKey: 'DT',      dataIndex: 0, x: 59,   y: 53 }, // Defensive Tackle
    { key: 'DE1',      label: 'DE',   dataKey: 'DE',      dataIndex: 0, x: 59,   y: 60 }, // Defensive End
    { key: 'DE2',      label: 'DE',   dataKey: 'DE',      dataIndex: 0, x: 59,   y: 40 }, // Defensive End
    { key: 'LB1',     label: 'LILB', dataKey: 'LB1',     dataIndex: 0, x: 69,  y: 44 }, // Left Inside Linebacker
    { key: 'LB2',     label: 'RILB', dataKey: 'LB2',     dataIndex: 0, x: 69,  y: 56 }, // Right Inside Linebacker
    { key: 'CB Slot', label: 'NCB',  dataKey: 'CB Slot', dataIndex: 0, x: 63.5, y: 30 }, // Nickel (Slot) Cornerback
    { key: 'CB2',     label: 'CB',   dataKey: 'CB2',     dataIndex: 0, x: 63.5, y: 18 }, // Cornerback
    { key: 'CB1',     label: 'CB',   dataKey: 'CB1',     dataIndex: 0, x: 63.5, y: 82 }, // Cornerback
    { key: 'SS',      label: 'SS',   dataKey: 'SS',      dataIndex: 0, x: 82,   y: 62 }, // Strong Safety
    { key: 'FS',      label: 'FS',   dataKey: 'FS',      dataIndex: 0, x: 85,   y: 36 }, // Free Safety
    ],
};

// ─── Shared components ─────────────────────────────────────────────────────

// Stadium-style endzone text: each letter is its own span so flex
// `justify-content: space-between` distributes them evenly across the
// endzone, regardless of word length (BALTIMORE = 9, RAVENS = 6).
function EndzoneText({ word }) {
  return (
    <span className="ez-word">
      {word.split('').map((c, i) => (
        <span key={i} className="ez-letter">{c}</span>
      ))}
    </span>
  );
}

function YardMarkers() {
  const lines = [];
  for (let yd = 10; yd <= 90; yd += 10) {
    lines.push(<div key={yd} className="yard-line" style={{ left: `${yd}%` }} />);
    const num = yd <= 50 ? yd : 100 - yd;
    lines.push(
      <div key={`tn-${yd}`} className="yard-number top" style={{ left: `${yd}%` }}>{num}</div>,
      <div key={`bn-${yd}`} className="yard-number bottom" style={{ left: `${yd}%` }}>{num}</div>
    );
  }
  for (let yd = 1; yd <= 99; yd++) {
    if (yd % 5 === 0) continue;
    lines.push(<div key={`ht-${yd}`} className="hash top" style={{ left: `${yd}%` }} />);
    lines.push(<div key={`hb-${yd}`} className="hash bottom" style={{ left: `${yd}%` }} />);
  }
  return <>{lines}</>;
}

function PlayerPos({ data, pos, depth, side, onClick, onContextMenu }) {
  if (!data) return null;
  
  // Use the player's actual roster position, fallback to the formation's default label
  const displayLabel = data.rosterPosition || pos.label || pos.key;

  return (
    <div
      className={`player-pos ${side}`}
      style={{ left: `${pos.x}%`, top: `${pos.y}%` }}
      onClick={() => onClick && onClick(data, pos.key)}
      onContextMenu={(e) => {
        if (onContextMenu) {
          e.preventDefault();
          onContextMenu(e, pos);
        }
      }}
    >
      <div className="player-disc">
        {data.number != null ? data.number : '—'}
        {depth > 1 && <div className="pos-depth">{depth}</div>}
      </div>
      <div className="pos-label">{displayLabel}</div>
      <div className="pos-name">{data.name.split(' ').slice(-1)[0]}</div>
    </div>
  );
}

// ─── Vertical field (Depth Chart page) ────────────────────────────────────
// Rotation: (x, y) → (y, 100−x) maps horizontal depth (x) to vertical depth (y)
// so offense ends up at the bottom and defense at the top.
function rotateForVertical(positions) {
  return positions.map(p => ({ ...p, x: p.y, y: 100 - p.x }));
}

function YardMarkersVertical() {
  const lines = [];
  for (let yd = 10; yd <= 90; yd += 10) {
    lines.push(<div key={yd} className="yard-line v" style={{ top: `${yd}%` }} />);
    const num = yd <= 50 ? yd : 100 - yd;
    lines.push(
      <div key={`ln-${yd}`} className="yard-number v left" style={{ top: `${yd}%` }}>{num}</div>,
      <div key={`rn-${yd}`} className="yard-number v right" style={{ top: `${yd}%` }}>{num}</div>
    );
  }
  for (let yd = 1; yd <= 99; yd++) {
    if (yd % 5 === 0) continue;
    lines.push(<div key={`hl-${yd}`} className="hash v left" style={{ top: `${yd}%` }} />);
    lines.push(<div key={`hr-${yd}`} className="hash v right" style={{ top: `${yd}%` }} />);
  }
  return <>{lines}</>;
}

function FootballFieldVertical({ depthChart, onPlayerClick, onRightClickPlayer, offPersonnel, defPersonnel }) {
  const oPositions = useMemo(() => rotateForVertical(OFFENSE_PERSONNEL[offPersonnel] || OFFENSE_PERSONNEL['11 (3 WR)']), [offPersonnel, depthChart]);
  const dPositions = useMemo(() => rotateForVertical(DEFENSE_PERSONNEL[defPersonnel] || DEFENSE_PERSONNEL['Base']), [defPersonnel, depthChart]);

  const renderSide = (positions, side, currentPackage) => {
    const group = side === 'offense' ? depthChart.offense : depthChart.defense;
    const usedNames = new Set(); // Track who is on the grass

    // Pass 1: Log all manually overridden players so they aren't cloned
    positions.forEach(p => {
      if (p.overridePlayer) usedNames.add(p.overridePlayer.name);
    });

    return positions.map(p => {
      let player = p.overridePlayer;
      let depthCount = 1;

      if (!player) {
        const players = group[p.dataKey || p.key] || [];
        
        // Filter out anyone already standing on the field
        const availablePlayers = players.filter(pl => !usedNames.has(pl.name));

        // Pull the next available backup, fallback to true default if we run out
        player = availablePlayers[p.dataIndex ?? 0] || availablePlayers[0] || players[0];
        depthCount = players.length;

        if (player) {
          player = { ...player, rosterPosition: window.POSITION_DISPLAY?.[p.dataKey || p.key] || (p.dataKey || p.key) };
          usedNames.add(player.name); // Mark this default player as used so the next chip skips them!
        }
      }

      return (
        <PlayerPos
          key={`${side}-${p.key}`}
          data={player}
          pos={p}
          depth={depthCount}
          side={side}
          onClick={(pl) => onPlayerClick && onPlayerClick({ ...pl, position: p.key, depth: 1, group: side })}
          onContextMenu={(e, pos) => onRightClickPlayer && onRightClickPlayer(e, pos, side, currentPackage)}
        />
      );
    });
  };

  return (
    <div className="field-wrap vertical">
      <div className="field vertical">
        <div className="endzone top"><EndzoneText word="RAVENS" /></div>
        <div className="endzone bottom"><EndzoneText word="BALTIMORE" /></div>
        <div className="field-play vertical">
          <YardMarkersVertical />
          <div className="raven-watermark top" />
          <div className="raven-watermark bottom" />
          <div className="scrimmage" />
          {renderSide(dPositions, 'defense', defPersonnel)}
          {renderSide(oPositions, 'offense', offPersonnel)}
        </div>
      </div>
    </div>
  );
}

// ─── Horizontal field (Dashboard preview) ─────────────────────────────────
function FootballField({ side, depthChart, onPlayerClick, onRightClickPlayer }) {
  const offKeys = Object.keys(OFFENSE_PERSONNEL);
  const defKeys = Object.keys(DEFENSE_PERSONNEL);
  const offensePositions = OFFENSE_PERSONNEL[offKeys[0]] || [];
  const defensePositions = DEFENSE_PERSONNEL[defKeys[0]] || [];
  const positions = side === 'offense' ? offensePositions : defensePositions;
  const currentPackage = side === 'offense' ? offKeys[0] : defKeys[0];
  const group = side === 'offense' ? depthChart.offense : depthChart.defense;

  const usedNames = new Set();
  positions.forEach(p => {
    if (p.overridePlayer) usedNames.add(p.overridePlayer.name);
  });

  return (
    <div className="field-wrap">
      <div className="field">
        <div className="endzone left"><EndzoneText word="BALTIMORE" /></div>
        <div className="endzone right"><EndzoneText word="RAVENS" /></div>
        <div className="field-play">
          <YardMarkers />
          <div className="mid-logo">B</div>
          {positions.map(p => {
            let player = p.overridePlayer;
            let depthCount = 1;

            if (!player) {
              const players = group[p.dataKey || p.key] || [];
              const availablePlayers = players.filter(pl => !usedNames.has(pl.name));
              
              player = availablePlayers[p.dataIndex ?? 0] || availablePlayers[0] || players[0];
              depthCount = players.length;
              
              if (player) {
                player = { ...player, rosterPosition: window.POSITION_DISPLAY?.[p.dataKey || p.key] || (p.dataKey || p.key) };
                usedNames.add(player.name);
              }
            }

            return (
              <PlayerPos
                key={p.key}
                data={player}
                pos={p}
                depth={depthCount}
                side={side}
                onClick={(pl) => onPlayerClick && onPlayerClick({ ...pl, position: p.key, depth: 1, group: side })}
                onContextMenu={(e, pos) => onRightClickPlayer && onRightClickPlayer(e, pos, side, currentPackage)}
              />
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.FootballField = FootballField;
window.FootballFieldVertical = FootballFieldVertical;
window.OFFENSE_PERSONNEL = OFFENSE_PERSONNEL;
window.DEFENSE_PERSONNEL = DEFENSE_PERSONNEL;
