@php
  $contest = $contest ?? null;
  $contestType = $contestType ?? ($contest->contest_type ?? 'paid');
  $contestTypeLabel = $contestTypeLabel ?? ($contestType === 'free' ? 'Free Exam' : 'Paid Competition');
  $isFreeModule = $contestType === 'free';
  $pageTitle = $pageTitle ?? 'Competition';
  $heroTitle = $heroTitle ?? $pageTitle;
  $heroDescription = $heroDescription ?? 'Manage competition details from this screen.';
  $submitLabel = $submitLabel ?? 'Save';
  $formAction = $formAction ?? '#';
  $manageRouteName = $manageRouteName ?? 'admin.managecontest';
  $prizeRows = collect($prizeRows ?? [])->map(function ($row) {
      return [
          'amount' => $row['amount'] ?? '',
          'start' => $row['start'] ?? '',
          'end' => $row['end'] ?? '',
      ];
  })->values();

  if ($prizeRows->isEmpty()) {
      $prizeRows = collect([['amount' => '', 'start' => '', 'end' => '']]);
  }

  $rewardRowCount = $prizeRows->count();
  $summaryCards = $contest
      ? [
          'Contest ID' => '#'.$contest->id,
          'Exam Type' => $contestTypeLabel,
          'Prize Pool' => 'Rs. '.number_format((float) old('prizetottalamount', $contest->totalamount ?? 0), 2),
          'Join Amount' => 'Rs. '.number_format((float) old('joinprice', $contest->joinamt ?? 0), 2),
      ]
      : [
          'Mode' => $contestTypeLabel,
          'Reward Rows' => number_format($rewardRowCount),
          'Entry Limit' => (string) old('userenrery', '1'),
          'Security' => 'Validated before save',
      ];
@endphp

<div class="portal-page-shell">
  <div class="portal-hero-card">
    <div class="portal-hero-main">
      <div class="portal-hero-copy">
        <h5>{{ $heroTitle }}</h5>
        <p>{{ $heroDescription }}</p>
        <div class="portal-chip-list">
          <span class="portal-chip">{{ $contestTypeLabel }}</span>
          @if($isFreeModule)
            <span class="portal-chip">Top 3 Per Class / Day</span>
            <span class="portal-chip">Final Top 10 Scholarship</span>
          @else
            <span class="portal-chip">Seat Based Competition</span>
            <span class="portal-chip">Reward Distribution Ready</span>
          @endif
          <span class="portal-chip">Secure Validation Enabled</span>
        </div>
        <div class="portal-hero-actions">
          <a href="{{ route($manageRouteName) }}" class="btn btn-outline-primary btn-sm">Back to List</a>
          @if($contest)
            <a href="{{ route('admin.applieddetails', ['id' => $contest->id]) }}" class="btn btn-info btn-sm">View Applied Users</a>
          @endif
        </div>
      </div>
    </div>
  </div>

  <div class="portal-summary-grid">
    @foreach($summaryCards as $label => $value)
      <div class="portal-summary-card">
        <span>{{ $label }}</span>
        <strong>{{ $value }}</strong>
      </div>
    @endforeach
  </div>

  <form action="{{ $formAction }}" method="post" class="portal-form-shell" id="contestBuilderForm">
    @csrf
    <input type="hidden" name="contest_type" value="{{ $contestType }}">
    @if($contest)
      <input type="hidden" name="editid" value="{{ $contest->id }}">
    @endif

    <div class="portal-form-section">
      <h6>Competition Overview</h6>
      <p>
        @if($isFreeModule)
          Set the free exam title, seat plan and entry rules. Scholarship winners will be calculated later from the daily class-wise pool.
        @else
          Set the competition title, entry rules, seats and overall prize pool.
        @endif
      </p>
      <div class="portal-form-grid">
        <div class="form-group portal-form-group portal-form-group-full">
          <label for="matchesname">Competition Title</label>
          <input type="text" class="form-control" id="matchesname" name="matchesname" value="{{ old('matchesname', $contest->contesttitile ?? '') }}" maxlength="150" placeholder="Competition Title" required>
        </div>
        <div class="form-group portal-form-group">
          <label for="contesttypeview">Exam Type</label>
          <input type="text" class="form-control" id="contesttypeview" value="{{ $contestTypeLabel }}" readonly>
        </div>
        <div class="form-group portal-form-group">
          <label for="totalseat">Total Seats</label>
          <input type="number" min="1" class="form-control" id="totalseat" name="totalseat" value="{{ old('totalseat', $contest->contestseat ?? '') }}" placeholder="Total seats" required>
        </div>
        <div class="form-group portal-form-group">
          <label for="userenrery">Per User Entries</label>
          <input type="number" min="1" max="99" class="form-control" id="userenrery" name="userenrery" value="{{ old('userenrery', $contest->userentery ?? 1) }}" placeholder="Per user entries" required>
        </div>
        <div class="form-group portal-form-group">
          <label for="prizetottalamount">Total Prize Amount</label>
          <input type="number" step="0.01" min="0" class="form-control" id="prizetottalamount" name="prizetottalamount" value="{{ old('prizetottalamount', $contest->totalamount ?? '') }}" placeholder="Total prize amount" required>
        </div>
        <div class="form-group portal-form-group">
          <label for="joinprice">Join Amount</label>
          <input type="number" step="0.01" min="0" class="form-control" id="joinprice" name="joinprice" value="{{ old('joinprice', $contest->joinamt ?? ($isFreeModule ? 0 : '')) }}" placeholder="Join amount" @if($isFreeModule) readonly @endif required>
          @if($isFreeModule)
            <small class="portal-form-hint">Free exam ke liye entry amount hamesha `0` rahega, lekin student page par visible rahega.</small>
          @endif
        </div>
        <div class="form-group portal-form-group">
          <label for="winpertantage">Winning Percentage</label>
          <input type="number" min="0" max="100" step="0.01" class="form-control" id="winpertantage" name="winpertantage" value="{{ old('winpertantage', $contest->winpertange ?? '') }}" placeholder="Winning percentage" required>
          <small class="portal-form-hint">Use this as your overall winning percentage reference for the competition.</small>
        </div>
        @if($isFreeModule)
          <div class="form-group portal-form-group portal-form-group-full">
            <div class="student-list-note">
              <strong>Free exam scholarship rule:</strong> har exam date par har class se overall top 3 students shortlist honge, aur final shortlisted pool me se top 10 scholarship winners choose honge.
            </div>
          </div>
        @endif
      </div>
    </div>

    <div class="portal-form-section">
      <h6>Reward Distribution</h6>
      <p>
        @if($isFreeModule)
          Free exam ke reward rows student exam page par show honge. Final scholarship logic alag daily shortlist rule se chalega.
        @else
          Create rank-wise reward slabs. Validation now checks overlapping or invalid seat ranges before saving.
        @endif
      </p>
      <div class="portal-rank-builder">
        <div class="portal-rank-builder-head">
          <strong>Prize Rows</strong>
          <button type="button" class="btn btn-info btn-sm" id="addContestPrizeRow">Add Reward Row</button>
        </div>

        <div class="portal-rank-list" id="contestPrizeRows">
          @foreach($prizeRows as $rowIndex => $row)
            <div class="portal-rank-row" data-rank-row>
              <div class="form-group portal-form-group">
                <label>Prize Amount</label>
                <input type="number" step="0.01" min="0" class="form-control" name="prizedetail[]" value="{{ $row['amount'] }}" placeholder="Prize amount" required>
              </div>
              <div class="form-group portal-form-group">
                <label>Seat Start</label>
                <input type="number" min="1" class="form-control" name="prizestratseat[]" value="{{ $row['start'] }}" placeholder="Start seat" required>
              </div>
              <div class="form-group portal-form-group">
                <label>Seat End</label>
                <input type="number" min="1" class="form-control" name="prizeendseat[]" value="{{ $row['end'] }}" placeholder="End seat" required>
              </div>
              <div class="portal-rank-remove">
                <button type="button" class="btn btn-outline-danger btn-sm" data-role="remove-prize-row">Remove</button>
              </div>
            </div>
          @endforeach
        </div>

        <template id="contestPrizeRowTemplate">
          <div class="portal-rank-row" data-rank-row>
            <div class="form-group portal-form-group">
              <label>Prize Amount</label>
              <input type="number" step="0.01" min="0" class="form-control" name="prizedetail[]" value="" placeholder="Prize amount" required>
            </div>
            <div class="form-group portal-form-group">
              <label>Seat Start</label>
              <input type="number" min="1" class="form-control" name="prizestratseat[]" value="" placeholder="Start seat" required>
            </div>
            <div class="form-group portal-form-group">
              <label>Seat End</label>
              <input type="number" min="1" class="form-control" name="prizeendseat[]" value="" placeholder="End seat" required>
            </div>
            <div class="portal-rank-remove">
              <button type="button" class="btn btn-outline-danger btn-sm" data-role="remove-prize-row">Remove</button>
            </div>
          </div>
        </template>
      </div>
    </div>

    <div class="portal-form-actions">
      <p class="portal-security-note">
        @if($isFreeModule)
          Free exam data is saved separately from paid competitions. Reward rows student side par visible rahenge, aur scholarship distribution daily class-wise shortlist rule se chalega.
        @else
          Competition data is saved only after field-level and reward-range validation passes.
        @endif
      </p>
      <button type="submit" class="btn btn-primary">{{ $submitLabel }}</button>
    </div>
  </form>
</div>

@push('scripts')
  <script>
    (function () {
      var rowsContainer = document.getElementById('contestPrizeRows');
      var template = document.getElementById('contestPrizeRowTemplate');
      var addButton = document.getElementById('addContestPrizeRow');

      if (!rowsContainer || !template || !addButton) {
        return;
      }

      var syncRemoveButtons = function () {
        var rows = rowsContainer.querySelectorAll('[data-rank-row]');
        rows.forEach(function (row) {
          var button = row.querySelector('[data-role="remove-prize-row"]');
          if (!button) {
            return;
          }

          button.disabled = rows.length === 1;
          button.classList.toggle('disabled', rows.length === 1);
        });
      };

      addButton.addEventListener('click', function () {
        rowsContainer.appendChild(template.content.cloneNode(true));
        syncRemoveButtons();
      });

      rowsContainer.addEventListener('click', function (event) {
        var removeButton = event.target.closest('[data-role="remove-prize-row"]');
        if (!removeButton) {
          return;
        }

        event.preventDefault();

        var rows = rowsContainer.querySelectorAll('[data-rank-row]');
        var currentRow = removeButton.closest('[data-rank-row]');

        if (!currentRow) {
          return;
        }

        if (rows.length === 1) {
          currentRow.querySelectorAll('input').forEach(function (input) {
            input.value = '';
          });
          return;
        }

        currentRow.remove();
        syncRemoveButtons();
      });

      syncRemoveButtons();
    })();
  </script>
@endpush
