<template>
  <div class="court-drawing-tool">
  <div class="tool-layout">
  <div class="exercise-selection">
    <h5>{{ $t('courtDrawingTool.configureExercise') }}</h5>
    <div class="workflow-grid">
      <section class="workflow-card">
        <button type="button" class="workflow-toggle" @click="toggleStartSection">
          <div>
            <div class="workflow-step">{{ $t('courtDrawingTool.stepStartPosition') }}</div>
            <p class="workflow-copy workflow-copy-compact">{{ $t('courtDrawingTool.stepStartPositionHint') }}</p>
          </div>
          <span class="workflow-toggle-icon">{{ startSectionExpanded ? '−' : '+' }}</span>
        </button>
        <div v-if="startSectionExpanded" class="workflow-section-body">
          <div class="choice-row">
            <button
              v-for="start in startPositionOptions"
              :key="start.value"
              type="button"
              :class="['choice-chip', { 'choice-chip-active': selectedStartPosition === start.value }]"
              @click="selectStartPosition(start.value)"
            >
              <strong>{{ start.short }}</strong>
              <span>{{ start.label }}</span>
            </button>
          </div>
        </div>
      </section>

      <section class="workflow-card">
        <button type="button" class="workflow-toggle" @click="toggleFirstStrokeSection">
          <div>
            <div class="workflow-step">{{ $t('courtDrawingTool.stepFirstStroke') }}</div>
            <p class="workflow-copy workflow-copy-compact">{{ $t('courtDrawingTool.stepFirstStrokeHint') }}</p>
          </div>
          <span class="workflow-toggle-icon">{{ firstStrokeSectionExpanded ? '−' : '+' }}</span>
        </button>
        <div v-if="firstStrokeSectionExpanded" class="workflow-section-body">
          <div class="workflow-block">
            <span class="group-label">{{ $t('courtDrawingTool.service') }}</span>
            <div class="choice-row">
              <button
                type="button"
                :class="['choice-chip', { 'choice-chip-active': strokeType === 'VH' }]"
                @click="strokeType = 'VH'"
              >
                <strong>VH</strong>
                <span>{{ $t('courtDrawingTool.forehand') }}</span>
              </button>
              <button
                type="button"
                :class="['choice-chip', { 'choice-chip-active': strokeType === 'RH' }]"
                @click="strokeType = 'RH'"
              >
                <strong>RH</strong>
                <span>{{ $t('courtDrawingTool.backhand') }}</span>
              </button>
            </div>
          </div>
          <div class="workflow-block">
            <span class="group-label">{{ $t('courtDrawingTool.spin') }}</span>
            <div class="choice-row choice-row-dense">
              <button
                v-for="option in mainSpinOptions"
                :key="option.value"
                type="button"
                :class="['choice-chip', 'choice-chip-compact', { 'choice-chip-active': spinType === option.value }]"
                @click="spinType = option.value"
              >
                <strong>{{ option.short }}</strong>
                <span>{{ option.label }}</span>
              </button>
            </div>
          </div>
        </div>
      </section>

      <section class="workflow-card">
        <button type="button" class="workflow-toggle" @click="toggleTargetSection">
          <div>
            <div class="workflow-step">{{ $t('courtDrawingTool.stepTarget') }}</div>
            <p class="workflow-copy workflow-copy-compact">{{ $t('courtDrawingTool.stepTargetHint') }}</p>
          </div>
          <span class="workflow-toggle-icon">{{ targetSectionExpanded ? '−' : '+' }}</span>
        </button>
        <div v-if="targetSectionExpanded" class="workflow-section-body">
          <div class="workflow-block">
            <span class="group-label">{{ $t('courtDrawingTool.targetPosition') }}</span>
            <div class="target-grid target-grid-large">
              <button
                v-for="n in mainTargetPositions"
                :key="`main-target-${n}`"
                type="button"
                :class="['grid-btn', { 'is-active': targetPosition === String(n) }]"
                @click="selectMainTargetPosition(n)"
                :disabled="!spinType"
              >
                {{ n }}
              </button>
            </div>
          </div>
        </div>
      </section>

      <section class="workflow-card workflow-card-wide" v-if="strokeType && spinType && targetPosition">
        <div class="workflow-step">{{ $t('courtDrawingTool.stepAdditionalStrokes') }}</div>
        <p class="workflow-copy">{{ $t('courtDrawingTool.stepAdditionalStrokesHint') }}</p>

        <div v-if="additionalStrokes.length" class="stroke-sequence-list">
          <div
            v-for="(stroke, index) in additionalStrokes"
            :key="`${stroke.counter}-${index}`"
            class="stroke-sequence-item"
          >
            <div class="stroke-sequence-index">{{ index + 2 }}</div>
            <div class="stroke-sequence-copy">{{ formatAdditionalStroke(stroke) }}</div>
            <button type="button" class="stroke-sequence-remove" @click="removeAdditionalStroke(index)">{{ $t('common.delete') }}</button>
          </div>
        </div>
        <div v-else class="stroke-sequence-empty">{{ $t('courtDrawingTool.noAdditionalStrokes') }}</div>

        <div class="next-stroke-selection">
          <div class="workflow-block">
            <span class="group-label">{{ $t('courtDrawingTool.strokeSide') }}</span>
            <div class="choice-row">
              <button
                type="button"
                :class="['choice-chip', { 'choice-chip-active': nextStrokeSide === 'VH' }]"
                @click="nextStrokeSide = 'VH'"
              >
                <strong>VH</strong>
                <span>{{ $t('courtDrawingTool.forehand') }}</span>
              </button>
              <button
                type="button"
                :class="['choice-chip', { 'choice-chip-active': nextStrokeSide === 'RH' }]"
                @click="nextStrokeSide = 'RH'"
              >
                <strong>RH</strong>
                <span>{{ $t('courtDrawingTool.backhand') }}</span>
              </button>
            </div>
          </div>

          <div class="workflow-block">
            <span class="group-label">{{ $t('courtDrawingTool.strokeTypeLabel') }}</span>
            <div class="choice-row choice-row-dense">
              <button
                v-for="option in additionalStrokeTypeOptions"
                :key="option.value"
                type="button"
                :class="['choice-chip', 'choice-chip-compact', { 'choice-chip-active': nextStrokeType === option.value }]"
                @click="nextStrokeType = option.value"
                :title="option.label"
              >
                <strong>{{ option.short }}</strong>
                <span>{{ option.label }}</span>
              </button>
            </div>
          </div>

          <div class="workflow-block">
            <span class="group-label">{{ $t('courtDrawingTool.targetPositionLabel') }}</span>
            <div class="target-grid target-grid-large">
              <button
                v-for="n in additionalTargetPositions"
                :key="`next-target-${n}`"
                type="button"
                :class="['grid-btn', { 'is-active': nextStrokeTargetPosition === String(n) }]"
                @click="selectAdditionalTargetPosition(n)"
                :disabled="additionalStrokes.length >= 4"
              >
                {{ n }}
              </button>
            </div>
          </div>

          <button
            type="button"
            class="btn-primary add-stroke-button"
            @click="addNextStroke"
            :disabled="additionalStrokes.length >= 4 || !nextStrokeTargetPosition"
          >
            {{ $t('courtDrawingTool.addStroke') }}
          </button>
        </div>
      </section>
    </div>

    <div class="exercise-info" v-if="strokeType && spinType">
      <p><strong>{{ $t('courtDrawingTool.codeLabel') }}:</strong> {{ getFullCode() }}</p>
      <p><strong>{{ $t('courtDrawingTool.titleLabel') }}:</strong> {{ getFullTitle() }}</p>
    </div>
  </div>

  <aside class="preview-panel">
    <div class="preview-panel-header">
      <div class="workflow-step">{{ $t('courtDrawingTool.preview') }}</div>
      <p class="workflow-copy">{{ $t('courtDrawingTool.previewHint') }}</p>
    </div>
    <div v-if="isPrimaryStrokeReady" class="canvas-container">
      <canvas
        ref="drawingCanvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
        :width="config.canvas.width"
        :height="config.canvas.height"
      ></canvas>
    </div>
    <div v-else class="canvas-placeholder">
      <strong>{{ $t('courtDrawingTool.completeFirstStroke') }}</strong>
      <span>{{ $t('courtDrawingTool.completeFirstStrokeHint') }}</span>
    </div>
  </aside>
  </div>
          
      <!-- Buttons entfernt: automatische Speicherung aktiv -->
  </div>
</template>

<script>
const COURT_TOOL_PALETTE = {
  table: '#315f43',
  frame: '#ffffff',
  frameBorder: '#102418',
  line: '#ffffff',
  startSelected: '#c84c32',
  startMuted: '#8d948f',
  targetSelected: '#6f8f3b',
  targetBorder: '#102418',
  targetText: '#102418',
  arrowPrimary: '#c84c32',
  arrowSupport: '#1f6a8a',
  arrowAccent: '#8a5a1f',
  arrowHighlight: '#c7a42a',
  arrowAlternate: '#7a4ea3',
  canvasSurface: '#eef3ef',
  accentText: '#f1d26b'
};

export default {
  name: 'CourtDrawingTool',
  props: {
    value: {
      type: String,
      default: ''
    },
    activityId: {
      type: [String, Number],
      default: null
    },
    drawingData: { // Added for loading saved drawing data
      type: Object,
      default: null
    },
    allowImageUpload: { // Neu: steuert, ob das Tool ein Bild erzeugt/hochlädt
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // Canvas-Konfiguration
      config: {
        canvas: {
          width: 600,
          height: 400
        },
        table: {
          width: 500,
          height: 300,
          color: COURT_TOOL_PALETTE.table,
          borderWidth: 2,
          borderColor: COURT_TOOL_PALETTE.frameBorder,
          outerFrameWidth: 5,
          outerFrameColor: COURT_TOOL_PALETTE.frame,
          outerFrameBorderWidth: 0.5,
          outerFrameBorderColor: COURT_TOOL_PALETTE.frameBorder
        },
        net: {
          width: 4,
          color: COURT_TOOL_PALETTE.frame,
          borderWidth: 1,
          borderColor: COURT_TOOL_PALETTE.frameBorder,
          overhang: 15
        },
        horizontalLine: {
          width: 1,
          color: COURT_TOOL_PALETTE.line,
          gap: 10,
          edgeMargin: 10
        },
        serviceLine: {
          width: 1,
          color: COURT_TOOL_PALETTE.line
        },
        startCircles: {
          radius: 12,
          x: 10,
          topYOffset: 30,
          bottomYOffset: 30,
          selectedColor: COURT_TOOL_PALETTE.startSelected,
          unselectedColor: COURT_TOOL_PALETTE.startMuted,
          selectedBorderColor: COURT_TOOL_PALETTE.frame,
          unselectedBorderColor: COURT_TOOL_PALETTE.frameBorder,
          selectedBorderWidth: 2,
          unselectedBorderWidth: 1
        },
        targetCircles: {
          radius: 10,
          rightXOffset: 20,
          middleXOffset: 40,
          topYOffset: 40,
          bottomYOffset: 40,
          selectedColor: COURT_TOOL_PALETTE.targetSelected,
          unselectedColor: COURT_TOOL_PALETTE.frame,
          selectedBorderColor: COURT_TOOL_PALETTE.frame,
          unselectedBorderColor: COURT_TOOL_PALETTE.targetBorder,
          selectedBorderWidth: 2,
          unselectedBorderWidth: 1,
          font: '12px Arial',
          textColor: COURT_TOOL_PALETTE.targetText,
          transparency: 0.3
        },
        leftTargetCircles: {
          radius: 10,
          leftXOffset: 20,
          rightXOffset: 40,
          topYOffset: 40,
          bottomYOffset: 40,
          selectedColor: COURT_TOOL_PALETTE.targetSelected,
          unselectedColor: COURT_TOOL_PALETTE.frame,
          selectedBorderColor: COURT_TOOL_PALETTE.targetSelected,
          unselectedBorderColor: COURT_TOOL_PALETTE.targetBorder,
          selectedBorderWidth: 2,
          unselectedBorderWidth: 1,
          font: '12px Arial',
          textColor: COURT_TOOL_PALETTE.targetText
        },
        arrow: {
          color: COURT_TOOL_PALETTE.arrowPrimary,
          width: 6,
          cap: 'round',
          headSize: 8,
          vhOffsetX: 5,
          vhOffsetY: 8,
          rhOffsetX: 10,
          rhOffsetY: 0,
          counterFont: 'bold 14px Arial',
          counterOffset: 15
        },
        pen: {
          color: COURT_TOOL_PALETTE.arrowPrimary,
          width: 3,
          cap: 'round',
          join: 'round'
        }
      },
      // Canvas-Instanzen
      canvas: null,
      ctx: null,
      // Zeichen-Status
      isDrawing: false,
      startX: 0,
      startY: 0,
      lastX: 0,
      lastY: 0,
      // Übungs-Konfiguration
      selectedStartPosition: null,
      selectedCirclePosition: null,
      strokeType: 'VH',
      spinType: '',
      targetPosition: '',
      exerciseCounter: 1,
      additionalStrokes: [],
      nextStrokeType: 'US',
      nextStrokeSide: 'VH',
      nextStrokeTargetPosition: '',
      startSectionExpanded: true,
      firstStrokeSectionExpanded: true,
      targetSectionExpanded: true
    }
  },
  computed: {
    isPrimaryStrokeReady() {
      return Boolean(this.selectedStartPosition && this.strokeType && this.spinType && this.targetPosition);
    },
    startPositionOptions() {
      return [
        { value: 'AS1', short: 'AS1', label: this.$t('courtDrawingTool.startLeft') },
        { value: 'AS2', short: 'AS2', label: this.$t('courtDrawingTool.startMiddle') },
        { value: 'AS3', short: 'AS3', label: this.$t('courtDrawingTool.startRight') }
      ];
    },
    mainSpinOptions() {
      return [
        { value: 'Unterschnitt', short: 'US', label: this.$t('courtDrawingTool.underspin') },
        { value: 'Überschnitt', short: 'OS', label: this.$t('courtDrawingTool.topspin') },
        { value: 'Seitschnitt', short: 'SR', label: this.$t('courtDrawingTool.sidespin') },
        { value: 'Seitunterschnitt', short: 'SU', label: this.$t('courtDrawingTool.sideUnderspin') },
        { value: 'Gegenläufer', short: 'GL', label: this.$t('courtDrawingTool.counterSpin') }
      ];
    },
    additionalStrokeTypeOptions() {
      return [
        { value: 'US', short: 'US', label: this.$t('courtDrawingTool.strokeTypePush') },
        { value: 'OS', short: 'OS', label: this.$t('courtDrawingTool.strokeTypeCounter') },
        { value: 'TS', short: 'TS', label: this.$t('courtDrawingTool.strokeTypeTopspin') },
        { value: 'F', short: 'F', label: this.$t('courtDrawingTool.strokeTypeFlip') },
        { value: 'B', short: 'B', label: this.$t('courtDrawingTool.strokeTypeBlock') },
        { value: 'SCH', short: 'SCH', label: this.$t('courtDrawingTool.strokeTypeSmash') },
        { value: 'SAB', short: 'SAB', label: this.$t('courtDrawingTool.strokeTypeChopDefense') },
        { value: 'BAB', short: 'BAB', label: this.$t('courtDrawingTool.strokeTypeLobDefense') }
      ];
    },
    // Reihenfolge der Positionen für Hauptschlag basierend auf Richtung
    mainTargetPositions() {
      const isLeftToRight = this.isMainStrokeLeftToRight();
      // Links nach rechts: 7 4 1 / 8 5 2 / 9 6 3
      // Rechts nach links: 3 6 9 / 2 5 8 / 1 4 7
      if (isLeftToRight) {
        return [7, 4, 1, 8, 5, 2, 9, 6, 3];
      } else {
        return [3, 6, 9, 2, 5, 8, 1, 4, 7];
      }
    },
    // Reihenfolge der Positionen für zusätzliche Schläge basierend auf Richtung
    additionalTargetPositions() {
      const isLeftToRight = this.isAdditionalStrokeLeftToRight();
      if (isLeftToRight) {
        return [7, 4, 1, 8, 5, 2, 9, 6, 3];
      } else {
        return [3, 6, 9, 2, 5, 8, 1, 4, 7];
      }
    }
  },
  watch: {
    strokeType() {
      this.emitDrawingData();
      this.updateTextFields();
    },
    spinType() {
      this.drawCourt(); // Neu zeichnen wenn sich Schnittoption ändert
      this.emitDrawingData();
      this.updateTextFields();
    },
    targetPosition() {
      this.emitDrawingData();
      this.updateTextFields();
    },
    isPrimaryStrokeReady(newVal) {
      if (newVal) {
        this.startSectionExpanded = false;
        this.firstStrokeSectionExpanded = false;
        this.targetSectionExpanded = false;
        this.$nextTick(() => {
          this.initCanvas();
          this.drawCourt(true);
        });
      }
    },
    selectedCirclePosition() {
      // bei Wechsel der Kreisposition: Daten + Strings aktualisieren
      this.emitDrawingData();
      this.updateTextFields();
      if (this.canvas && this.ctx) {
        this.drawCourt();
      }
    },
    selectedStartPosition() {
      // Neu zeichnen wenn sich die Auswahl ändert
      if (this.canvas && this.ctx) {
        this.drawCourt();
      }
      this.emitDrawingData();
      this.updateTextFields();
    },
    drawingData: {
      handler(newVal, oldVal) {
        if (this.drawingData) {
          this.loadDrawingFromMetadata();
        } else if (oldVal && !newVal) {
          // drawingData wurde auf null gesetzt - reset alle Werte und zeichne leeres Canvas
          this.resetAllValues();
          this.clearCanvas();
          this.drawCourt(true); // forceRedraw = true
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initCanvas();
      this.drawCourt();
      if (this.value) {
        this.loadDrawingFromData(this.value);
      }
    });
  },
  methods: {
    toggleStartSection() {
      this.startSectionExpanded = !this.startSectionExpanded;
    },
    toggleFirstStrokeSection() {
      this.firstStrokeSectionExpanded = !this.firstStrokeSectionExpanded;
    },
    toggleTargetSection() {
      this.targetSectionExpanded = !this.targetSectionExpanded;
    },
    selectStartPosition(position) {
      this.selectedStartPosition = position;
      this.selectedCirclePosition = position === 'AS1' ? 'top' : position === 'AS3' ? 'bottom' : 'middle';
      this.drawCourt();
      this.emitDrawingData();
      this.updateTextFields();
    },
    selectMainTargetPosition(position) {
      this.targetPosition = String(position);
      if (this.isPrimaryStrokeReady) {
        this.$nextTick(() => {
          this.initCanvas();
          this.drawCourt(true);
        });
      }
      this.emitDrawingData();
      this.updateTextFields();
    },
    selectAdditionalTargetPosition(position) {
      this.nextStrokeTargetPosition = String(position);
      this.emitDrawingData();
    },
    formatStrokeSide(side) {
      return side === 'VH' ? this.$t('courtDrawingTool.forehand') : this.$t('courtDrawingTool.backhand');
    },
    formatAdditionalStrokeType(type) {
      const option = this.additionalStrokeTypeOptions.find(entry => entry.value === type);
      return option ? option.label : type;
    },
    formatTargetPosition(position) {
      const labels = {
        '1': this.$t('courtDrawingTool.targetForehandLong'),
        '2': this.$t('courtDrawingTool.targetMiddleLong'),
        '3': this.$t('courtDrawingTool.targetBackhandLong'),
        '4': this.$t('courtDrawingTool.targetForehandHalfLong'),
        '5': this.$t('courtDrawingTool.targetMiddleHalfLong'),
        '6': this.$t('courtDrawingTool.targetBackhandHalfLong'),
        '7': this.$t('courtDrawingTool.targetForehandShort'),
        '8': this.$t('courtDrawingTool.targetMiddleShort'),
        '9': this.$t('courtDrawingTool.targetBackhandShort')
      };
      return labels[String(position)] || String(position);
    },
    formatAdditionalStroke(stroke) {
      return `${this.formatStrokeSide(stroke.side)} ${this.formatAdditionalStrokeType(stroke.type)} ${this.$t('courtDrawingTool.toTarget')} ${this.formatTargetPosition(stroke.targetPosition)}`;
    },
    removeAdditionalStroke(index) {
      this.additionalStrokes.splice(index, 1);
      this.nextStrokeTargetPosition = '';
      this.updateTextFields();
      this.drawCourt();
      this.emitDrawingData();
    },
    initCanvas() {
      this.canvas = this.$refs.drawingCanvas;
      if (this.canvas) {
        this.ctx = this.canvas.getContext('2d');
        this.ctx.lineCap = this.config.pen.cap;
        this.ctx.lineJoin = this.config.pen.join;
      }
    },
    
    drawCourt(forceRedraw = false) {
      const ctx = this.ctx;
      const canvas = this.canvas;
      const config = this.config;
      
      if (!ctx || !canvas) {
        return;
      }
      
      
      // Hintergrund immer zeichnen wenn forceRedraw=true, sonst nur wenn Canvas leer ist
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const isEmpty = imageData.data.every(pixel => pixel === 0);
      
      if (forceRedraw || isEmpty) {
        // Hintergrund
        ctx.fillStyle = COURT_TOOL_PALETTE.canvasSurface;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      } else {
      }
      
      // Tischtennis-Tisch
      const tableWidth = config.table.width;
      const tableHeight = config.table.height;
      const tableX = (canvas.width - tableWidth) / 2;
      const tableY = (canvas.height - tableHeight) / 2;
      
      
      // Tischtennis-Tisch Hintergrund
      ctx.fillStyle = config.table.color;
      ctx.fillRect(tableX, tableY, tableWidth, tableHeight);
      
      // Tischtennis-Tisch Rand
      ctx.strokeStyle = config.table.borderColor;
      ctx.lineWidth = config.table.borderWidth;
      ctx.strokeRect(tableX, tableY, tableWidth, tableHeight);
      
      // Äußerer Rahmen (weiß für Tischbeine)
      ctx.strokeStyle = config.table.outerFrameColor;
      ctx.lineWidth = config.table.outerFrameWidth;
      ctx.strokeRect(tableX - config.table.outerFrameWidth, tableY - config.table.outerFrameWidth, tableWidth + config.table.outerFrameWidth * 2, tableHeight + config.table.outerFrameWidth * 2);
      
      // Schwarzer Rahmen um den äußeren Rahmen
      ctx.strokeStyle = config.table.outerFrameBorderColor;
      ctx.lineWidth = config.table.outerFrameBorderWidth;
      ctx.strokeRect(tableX - config.table.outerFrameWidth - config.table.outerFrameBorderWidth, tableY - config.table.outerFrameWidth - config.table.outerFrameBorderWidth, tableWidth + (config.table.outerFrameWidth + config.table.outerFrameBorderWidth) * 2, tableHeight + (config.table.outerFrameWidth + config.table.outerFrameBorderWidth) * 2);
      
      // Mittellinie (dünnere weiße horizontale Linie in der Mitte, geteilt)
      ctx.strokeStyle = config.horizontalLine.color;
      ctx.lineWidth = config.horizontalLine.width;
      const centerX = tableX + tableWidth / 2;
      const centerY = tableY + tableHeight / 2;
      const gap = config.horizontalLine.gap;
      const edgeMargin = config.horizontalLine.edgeMargin;
      
      // Linke Hälfte der horizontalen Linie
      ctx.beginPath();
      ctx.moveTo(tableX + edgeMargin, centerY);
      ctx.lineTo(centerX - gap, centerY);
      ctx.stroke();
      
      // Rechte Hälfte der horizontalen Linie
      ctx.beginPath();
      ctx.moveTo(centerX + gap, centerY);
      ctx.lineTo(tableX + tableWidth - edgeMargin, centerY);
      ctx.stroke();
      
      // Netz (dicke weiße vertikale Linie in der Mitte mit Überstand)
      ctx.strokeStyle = config.net.color;
      ctx.lineWidth = config.net.width;
      const verticalOverhang = config.net.overhang;
      ctx.beginPath();
      ctx.moveTo(tableX + tableWidth / 2, tableY - verticalOverhang);
      ctx.lineTo(tableX + tableWidth / 2, tableY + tableHeight + verticalOverhang);
      ctx.stroke();
      
      // Schwarzer Rahmen um das Netz (vertikale Linie)
      ctx.strokeStyle = config.net.borderColor;
      ctx.lineWidth = config.net.borderWidth;
      ctx.beginPath();
      ctx.moveTo(tableX + tableWidth / 2, tableY - verticalOverhang);
      ctx.lineTo(tableX + tableWidth / 2, tableY + tableHeight + verticalOverhang);
      ctx.stroke();
      
      // Service-Bereiche (nur vertikale Linien, keine horizontalen)
      const serviceWidth = tableWidth / 2;
      
      // Service-Bereiche zeichnen (nur vertikale Trennlinien)
      ctx.strokeStyle = config.serviceLine.color;
      ctx.lineWidth = config.serviceLine.width;
      
      // Vertikale Trennlinie zwischen linken und rechten Bereichen
      ctx.beginPath();
      ctx.moveTo(tableX + serviceWidth, tableY);
      ctx.lineTo(tableX + serviceWidth, tableY + tableHeight);
      ctx.stroke();
      
      // Startpositionen (drei Kreise am linken Bildrand)
      const circleRadius = config.startCircles.radius;
      const circleX = config.startCircles.x;
      const topCircleY = tableY + config.startCircles.topYOffset;
      const middleCircleY = tableY + tableHeight / 2;
      const bottomCircleY = tableY + tableHeight - config.startCircles.bottomYOffset;
      
      const circles = [
        { x: circleX, y: topCircleY, position: 'top' },
        { x: circleX, y: middleCircleY, position: 'middle' },
        { x: circleX, y: bottomCircleY, position: 'bottom' }
      ];
      
      circles.forEach(circle => {
        const isSelected = this.selectedCirclePosition === circle.position;
        const hasSelection = this.selectedCirclePosition !== null;
        
        // Transparenz setzen für nicht-ausgewählte Kreise
        if (hasSelection && !isSelected) {
          ctx.globalAlpha = 0.3; // Teiltransparent für nicht-ausgewählte
        } else {
          ctx.globalAlpha = 1.0; // Vollständig sichtbar für ausgewählten
        }
        
        // Kreis füllen
        ctx.fillStyle = isSelected ? config.startCircles.selectedColor : config.startCircles.unselectedColor;
        ctx.beginPath();
        ctx.arc(circle.x, circle.y, circleRadius, 0, 2 * Math.PI);
        ctx.fill();
        
        // Kreis rand
        ctx.strokeStyle = isSelected ? config.startCircles.selectedBorderColor : config.startCircles.unselectedBorderColor;
        ctx.lineWidth = isSelected ? config.startCircles.selectedBorderWidth : config.startCircles.unselectedBorderWidth;
        ctx.stroke();
        
        // Transparenz zurücksetzen
        ctx.globalAlpha = 1.0;
      });
      
      // Zielpositionen (9 Kreise mit Zahlen) - nur anzeigen wenn Schnittoption gewählt
      if (this.spinType) {
        this.drawTargetPositions(ctx, tableX, tableY, tableWidth, tableHeight);
      }
    },
    
    drawTargetPositions(ctx, tableX, tableY, tableWidth, tableHeight) {
      const config = this.config.targetCircles;
      const targetRadius = config.radius;
      const numberFont = config.font;
      
      const x1 = tableX + tableWidth - config.rightXOffset;
      const x3 = tableX + tableWidth/2 + config.middleXOffset;
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff/2;
      // Positionen der 9 Kreise
      const positions = [
        // Rechts (1, 2, 3) - am rechten Tischrand: L (Lang)
        { x: x1, y: tableY + config.topYOffset, number: 1, label: 'VHL' }, // Vorhand Lang
        { x: x1, y: tableY + tableHeight/2, number: 2, label: 'ML' }, // Mitte Lang
        { x: x1, y: tableY + tableHeight - config.bottomYOffset, number: 3, label: 'RHL' }, // Rückhand Lang
        // Mitte (4, 5, 6) - zwischen 1-3 und 7-9: H (Halblang)
        { x: x2, y: tableY + config.topYOffset, number: 4, label: 'VHH' }, // Vorhand Halblang
        { x: x2, y: tableY + tableHeight/2, number: 5, label: 'MH' }, // Mitte Halblang
        { x: x2, y: tableY + tableHeight - config.bottomYOffset, number: 6, label: 'RHH' }, // Rückhand Halblang
        // Zwischen Netz und Mitte (7, 8, 9) - näher am Netz: K (Kurz)
        { x: x3, y: tableY + config.topYOffset, number: 7, label: 'VHK' }, // Vorhand Kurz
        { x: x3, y: tableY + tableHeight/2, number: 8, label: 'MK' }, // Mitte Kurz
        { x: x3, y: tableY + tableHeight - config.bottomYOffset, number: 9, label: 'RHK' } // Rückhand Kurz
      ];
      
      positions.forEach(pos => {
        const isSelected = this.targetPosition === pos.number.toString();
        const isTargetSelected = this.targetPosition !== '' && this.targetPosition !== null;
        
        // Transparenz für nicht-ausgewählte Kreise wenn ein Target ausgewählt ist
        if (isTargetSelected && !isSelected) {
          ctx.globalAlpha = config.transparency;
        } else {
          ctx.globalAlpha = 1.0;
        }
        
        // Kreis zeichnen
        ctx.fillStyle = isSelected ? config.selectedColor : config.unselectedColor;
        ctx.beginPath();
        ctx.arc(pos.x, pos.y, targetRadius, 0, 2 * Math.PI);
        ctx.fill();
        
        // Kreis rand
        ctx.strokeStyle = isSelected ? config.selectedBorderColor : config.unselectedBorderColor;
        ctx.lineWidth = isSelected ? config.selectedBorderWidth : config.unselectedBorderWidth;
        ctx.stroke();
        
        // Zahl zeichnen (im Kreis)
        ctx.fillStyle = config.textColor;
        ctx.font = numberFont;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(pos.number.toString(), pos.x, pos.y);
        
        // Alpha zurücksetzen
        ctx.globalAlpha = 1.0;
      });
      
      // Roten Pfeil vom Startposition-Kreis zur ausgewählten Zielposition zeichnen
      if (this.targetPosition && this.selectedCirclePosition) {
        this.drawArrowToTarget(ctx, tableX, tableY, tableWidth, tableHeight);
      }
      
      // Kreise für zusätzliche Schläge auf der linken Seite anzeigen
      // Sollen bereits erscheinen, sobald rechts alles gewählt ist (Aufschlag-Seite):
      // also wenn strokeType, spinType und targetPosition gesetzt sind.
      // Zusätzlich weiterhin, wenn bereits nextStrokeType/Side gewählt wurden.
      if ((this.strokeType && this.spinType && this.targetPosition) ||
          (this.nextStrokeType && this.nextStrokeSide && this.targetPosition)) {
        this.drawLeftSideTargetCircles(ctx, tableX, tableY, tableWidth, tableHeight);
      }
      
      // Zeichne Kette zusätzlicher Schläge (bis zu 3)
      if (this.targetPosition) {
        this.drawAdditionalArrows(ctx, tableX, tableY, tableWidth, tableHeight);
      }
    },
    
    drawArrowToTarget(ctx, tableX, tableY, tableWidth, tableHeight) {
      const config = this.config;
      // Startposition-Kreis Koordinaten ermitteln
      const circleRadius = config.startCircles.radius;
      const circleX = config.startCircles.x;
      let startY;
      // Bestimme Startkreis primär aus selectedStartPosition (AS1/AS2/AS3),
      // fallback auf selectedCirclePosition
      const circlePos = this.resolveStartCirclePosition();
      if (circlePos === 'top') {
        startY = tableY + config.startCircles.topYOffset;
      } else if (circlePos === 'middle') {
        startY = tableY + tableHeight / 2;
      } else if (circlePos === 'bottom') {
        startY = tableY + tableHeight - config.startCircles.bottomYOffset;
      } else {
        return;
      }
      
      // Zielposition-Kreis Koordinaten ermitteln
      const targetRadius = config.targetCircles.radius;
      const x1 = tableX + tableWidth - config.targetCircles.rightXOffset;
      const x3 = tableX + tableWidth/2 + config.targetCircles.middleXOffset;
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff/2;
      
      let targetX, targetY;
      const targetNum = parseInt(this.targetPosition);
      
      // X-Koordinate basierend auf Target-Nummer
      if (targetNum >= 1 && targetNum <= 3) {
        targetX = x1;
      } else if (targetNum >= 4 && targetNum <= 6) {
        targetX = x2;
      } else if (targetNum >= 7 && targetNum <= 9) {
        targetX = x3;
      } else {
        return;
      }
      
      // Y-Koordinate basierend auf Target-Nummer
      if (targetNum === 1 || targetNum === 4 || targetNum === 7) {
        targetY = tableY + config.targetCircles.topYOffset;
      } else if (targetNum === 2 || targetNum === 5 || targetNum === 8) {
        targetY = tableY + tableHeight/2;
      } else if (targetNum === 3 || targetNum === 6 || targetNum === 9) {
        targetY = tableY + tableHeight - config.targetCircles.bottomYOffset;
      } else {
        return;
      }
      
      // Pfeil zeichnen
      ctx.strokeStyle = config.arrow.color;
      ctx.fillStyle = config.arrow.color;
      ctx.lineWidth = config.arrow.width;
      ctx.lineCap = config.arrow.cap;
      
      // Linie vom Start- zum Zielkreis (Position abhängig von Schlagart)
      let startX, startYOffset;
      if (this.strokeType === 'VH') {
        // Vorhand: unterhalb seitlich des Punktes
        startX = circleX + circleRadius + config.arrow.vhOffsetX;
        startYOffset = circleRadius + config.arrow.vhOffsetY;
      } else {
        // Rückhand: rechts vom Punkt
        startX = circleX + circleRadius + config.arrow.rhOffsetX;
        startYOffset = config.arrow.rhOffsetY;
      }
      
      const actualStartY = startY + startYOffset;
      
      // Übungsnummer über der Linie zeichnen
      ctx.fillStyle = config.arrow.color;
      ctx.font = config.arrow.counterFont;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      // Position für die Nummer (Mitte der Linie, etwas höher)
      const midX = (startX + targetX - targetRadius) / 2;
      const midY = (actualStartY + targetY) / 2 - config.arrow.counterOffset;
      
      ctx.fillText("1", midX, midY);
      
      // Linie zeichnen
      ctx.beginPath();
      ctx.moveTo(startX, actualStartY);
      ctx.lineTo(targetX - targetRadius, targetY);
      ctx.stroke();
      
      // Pfeilspitze zeichnen
      const arrowSize = config.arrow.headSize;
      const angle = Math.atan2(targetY - actualStartY, targetX - startX);
      
      ctx.beginPath();
      ctx.moveTo(targetX - targetRadius, targetY);
      ctx.lineTo(
        targetX - targetRadius - arrowSize * Math.cos(angle - Math.PI / 6),
        targetY - arrowSize * Math.sin(angle - Math.PI / 6)
      );
      ctx.moveTo(targetX - targetRadius, targetY);
      ctx.lineTo(
        targetX - targetRadius - arrowSize * Math.cos(angle + Math.PI / 6),
        targetY - arrowSize * Math.sin(angle + Math.PI / 6)
      );
      ctx.stroke();
    },

    // Leitet die visuelle Kreis-Position aus selectedStartPosition ab
    resolveStartCirclePosition() {
      if (this.selectedStartPosition === 'AS1') return 'top';
      if (this.selectedStartPosition === 'AS2') return 'middle';
      if (this.selectedStartPosition === 'AS3') return 'bottom';
      // Fallback: benutze bestehenden Kreisstatus
      return this.selectedCirclePosition;
    },
    
    drawArrowToLeftTarget(ctx, tableX, tableY, tableWidth, tableHeight) {
      const config = this.config;
      
      // Rechter Source-Kreis Koordinaten (vom ersten Pfeil)
      const sourceRadius = config.targetCircles.radius;
      const x1 = tableX + tableWidth - config.targetCircles.rightXOffset;
      const x3 = tableX + tableWidth/2 + config.targetCircles.middleXOffset;
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff/2;
      
      let sourceX, sourceY;
      const sourceNum = parseInt(this.targetPosition);
      
      // X-Koordinate basierend auf Source-Nummer
      if (sourceNum >= 1 && sourceNum <= 3) {
        sourceX = x1;
      } else if (sourceNum >= 4 && sourceNum <= 6) {
        sourceX = x2;
      } else if (sourceNum >= 7 && sourceNum <= 9) {
        sourceX = x3;
      } else {
        return;
      }
      
      // Y-Koordinate basierend auf Source-Nummer
      if (sourceNum === 1 || sourceNum === 4 || sourceNum === 7) {
        sourceY = tableY + config.targetCircles.topYOffset;
      } else if (sourceNum === 2 || sourceNum === 5 || sourceNum === 8) {
        sourceY = tableY + tableHeight/2;
      } else if (sourceNum === 3 || sourceNum === 6 || sourceNum === 9) {
        sourceY = tableY + tableHeight - config.targetCircles.bottomYOffset;
      } else {
        return;
      }
      
      // Linker Target-Kreis Koordinaten
      const targetRadius = config.leftTargetCircles.radius;
      const leftX1 = tableX + config.leftTargetCircles.leftXOffset;
      const leftX3 = tableX + tableWidth / 2 - config.leftTargetCircles.rightXOffset;
      const leftXdiff = leftX3 - leftX1;
      const leftX2 = leftX3 - leftXdiff / 2;
      
      let targetX, targetY;
      const targetNum = parseInt(this.nextStrokeTargetPosition);
      
      // X-Koordinate basierend auf Target-Nummer (gespiegelt)
      if (targetNum >= 1 && targetNum <= 3) {
        targetX = leftX1;
      } else if (targetNum >= 4 && targetNum <= 6) {
        targetX = leftX2;
      } else if (targetNum >= 7 && targetNum <= 9) {
        targetX = leftX3;
      } else {
        return;
      }
      
      // Y-Koordinate basierend auf Target-Nummer (gespiegelt)
      // Auf der linken Seite: 1=unten, 2=mitte, 3=oben (gespiegelt zu rechts)
      if (targetNum === 1 || targetNum === 4 || targetNum === 7) {
        targetY = tableY + tableHeight - config.leftTargetCircles.bottomYOffset; // Unten
      } else if (targetNum === 2 || targetNum === 5 || targetNum === 8) {
        targetY = tableY + tableHeight/2; // Mitte
      } else if (targetNum === 3 || targetNum === 6 || targetNum === 9) {
        targetY = tableY + config.leftTargetCircles.topYOffset; // Oben
      } else {
        return;
      }
      
      // Pfeil zeichnen (von rechts nach links = blau)
      ctx.strokeStyle = COURT_TOOL_PALETTE.arrowSupport;
      ctx.fillStyle = COURT_TOOL_PALETTE.arrowSupport;
      ctx.lineWidth = config.arrow.width;
      ctx.lineCap = config.arrow.cap;
      
      // Startposition vom rechten Kreis (links vom Kreis)
      const startX = sourceX - sourceRadius;
      const startY = sourceY;
      
      // Zielposition zum linken Kreis (rechts vom Kreis)
      const endX = targetX + targetRadius;
      const endY = targetY;
      
      // Übungsnummer über der Linie zeichnen
      ctx.fillStyle = COURT_TOOL_PALETTE.arrowSupport;
      ctx.font = config.arrow.counterFont;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      // Position für die Nummer (Mitte der Linie, etwas höher)
      const midX = (startX + endX) / 2;
      const midY = (startY + endY) / 2 - config.arrow.counterOffset;
      
      ctx.fillText("2", midX, midY);
      
      // Linie zeichnen
      ctx.beginPath();
      ctx.moveTo(startX, startY);
      ctx.lineTo(endX, endY);
      ctx.stroke();
      
      // Pfeilspitze zeichnen
      const arrowSize = config.arrow.headSize;
      const angle = Math.atan2(endY - startY, endX - startX);
      
      ctx.beginPath();
      ctx.moveTo(endX, endY);
      ctx.lineTo(
        endX - arrowSize * Math.cos(angle - Math.PI / 6),
        endY - arrowSize * Math.sin(angle - Math.PI / 6)
      );
      ctx.moveTo(endX, endY);
      ctx.lineTo(
        endX - arrowSize * Math.cos(angle + Math.PI / 6),
        endY - arrowSize * Math.sin(angle + Math.PI / 6)
      );
      ctx.stroke();
    },
    
    // Ermittelt, welche Tischseite (left/right) als nächstes für Zusatzschlag benutzt wird
    getNextAdditionalSide() {
      const idx = this.additionalStrokes.length; // 0,1,2
      return idx % 2 === 0 ? 'left' : 'right';
    },
    
    // Bestimmt ob der Hauptschlag von links nach rechts geht
    isMainStrokeLeftToRight() {
      // Bei Aufschlag immer links nach rechts
      if (this.selectedStartPosition && this.selectedStartPosition.startsWith('AS')) {
        return true;
      }
      // Wenn von links kommt, dann links nach rechts
      if (this.selectedCirclePosition === 'left') {
        return true;
      }
      // Wenn von rechts kommt, dann rechts nach links
      if (this.selectedCirclePosition === 'right') {
        return false;
      }
      // Standard: links nach rechts
      return true;
    },
    
    // Bestimmt ob der nächste zusätzliche Schlag von links nach rechts geht
    isAdditionalStrokeLeftToRight() {
      // Wenn der Hauptschlag ein Aufschlag ist, endet er rechts
      // Dann kommt der erste zusätzliche Schlag von rechts → rechts nach links → false
      // Der zweite zusätzliche Schlag kommt dann von links → links nach rechts → true
      // etc.
      
      // Wenn der Hauptschlag kein Aufschlag ist und von links kommt, endet er rechts
      // Dann kommt der erste zusätzliche Schlag von rechts → rechts nach links → false
      
      // Wenn der Hauptschlag von rechts kommt, endet er links
      // Dann kommt der erste zusätzliche Schlag von links → links nach rechts → true
      
      const nextIdx = this.additionalStrokes.length;
      const isMainStrokeEndingRight = this.isMainStrokeLeftToRight();
      
      // Wenn der Hauptschlag rechts endet (links nach rechts), dann:
      // - erster zusätzlicher Schlag kommt von rechts → rechts nach links → false
      // - zweiter zusätzlicher Schlag kommt von links → links nach rechts → true
      if (isMainStrokeEndingRight) {
        return nextIdx % 2 === 1; // ungerade Index = links nach rechts
      } else {
        // Wenn der Hauptschlag links endet (rechts nach links), dann:
        // - erster zusätzlicher Schlag kommt von links → links nach rechts → true
        // - zweiter zusätzlicher Schlag kommt von rechts → rechts nach links → false
        return nextIdx % 2 === 0; // gerade Index = links nach rechts
      }
    },
    
    // Berechne Mittelpunkt eines rechten Zielkreises (1..9)
    computeRightTargetCenter(tableX, tableY, tableWidth, tableHeight, number) {
      const cfg = this.config.targetCircles;
      const x1 = tableX + tableWidth - cfg.rightXOffset;
      const x3 = tableX + tableWidth/2 + cfg.middleXOffset;
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff/2;
      const yTop = tableY + cfg.topYOffset;
      const yMid = tableY + tableHeight/2;
      const yBot = tableY + tableHeight - cfg.bottomYOffset;
      const map = {
        1: { x: x1, y: yTop }, 2: { x: x1, y: yMid }, 3: { x: x1, y: yBot },
        4: { x: x2, y: yTop }, 5: { x: x2, y: yMid }, 6: { x: x2, y: yBot },
        7: { x: x3, y: yTop }, 8: { x: x3, y: yMid }, 9: { x: x3, y: yBot }
      };
      return map[number] || null;
    },
    // Berechne Mittelpunkt eines linken Zielkreises (1..9 gespiegelt)
    computeLeftTargetCenter(tableX, tableY, tableWidth, tableHeight, number) {
      const cfg = this.config.leftTargetCircles;
      const x1 = tableX + cfg.leftXOffset;
      const x3 = tableX + tableWidth / 2 - cfg.rightXOffset;
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff/2;
      const yTop = tableY + cfg.topYOffset;
      const yMid = tableY + tableHeight/2;
      const yBot = tableY + tableHeight - cfg.bottomYOffset;
      const map = {
        1: { x: x1, y: yBot }, 2: { x: x1, y: yMid }, 3: { x: x1, y: yTop },
        4: { x: x2, y: yBot }, 5: { x: x2, y: yMid }, 6: { x: x2, y: yTop },
        7: { x: x3, y: yBot }, 8: { x: x3, y: yMid }, 9: { x: x3, y: yTop }
      };
      return map[number] || null;
    },
    
    // Zeichnet zusätzliche Pfeile abwechselnd rechts/links aus additionalStrokes
    drawAdditionalArrows(ctx, tableX, tableY, tableWidth, tableHeight) {
      if (!this.additionalStrokes || this.additionalStrokes.length === 0) return;
      const max = this.additionalStrokes.length;
      // 1: rot, 2: blau, 3: gelb, 4: violett, ab 5: pink
      const colors = [
        COURT_TOOL_PALETTE.arrowSupport,
        COURT_TOOL_PALETTE.arrowHighlight,
        COURT_TOOL_PALETTE.arrowAlternate,
        COURT_TOOL_PALETTE.arrowAccent
      ];
      const rightRadius = this.config.targetCircles.radius;
      const leftRadius = this.config.leftTargetCircles.radius;
      
      // Quelle: Ende des ersten Pfeils (rechts)
      const firstNum = parseInt(this.targetPosition);
      const firstCenter = this.computeRightTargetCenter(tableX, tableY, tableWidth, tableHeight, firstNum);
      let prevPoint = { x: firstCenter.x - rightRadius, y: firstCenter.y }; // linke Kante des rechten Kreises
      let prevSide = 'right';
      
      for (let i = 0; i < max; i++) {
        const stroke = this.additionalStrokes[i];
        const side = i % 2 === 0 ? 'left' : 'right';
        const targetNum = parseInt(stroke.targetPosition);
        // Farben: 2. blau, 3. gelb, 4. violett, ab dem 5. pink
        const color = (i < colors.length) ? colors[i] : COURT_TOOL_PALETTE.arrowAccent;
        let toCenter, toPoint;
        if (side === 'left') {
          toCenter = this.computeLeftTargetCenter(tableX, tableY, tableWidth, tableHeight, targetNum);
          toPoint = { x: toCenter.x + leftRadius, y: toCenter.y }; // rechte Kante des linken Kreises
        } else {
          toCenter = this.computeRightTargetCenter(tableX, tableY, tableWidth, tableHeight, targetNum);
          toPoint = { x: toCenter.x - rightRadius, y: toCenter.y }; // linke Kante des rechten Kreises
        }
        // Linie
        ctx.strokeStyle = color;
        ctx.fillStyle = color;
        ctx.lineWidth = this.config.arrow.width;
        ctx.lineCap = this.config.arrow.cap;
        // Nummer
        ctx.font = this.config.arrow.counterFont;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        const midX = (prevPoint.x + toPoint.x) / 2;
        const midY = (prevPoint.y + toPoint.y) / 2 - this.config.arrow.counterOffset;
        ctx.fillText(String(i + 2), midX, midY);
        // Linie zeichnen
        ctx.beginPath();
        ctx.moveTo(prevPoint.x, prevPoint.y);
        ctx.lineTo(toPoint.x, toPoint.y);
        ctx.stroke();
        // Pfeilkopf
        const angle = Math.atan2(toPoint.y - prevPoint.y, toPoint.x - prevPoint.x);
        const sz = this.config.arrow.headSize;
        ctx.beginPath();
        ctx.moveTo(toPoint.x, toPoint.y);
        ctx.lineTo(toPoint.x - sz * Math.cos(angle - Math.PI / 6), toPoint.y - sz * Math.sin(angle - Math.PI / 6));
        ctx.moveTo(toPoint.x, toPoint.y);
        ctx.lineTo(toPoint.x - sz * Math.cos(angle + Math.PI / 6), toPoint.y - sz * Math.sin(angle + Math.PI / 6));
        ctx.stroke();
        
        // nächste Quelle ist die Pfeilspitze dieses Schlages
        prevPoint = toPoint;
        prevSide = side;
      }
    },
    
    drawLeftSideTargetCircles(ctx, tableX, tableY, tableWidth, tableHeight) {
      const config = this.config.leftTargetCircles;
      // Kreise auf der linken Tischhälfte (spiegelbildlich zu rechts)
      const x1 = tableX + config.leftXOffset; // Linker Tischrand (Lang)
      const x3 = tableX + tableWidth / 2 - config.rightXOffset; // Näher am Netz (Kurz)
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff / 2; // Mitte (Halblang)
      
      const positions = [
        { x: x1, y: tableY + config.topYOffset, num: 3 },    // RH Lang (gespiegelt)
        { x: x1, y: tableY + tableHeight / 2, num: 2 },    // M Lang
        { x: x1, y: tableY + tableHeight - config.bottomYOffset, num: 1 }, // VH Lang (gespiegelt)
        { x: x2, y: tableY + config.topYOffset, num: 6 },    // RH Halblang (gespiegelt)
        { x: x2, y: tableY + tableHeight / 2, num: 5 },    // M Halblang
        { x: x2, y: tableY + tableHeight - config.bottomYOffset, num: 4 }, // VH Halblang (gespiegelt)
        { x: x3, y: tableY + config.topYOffset, num: 9 },    // RH Kurz (gespiegelt)
        { x: x3, y: tableY + tableHeight / 2, num: 8 },    // M Kurz
        { x: x3, y: tableY + tableHeight - config.bottomYOffset, num: 7 }  // VH Kurz (gespiegelt)
      ];
      
      positions.forEach(pos => {
        ctx.beginPath();
        ctx.arc(pos.x, pos.y, config.radius, 0, 2 * Math.PI);
        ctx.fillStyle = config.unselectedColor;
        ctx.fill();
        
        // Hervorhebung wenn ausgewählt
        if (this.nextStrokeTargetPosition === pos.num.toString()) {
          ctx.strokeStyle = config.selectedBorderColor;
          ctx.lineWidth = config.selectedBorderWidth;
        } else {
          ctx.strokeStyle = config.unselectedBorderColor;
          ctx.lineWidth = config.unselectedBorderWidth;
        }
        ctx.stroke();
        
        // Nummer in den Kreis zeichnen
        ctx.fillStyle = config.textColor;
        ctx.font = config.font;
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(pos.num.toString(), pos.x, pos.y);
      });
    },
    
    startDrawing(e) {
      const rect = this.canvas.getBoundingClientRect();
      const clickX = e.clientX - rect.left;
      const clickY = e.clientY - rect.top;
      
      // Prüfe ob auf eine Startposition geklickt wurde
      const clickedCircle = this.checkStartPositionClick(clickX, clickY);
      if (clickedCircle) {
        this.selectedCirclePosition = clickedCircle.circlePosition;
        this.selectedStartPosition = clickedCircle.position;
        this.drawCourt(); // Neu zeichnen für Kreis-Hervorhebung
        this.emitDrawingData();
        this.updateTextFields();
        return;
      }
      
      // Prüfe ob auf eine Zielposition geklickt wurde
      const clickedTarget = this.checkTargetPositionClick(clickX, clickY);
      if (clickedTarget) {
        // Wenn noch kein Hauptziel gesetzt: setze es
        if (!this.targetPosition) {
          this.targetPosition = clickedTarget;
          // Wenn keine Startposition ausgewählt ist, setze standardmäßig die mittlere Startposition (AS2)
          if (!this.selectedStartPosition) {
            this.selectedStartPosition = 'AS2';
            this.selectedCirclePosition = 'middle';
          }
          this.drawCourt();
          this.emitDrawingData();
          this.updateTextFields();
          return;
        }
        // Andernfalls: wenn wir einen Zusatzschlag auf die rechte Seite wählen sollen
        if (this.targetPosition && this.additionalStrokes.length < 4 && this.getNextAdditionalSide() === 'right') {
          this.nextStrokeTargetPosition = clickedTarget;
          this.drawCourt();
          this.emitDrawingData();
          this.updateTextFields();
          return;
        }
      }
      
      // Prüfe ob auf eine linke Zielposition geklickt wurde (nur wenn Zusatzschlag links erwartet)
      if (this.nextStrokeType && this.nextStrokeSide && this.targetPosition && this.getNextAdditionalSide() === 'left') {
        const clickedLeftTarget = this.checkLeftTargetPositionClick(clickX, clickY);
        if (clickedLeftTarget) {
          this.nextStrokeTargetPosition = clickedLeftTarget;
          this.drawCourt();
          this.emitDrawingData();
          this.updateTextFields();
          return;
        }
      }
      
      // Nur zeichnen wenn kein Kreis geklickt wurde
      this.isDrawing = true;
      this.startX = clickX;
      this.startY = clickY;
      this.lastX = this.startX;
      this.lastY = this.startY;
    },
    
    checkStartPositionClick(x, y) {
      const config = this.config;
      const tableWidth = config.table.width;
      const tableHeight = config.table.height;
      const tableX = (this.canvas.width - tableWidth) / 2;
      const tableY = (this.canvas.height - tableHeight) / 2;
      
      const circleRadius = config.startCircles.radius;
      const circleX = config.startCircles.x;
      const topCircleY = tableY + config.startCircles.topYOffset;
      const middleCircleY = tableY + tableHeight / 2;
      const bottomCircleY = tableY + tableHeight - config.startCircles.bottomYOffset;
      
      // Prüfe Abstand zu den Kreisen
      const circles = [
        { x: circleX, y: topCircleY, position: 'AS1', circlePosition: 'top' },
        { x: circleX, y: middleCircleY, position: 'AS2', circlePosition: 'middle' },
        { x: circleX, y: bottomCircleY, position: 'AS3', circlePosition: 'bottom' }
      ];
      
      for (const circle of circles) {
        const distance = Math.sqrt((x - circle.x) ** 2 + (y - circle.y) ** 2);
        if (distance <= circleRadius) {
          return circle; // Gibt das komplette Circle-Objekt zurück
        }
      }
      
      return null;
    },
    
    checkTargetPositionClick(x, y) {
      if (!this.spinType) return null; // Nur wenn Schnittoption gewählt
      
      const config = this.config;
      const tableWidth = config.table.width;
      const tableHeight = config.table.height;
      const tableX = (this.canvas.width - tableWidth) / 2;
      const tableY = (this.canvas.height - tableHeight) / 2;
      
      const targetRadius = config.targetCircles.radius;
      
      const x1 = tableX + tableWidth - config.targetCircles.rightXOffset;
      const x3 = tableX + tableWidth/2 + config.targetCircles.middleXOffset;
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff/2;
      
      // Positionen der 9 Kreise (gleiche wie in drawTargetPositions)
      const positions = [
        // Rechts (1, 2, 3) - am rechten Tischrand: L (Lang)
        { x: x1, y: tableY + config.targetCircles.topYOffset, number: 1, label: 'VHL' },
        { x: x1, y: tableY + tableHeight/2, number: 2, label: 'ML' },
        { x: x1, y: tableY + tableHeight - config.targetCircles.bottomYOffset, number: 3, label: 'RHL' },
        // Mitte (4, 5, 6) - zwischen 1-3 und 7-9: H (Halblang)
        { x: x2, y: tableY + config.targetCircles.topYOffset, number: 4, label: 'VHH' },
        { x: x2, y: tableY + tableHeight/2, number: 5, label: 'MH' },
        { x: x2, y: tableY + tableHeight - config.targetCircles.bottomYOffset, number: 6, label: 'RHH' },
        // Zwischen Netz und Mitte (7, 8, 9) - näher am Netz: K (Kurz)
        { x: x3, y: tableY + config.targetCircles.topYOffset, number: 7, label: 'VHK' },
        { x: x3, y: tableY + tableHeight/2, number: 8, label: 'MK' },
        { x: x3, y: tableY + tableHeight - config.targetCircles.bottomYOffset, number: 9, label: 'RHK' }
      ];
      
      for (const pos of positions) {
        const distance = Math.sqrt((x - pos.x) ** 2 + (y - pos.y) ** 2);
        if (distance <= targetRadius) {
          return pos.number.toString();
        }
      }
      
      return null;
    },
    
    checkLeftTargetPositionClick(x, y) {
      const canvas = this.canvas;
      if (!canvas) return null;
      
      const config = this.config;
      // Verwende dieselben Maße wie rechts (Canvas-Maße, nicht getBoundingClientRect)
      const tableWidth = config.table.width;
      const tableHeight = config.table.height;
      const tableX = (canvas.width - tableWidth) / 2;
      const tableY = (canvas.height - tableHeight) / 2;
      
      const targetRadius = config.leftTargetCircles.radius;
      
      // Spiegelbildliche X-Positionen zur rechten Seite
      const x1 = tableX + config.leftTargetCircles.leftXOffset; // Linker Tischrand (Lang)
      const x3 = tableX + tableWidth / 2 - config.leftTargetCircles.rightXOffset; // Näher am Netz (Kurz)
      const xdiff = x3 - x1;
      const x2 = x3 - xdiff / 2; // Mitte (Halblang)
      
      const positions = [
        { x: x1, y: tableY + config.leftTargetCircles.topYOffset, num: 3 },    // RH Lang (gespiegelt)
        { x: x1, y: tableY + tableHeight / 2, num: 2 },    // M Lang
        { x: x1, y: tableY + tableHeight - config.leftTargetCircles.bottomYOffset, num: 1 }, // VH Lang (gespiegelt)
        { x: x2, y: tableY + config.leftTargetCircles.topYOffset, num: 6 },    // RH Halblang (gespiegelt)
        { x: x2, y: tableY + tableHeight / 2, num: 5 },    // M Halblang
        { x: x2, y: tableY + tableHeight - config.leftTargetCircles.bottomYOffset, num: 4 }, // VH Halblang (gespiegelt)
        { x: x3, y: tableY + config.leftTargetCircles.topYOffset, num: 9 },    // RH Kurz (gespiegelt)
        { x: x3, y: tableY + tableHeight / 2, num: 8 },    // M Kurz
        { x: x3, y: tableY + tableHeight - config.leftTargetCircles.bottomYOffset, num: 7 }  // VH Kurz (gespiegelt)
      ];
      
      for (const pos of positions) {
        const distance = Math.sqrt((x - pos.x) ** 2 + (y - pos.y) ** 2);
        if (distance <= targetRadius) {
          return pos.num.toString();
        }
      }
      
      return null;
    },
    
    draw(e) {
      if (!this.isDrawing) return;
      
      const rect = this.canvas.getBoundingClientRect();
      const currentX = e.clientX - rect.left;
      const currentY = e.clientY - rect.top;
      
      this.ctx.strokeStyle = this.config.pen.color;
      this.ctx.lineWidth = this.config.pen.width;
      
      this.ctx.beginPath();
      this.ctx.moveTo(this.lastX, this.lastY);
      this.ctx.lineTo(currentX, currentY);
      this.ctx.stroke();
      
      this.lastX = currentX;
      this.lastY = currentY;
    },
    
    stopDrawing() {
      if (!this.isDrawing) return;
      this.isDrawing = false;
    },
    
    clearCanvas() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.drawCourt();
    },
    
    
    async saveDrawing() {
      
      try {
        const dataURL = this.canvas.toDataURL('image/png');
        
        this.$emit('input', dataURL);
        
        // Erstelle Zeichnungsdaten für Metadaten
        const drawingData = {
          selectedStartPosition: this.selectedStartPosition,
          strokeType: this.strokeType,
          spinType: this.spinType,
          targetPosition: this.targetPosition,
          nextStrokeType: this.nextStrokeType,
          nextStrokeSide: this.nextStrokeSide,
          nextStrokeTargetPosition: this.nextStrokeTargetPosition,
          exerciseCounter: this.exerciseCounter,
          additionalStrokes: this.additionalStrokes,
          code: this.getFullCode ? this.getFullCode() : '',
          timestamp: new Date().toISOString()
        };
        
      // Immer Metadaten nach oben geben
      this.$emit('update-drawing-data', drawingData);
      
      if (this.allowImageUpload) {
        // Konvertiere DataURL zu Blob für Upload
        const response = await fetch(dataURL);
        const blob = await response.blob();
        
        // Erstelle File-Objekt
        const file = new File([blob], `exercise-${Date.now()}.png`, { type: 'image/png' });
        
        // Emittiere das File und die Zeichnungsdaten für Upload
        this.$emit('upload-image', file, drawingData);
      } else {
        // Kein Bild-Upload mehr: gebe lediglich die Zeichnungsdaten an den Parent weiter,
        // damit Felder (Kürzel/Name/Beschreibung) gefüllt werden können
        this.$emit('update-fields', {
          code: this.getFullCode ? this.getFullCode() : '',
          name: this.getFullTitle ? this.getFullTitle() : '',
          description: ''
        });
      }
      } catch (error) {
        // Fehlerbehandlung
      }
    },
    
    loadDrawing() {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = 'image/*';
      input.onchange = (e) => {
        const file = e.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            this.loadDrawingFromData(e.target.result);
          };
          reader.readAsDataURL(file);
        }
      };
      input.click();
    },
    
    resetAllValues() {
      this.selectedStartPosition = null;
      this.selectedCirclePosition = null;
      this.strokeType = null;
      this.spinType = null;
      this.targetPosition = null;
      this.nextStrokeType = null;
      this.nextStrokeSide = null;
      this.nextStrokeTargetPosition = null;
      this.exerciseCounter = 1;
      this.additionalStrokes = [];
      this.updateTextFields();
    },
    
    loadDrawingFromMetadata() {
      if (this.drawingData) {
        
        // Lade alle Zeichnungsdaten
        this.selectedStartPosition = this.drawingData.selectedStartPosition || null;
        this.strokeType = this.drawingData.strokeType || null;
        this.spinType = this.drawingData.spinType || null;
        this.targetPosition = this.drawingData.targetPosition || null;
        this.nextStrokeType = this.drawingData.nextStrokeType || null;
        this.nextStrokeSide = this.drawingData.nextStrokeSide || null;
        this.nextStrokeTargetPosition = this.drawingData.nextStrokeTargetPosition || null;
        this.exerciseCounter = this.drawingData.exerciseCounter || 1;
        this.additionalStrokes = this.drawingData.additionalStrokes || [];
        
        // Setze selectedCirclePosition basierend auf selectedStartPosition
        if (this.selectedStartPosition === 'AS') {
          this.selectedCirclePosition = 'middle'; // Standard für AS
        } else if (this.selectedStartPosition === 'AS1') {
          this.selectedCirclePosition = 'top';
        } else if (this.selectedStartPosition === 'AS2') {
          this.selectedCirclePosition = 'middle';
        } else if (this.selectedStartPosition === 'AS3') {
          this.selectedCirclePosition = 'bottom';
        }
        
        this.$emit('drawing-data', {
          selectedStartPosition: this.selectedStartPosition,
          selectedCirclePosition: this.selectedCirclePosition,
          strokeType: this.strokeType,
          spinType: this.spinType,
          targetPosition: this.targetPosition
        });
        
        // Aktualisiere die Textfelder
        this.updateTextFields();
        
        // Zeichne das Canvas neu
        this.$nextTick(() => {
          this.drawCourt();
        });
        
      }
    },
    
    loadDrawingFromData(dataURL) {
      const img = new Image();
      img.onload = () => {
        this.clearCanvas();
        this.ctx.drawImage(img, 0, 0);
      };
      img.src = dataURL;
    },
    
    
    getFullCode() {
      if (!this.selectedStartPosition || !this.strokeType) return '';
      
      // Kürzel-Mapping für Schnittoptionen
      const spinCodeMap = {
        'Unterschnitt': 'US',
        'Überschnitt': 'OS', 
        'Seitschnitt': 'SR',
        'Seitunterschnitt': 'SU',
        'Gegenläufer': 'GL'
      };
      
      // Suffix-Mapping für Startposition (an AS direkt anhängen, ohne Leerzeichen)
      const startSuffixMap = {
        'AS1': 'vL',
        'AS2': 'vM',
        'AS3': 'vR'
      };
      const startSuffix = startSuffixMap[this.selectedStartPosition] || '';
      const startCode = `AS${startSuffix}`;
      
      // Label-Mapping für erstes Ziel (Hauptpfeil): altes Schema
      const mainTargetLabelMap = {
        '1': 'VH L', '2': 'M L', '3': 'RH L',
        '4': 'VH H', '5': 'M H', '6': 'RH H',
        '7': 'VH K', '8': 'M K', '9': 'RH K'
      };
      // Label-Mapping für Zusatzschläge: wie Hauptziel (VH L, M L, RH L ...)
      const additionalTargetLabelMap = mainTargetLabelMap;
      
      let code = `${startCode} ${this.strokeType}`;
      if (this.spinType) {
        const spinCode = spinCodeMap[this.spinType] || this.spinType;
        code += ` ${spinCode}`;
      }
      if (this.targetPosition) {
        const targetLabel = mainTargetLabelMap[this.targetPosition] || this.targetPosition;
        code += ` → ${targetLabel}`;
      }
      
      // Zusätzliche Schläge hinzufügen
      if (this.additionalStrokes.length > 0) {
        this.additionalStrokes.forEach(stroke => {
          const targetLabel = additionalTargetLabelMap[stroke.targetPosition] || stroke.targetPosition;
          code += ` / ${stroke.side} ${stroke.type} → ${targetLabel}`;
        });
      }
      
      return code;
    },
    
    getFullTitle() {
      if (!this.selectedStartPosition || !this.strokeType) return '';
      
      const strokeName = this.strokeType === 'VH' ? this.$t('courtDrawingTool.forehand') : this.$t('courtDrawingTool.backhand');
      let title = `${this.$t('courtDrawingTool.serviceTitle')} ${strokeName}`;
      if (this.spinType) {
        title = `${this.$t('courtDrawingTool.serviceTitle')} ${strokeName} ${this.spinType}`;
      }
      if (this.targetPosition) {
        const targetDescription = this.formatTargetPosition(this.targetPosition);
        title += ` → ${targetDescription}`;
      }
      
      // Zusätzliche Schläge hinzufügen
      if (this.additionalStrokes.length > 0) {
        this.additionalStrokes.forEach(stroke => {
          const strokeName = this.formatAdditionalStrokeType(stroke.type);
          const sideName = this.formatStrokeSide(stroke.side);
          const targetDescription = this.formatTargetPosition(stroke.targetPosition);
          title += ` / ${sideName} ${strokeName} → ${targetDescription}`;
        });
      }
      
      return title;
    },
    
    addNextStroke() {
      if (!this.nextStrokeTargetPosition) return;
      if (this.additionalStrokes.length >= 4) return;
      
      // Neuen Schlag zur Liste hinzufügen
      this.additionalStrokes.push({
        side: this.nextStrokeSide,
        type: this.nextStrokeType,
        targetPosition: this.nextStrokeTargetPosition,
        counter: this.exerciseCounter + this.additionalStrokes.length + 1
      });
      
      // Counter erhöhen
      this.exerciseCounter++;
      // Auswahl für nächsten Zusatzschlag zurücksetzen
      this.nextStrokeTargetPosition = '';
      
      // Textfelder aktualisieren
      this.updateTextFields();
      
      // Canvas neu zeichnen
      this.drawCourt();
      this.emitDrawingData();
    },
    
    updateTextFields() {
      if (!this.selectedStartPosition || !this.strokeType) return;
      
      const code = this.getFullCode();
      const title = this.getFullTitle();
      const description = `Tischtennis-Übung: ${title} von Position ${this.selectedStartPosition}`;
      
      // Event an Parent-Komponente senden
      this.$emit('update-fields', {
        code: code,
        name: title,
        description: description
      });
    }
    ,
    emitDrawingData() {
      const drawingData = {
        selectedStartPosition: this.getEffectiveStartPosition(),
        selectedCirclePosition: this.resolveStartCirclePosition(),
        strokeType: this.strokeType,
        spinType: this.spinType,
        targetPosition: this.targetPosition,
        nextStrokeType: this.nextStrokeType,
        nextStrokeSide: this.nextStrokeSide,
        nextStrokeTargetPosition: this.nextStrokeTargetPosition,
        exerciseCounter: this.exerciseCounter,
        additionalStrokes: this.additionalStrokes,
        code: this.getFullCode ? this.getFullCode() : ''
      };
      this.$emit('update-drawing-data', drawingData);
    },

    getEffectiveStartPosition() {
      if (this.selectedStartPosition === 'AS1' || this.selectedStartPosition === 'AS2' || this.selectedStartPosition === 'AS3') {
        return this.selectedStartPosition;
      }
      if (this.selectedCirclePosition === 'top') return 'AS1';
      if (this.selectedCirclePosition === 'middle') return 'AS2';
      if (this.selectedCirclePosition === 'bottom') return 'AS3';
      return 'AS2';
    }
  }
}
</script>

<style scoped>
.court-drawing-tool {
  display: flex;
  flex-direction: column;
  border: 1px solid var(--border-color);
  border-radius: 14px;
  padding: 1rem;
  background: var(--surface-color, #ffffff);
  box-shadow: 0 10px 26px rgba(15, 23, 42, 0.06);
  min-height: 0;
  height: 100%;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.tool-header h4 {
  margin: 0;
  color: var(--text-color);
}

.tool-layout {
  display: grid;
  grid-template-columns: minmax(360px, 430px) minmax(0, 1fr);
  gap: 1rem;
  align-items: stretch;
  min-height: 0;
  flex: 1;
  overflow: hidden;
}

.tool-controls {
  display: flex;
  gap: 0.5rem;
}

.preview-panel {
  display: flex;
  flex-direction: column;
  gap: 0.85rem;
  min-height: 0;
  align-self: stretch;
}

.exercise-selection {
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  min-height: 0;
  max-height: 100%;
  padding-right: 0.25rem;
  padding: 1rem;
  background: var(--background-soft);
  border-radius: 12px;
  border: 1px solid var(--border-color);
}

.preview-panel-header {
  padding: 0.9rem;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  background: var(--surface-color, #ffffff);
}

.canvas-container {
  text-align: center;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  background: var(--background-soft);
  padding: 0.75rem;
}

.canvas-placeholder {
  display: flex;
  flex-direction: column;
  gap: 0.45rem;
  padding: 1rem;
  border: 1px dashed var(--border-color);
  border-radius: 12px;
  background: var(--background-soft);
  color: var(--text-muted);
}

.canvas-placeholder strong {
  color: var(--text-color);
}

canvas {
  max-width: 100%;
  height: auto;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  cursor: crosshair;
  background: var(--surface-color, #ffffff);
}


.btn-small {
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
  border-radius: 999px;
  border: 1px solid var(--border-color);
  cursor: pointer;
  transition: transform 0.2s ease, opacity 0.2s ease, border-color 0.2s ease;
  min-width: 2.5rem;
  text-align: center;
  background: var(--surface-color, #ffffff);
  color: var(--text-color);
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border-color: transparent;
}

.btn-primary:hover {
  opacity: 0.95;
  transform: translateY(-1px);
}

.btn-secondary {
  background: var(--surface-color, #ffffff);
  color: var(--text-color);
  border-color: var(--border-color);
}

.btn-secondary:hover {
  border-color: var(--primary-color);
  transform: translateY(-1px);
}

.btn-stroke {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  border-color: transparent;
}

.btn-stroke:hover {
  opacity: 0.95;
  transform: translateY(-1px);
}

.btn-stroke.btn-secondary {
  background: var(--surface-color, #ffffff);
  color: var(--text-color);
  border-color: var(--border-color);
}

.btn-stroke.btn-secondary:hover {
  border-color: var(--primary-color);
  transform: translateY(-1px);
}

.btn-stroke-type {
  background: linear-gradient(135deg, #b56a1d, #8f5316);
  color: var(--text-on-primary);
  border-color: transparent;
}

.btn-stroke-type:hover {
  opacity: 0.95;
  transform: translateY(-1px);
}

.btn-stroke-type.btn-secondary {
  background: rgba(181, 106, 29, 0.12);
  color: #8f5316 !important;
  border-color: rgba(181, 106, 29, 0.22);
  opacity: 1;
}

.btn-stroke-type.btn-secondary:hover {
  background: rgba(181, 106, 29, 0.18);
  border-color: rgba(181, 106, 29, 0.3) !important;
}

.group-label {
  display: block;
  margin: 0 0 4px 0;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-muted);
}

input[type="color"] {
  width: 40px;
  height: 30px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type="range"] {
  width: 100px;
}

.exercise-selection h5 {
  margin: 0 0 1rem 0;
  color: var(--text-color);
}

.workflow-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 0.9rem;
}

.workflow-card {
  padding: 0.9rem;
  border: 1px solid var(--border-color);
  border-radius: 12px;
  background: var(--surface-color, #ffffff);
}

.workflow-card-wide {
  grid-column: 1 / -1;
}

.workflow-step {
  margin-bottom: 0.35rem;
  font-size: 0.82rem;
  font-weight: 700;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  color: var(--primary-color);
}

.workflow-toggle {
  width: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 0.75rem;
  padding: 0;
  border: none;
  background: transparent;
  text-align: left;
  cursor: pointer;
}

.workflow-toggle-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 999px;
  background: rgba(29, 90, 61, 0.1);
  color: var(--primary-color);
  font-size: 1rem;
  font-weight: 700;
  flex-shrink: 0;
}

.workflow-copy {
  margin: 0 0 0.85rem 0;
  color: var(--text-muted);
  font-size: 0.9rem;
}

.workflow-copy-compact {
  margin-bottom: 0;
}

.workflow-section-body {
  margin-top: 0.85rem;
}

.workflow-block + .workflow-block {
  margin-top: 0.9rem;
}

.choice-row {
  display: flex;
  gap: 0.55rem;
  flex-wrap: wrap;
}

.choice-row-dense {
  gap: 0.45rem;
}

.choice-chip {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  min-width: 90px;
  gap: 0.15rem;
  padding: 0.55rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  background: var(--surface-color, #ffffff);
  color: var(--text-color);
  cursor: pointer;
  transition: border-color 0.2s ease, transform 0.2s ease, background 0.2s ease;
}

.choice-chip:hover {
  transform: translateY(-1px);
  border-color: var(--primary-soft);
}

.choice-chip strong {
  font-size: 0.82rem;
  line-height: 1;
}

.choice-chip span {
  font-size: 0.78rem;
  color: var(--text-muted);
}

.choice-chip-active {
  background: linear-gradient(135deg, rgba(29, 90, 61, 0.1), rgba(29, 90, 61, 0.16));
  border-color: var(--primary-color);
}

.choice-chip-active span {
  color: var(--text-color);
}

.choice-chip-compact {
  min-width: 84px;
}

.next-stroke-selection {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 0.9rem;
  align-items: end;
}

.exercise-info {
  background: var(--surface-color, #ffffff);
  padding: 0.75rem;
  border-radius: 10px;
  border: 1px solid var(--border-color);
  margin-top: 1rem;
}

.exercise-info p {
  margin: 0.25rem 0;
  font-size: 0.9rem;
}

/* Kompakte 3x3 Zielauswahl */
.target-grid {
  display: grid;
  grid-template-columns: repeat(3, 24px);
  grid-auto-rows: 24px;
  gap: 0;
}

.target-grid-large {
  grid-template-columns: repeat(3, 44px);
  grid-auto-rows: 44px;
  gap: 0.35rem;
}

.grid-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  padding: 0;
  margin: 0;
  border: none;
  border-radius: 6px;
  background: var(--primary-soft);
  color: var(--primary-dark);
  font-size: 12px;
  font-weight: 500;
  line-height: 1;
  cursor: pointer;
  border: 1px solid rgba(29, 90, 61, 0.14);
}

.target-grid-large .grid-btn {
  width: 44px;
  height: 44px;
  border-radius: 10px;
  font-size: 0.92rem;
}

.grid-btn.is-active {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
  font-weight: 700; /* fett */
}

.stroke-sequence-list {
  display: flex;
  flex-direction: column;
  gap: 0.55rem;
  margin-bottom: 0.9rem;
}

.stroke-sequence-item {
  display: grid;
  grid-template-columns: 32px 1fr auto;
  gap: 0.75rem;
  align-items: center;
  padding: 0.6rem 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  background: var(--background-soft);
}

.stroke-sequence-index {
  display: grid;
  place-items: center;
  width: 32px;
  height: 32px;
  border-radius: 999px;
  background: rgba(29, 90, 61, 0.1);
  color: var(--primary-color);
  font-weight: 700;
}

.stroke-sequence-copy {
  color: var(--text-color);
  font-size: 0.92rem;
}

.stroke-sequence-remove {
  border: 1px solid rgba(200, 74, 56, 0.22);
  background: rgba(200, 74, 56, 0.08);
  color: #8b3327;
  border-radius: 8px;
  padding: 0.45rem 0.65rem;
  cursor: pointer;
}

.stroke-sequence-empty {
  margin-bottom: 0.9rem;
  padding: 0.75rem;
  border-radius: 10px;
  background: rgba(29, 90, 61, 0.06);
  color: var(--text-muted);
}

.btn-stroke.btn-primary {
  color: COURT_TOOL_PALETTE.accentText !important;
  font-weight: 700;
}

.btn-stroke-type.btn-primary {
  color: COURT_TOOL_PALETTE.accentText !important;
  font-weight: 700;
}

.add-stroke-button {
  align-self: start;
  min-height: 44px;
}

@media (max-width: 720px) {
  .tool-layout,
  .workflow-grid,
  .next-stroke-selection {
    grid-template-columns: 1fr;
  }

  .preview-panel {
    position: static;
  }

  .choice-chip {
    min-width: calc(50% - 0.4rem);
  }
}
</style>
