@extends('layout.admin')

@section('title', 'Typing Settings')

@section('content')
@php
  $fieldMap = collect($definitions)->mapWithKeys(fn ($definition) => [(string) $definition['field'] => $definition]);
  $fieldValueMap = collect($definitions)->mapWithKeys(
      fn ($definition, $key) => [(string) $definition['field'] => (string) ($values[$key] ?? ($definition['default'] ?? ''))]
  );
@endphp

<div class="min-h-screen bg-slate-50">
  <div class="mx-auto max-w-6xl px-3 sm:px-4 py-4 sm:py-6">
    <div class="mb-5 flex items-start justify-between gap-3 flex-wrap">
      <div>
        <h1 class="text-xl sm:text-2xl font-extrabold text-slate-900 leading-tight">Typing Settings</h1>
        <p class="mt-1 text-xs sm:text-sm font-semibold text-slate-500">
          Task count, reward amount, number range, operator mode, user page-এর সব copy এখান থেকে edit করতে পারবেন।
        </p>
      </div>

      <div class="flex flex-wrap gap-2">
        @if($canViewHistory)
          <a href="{{ route('admin.typing-job.index') }}"
             class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-extrabold text-slate-700 hover:bg-slate-50">
            <i class="fa-solid fa-clock-rotate-left"></i>
            <span>Typing History</span>
          </a>
        @endif
        <a href="{{ route('admin.dashboard') }}"
           class="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-extrabold text-slate-700 hover:bg-slate-50">
          <i class="fa-solid fa-arrow-left"></i>
          <span>Dashboard</span>
        </a>
      </div>
    </div>

    @if(session('success'))
      <div class="mb-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-emerald-700 font-bold">
        {{ session('success') }}
      </div>
    @endif

    @if($errors->any())
      <div class="mb-4 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-rose-700">
        <div class="font-extrabold mb-2">Fix these fields:</div>
        <ul class="list-disc ps-5 text-sm font-semibold space-y-1">
          @foreach($errors->all() as $error)
            <li>{{ $error }}</li>
          @endforeach
        </ul>
      </div>
    @endif

    <div class="grid grid-cols-1 xl:grid-cols-[minmax(0,1.35fr)_360px] gap-5">
      <form method="POST" action="{{ route('admin.typing-job.settings.update') }}" class="space-y-5">
        @csrf

        <div class="rounded-2xl bg-white border border-slate-200 shadow-[0_14px_30px_rgba(2,6,23,0.08)] overflow-hidden">
          <div class="px-4 sm:px-6 py-4 border-b border-slate-100 bg-gradient-to-r from-sky-600 to-cyan-600">
            <div class="flex items-center gap-3">
              <div class="h-10 w-10 rounded-xl bg-white/15 grid place-items-center">
                <i class="fa-solid fa-sliders text-white"></i>
              </div>
              <div>
                <div class="text-white font-extrabold text-base sm:text-lg leading-tight">Task Rules</div>
                <div class="text-white/90 text-xs font-semibold">Reward, quota, operator mode, number range</div>
              </div>
            </div>
          </div>

          <div class="px-4 sm:px-6 py-5 grid grid-cols-1 md:grid-cols-2 gap-4">
            @foreach(['typing_job_tasks_per_verified_referral', 'typing_job_task_reward', 'typing_job_launch_starts_at', 'typing_job_operator_mode', 'typing_job_left_operand_min', 'typing_job_left_operand_max', 'typing_job_right_operand_min', 'typing_job_right_operand_max'] as $field)
              @php
                $definition = $fieldMap[$field];
                $currentValue = old($field, $fieldValueMap[$field] ?? ($definition['default'] ?? ''));
              @endphp
              <div>
                <label class="block text-xs font-extrabold text-slate-700 mb-1">{{ $definition['label'] }}</label>
                @if(($definition['type'] ?? 'text') === 'select')
                  <select
                    name="{{ $field }}"
                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-bold text-slate-900 outline-none focus:border-sky-500 focus:ring-4 focus:ring-sky-100"
                  >
                    @foreach($operatorOptions as $optionValue => $optionLabel)
                      <option value="{{ $optionValue }}" @selected($currentValue === $optionValue)>{{ $optionLabel }}</option>
                    @endforeach
                  </select>
                @else
                  <input
                    type="{{ in_array(($definition['type'] ?? 'text'), ['number', 'datetime-local'], true) ? ($definition['type'] ?? 'text') : 'text' }}"
                    name="{{ $field }}"
                    value="{{ $currentValue }}"
                    step="{{ $definition['step'] ?? 'any' }}"
                    min="{{ $definition['min'] ?? '' }}"
                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-bold text-slate-900 outline-none focus:border-sky-500 focus:ring-4 focus:ring-sky-100"
                  />
                @endif
                <div class="mt-1 text-[11px] font-semibold text-slate-500">{{ $definition['help'] ?? '' }}</div>
              </div>
            @endforeach
          </div>
        </div>

        <div class="rounded-2xl bg-white border border-slate-200 shadow-[0_14px_30px_rgba(2,6,23,0.08)] overflow-hidden">
          <div class="px-4 sm:px-6 py-4 border-b border-slate-100 bg-gradient-to-r from-slate-900 to-slate-700">
            <div class="flex items-center gap-3">
              <div class="h-10 w-10 rounded-xl bg-white/10 grid place-items-center">
                <i class="fa-solid fa-pen-to-square text-white"></i>
              </div>
              <div>
                <div class="text-white font-extrabold text-base sm:text-lg leading-tight">Main Page Copy</div>
                <div class="text-white/90 text-xs font-semibold">Hero, income card, task panel, input and history card</div>
              </div>
            </div>
          </div>

          <div class="px-4 sm:px-6 py-5 grid grid-cols-1 gap-4">
            @foreach(['typing_job_page_title', 'typing_job_page_summary', 'typing_job_income_title', 'typing_job_income_note', 'typing_job_task_panel_title', 'typing_job_task_panel_summary', 'typing_job_answer_label', 'typing_job_answer_placeholder', 'typing_job_submit_button_label', 'typing_job_history_card_title', 'typing_job_history_card_summary', 'typing_job_history_link_label'] as $field)
              @php
                $definition = $fieldMap[$field];
                $currentValue = old($field, $fieldValueMap[$field] ?? ($definition['default'] ?? ''));
              @endphp
              <div>
                <label class="block text-xs font-extrabold text-slate-700 mb-1">{{ $definition['label'] }}</label>
                @if(($definition['type'] ?? 'text') === 'textarea')
                  <textarea
                    name="{{ $field }}"
                    rows="3"
                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-bold text-slate-900 outline-none focus:border-sky-500 focus:ring-4 focus:ring-sky-100"
                  >{{ $currentValue }}</textarea>
                @else
                  <input
                    type="text"
                    name="{{ $field }}"
                    value="{{ $currentValue }}"
                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-bold text-slate-900 outline-none focus:border-sky-500 focus:ring-4 focus:ring-sky-100"
                  />
                @endif
                <div class="mt-1 text-[11px] font-semibold text-slate-500">{{ $definition['help'] ?? '' }}</div>
              </div>
            @endforeach
          </div>
        </div>

        <div class="rounded-2xl bg-white border border-slate-200 shadow-[0_14px_30px_rgba(2,6,23,0.08)] overflow-hidden">
          <div class="px-4 sm:px-6 py-4 border-b border-slate-100 bg-gradient-to-r from-emerald-600 to-teal-600">
            <div class="flex items-center gap-3">
              <div class="h-10 w-10 rounded-xl bg-white/15 grid place-items-center">
                <i class="fa-solid fa-table-list text-white"></i>
              </div>
              <div>
                <div class="text-white font-extrabold text-base sm:text-lg leading-tight">History & State Copy</div>
                <div class="text-white/90 text-xs font-semibold">History page এবং empty / complete / pending state message</div>
              </div>
            </div>
          </div>

          <div class="px-4 sm:px-6 py-5 grid grid-cols-1 gap-4">
            @foreach(['typing_job_history_page_title', 'typing_job_history_page_summary', 'typing_job_history_back_label', 'typing_job_history_empty_text', 'typing_job_state_table_not_ready_title', 'typing_job_state_table_not_ready_copy', 'typing_job_state_no_referral_title', 'typing_job_state_no_referral_copy', 'typing_job_state_complete_title', 'typing_job_state_complete_copy'] as $field)
              @php
                $definition = $fieldMap[$field];
                $currentValue = old($field, $fieldValueMap[$field] ?? ($definition['default'] ?? ''));
              @endphp
              <div>
                <label class="block text-xs font-extrabold text-slate-700 mb-1">{{ $definition['label'] }}</label>
                @if(($definition['type'] ?? 'text') === 'textarea')
                  <textarea
                    name="{{ $field }}"
                    rows="3"
                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-bold text-slate-900 outline-none focus:border-sky-500 focus:ring-4 focus:ring-sky-100"
                  >{{ $currentValue }}</textarea>
                @else
                  <input
                    type="text"
                    name="{{ $field }}"
                    value="{{ $currentValue }}"
                    class="w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-sm font-bold text-slate-900 outline-none focus:border-sky-500 focus:ring-4 focus:ring-sky-100"
                  />
                @endif
                <div class="mt-1 text-[11px] font-semibold text-slate-500">{{ $definition['help'] ?? '' }}</div>
              </div>
            @endforeach
          </div>
        </div>

        <div class="flex flex-col sm:flex-row gap-3">
          <button type="submit"
                  class="w-full sm:w-auto flex-1 rounded-xl bg-sky-600 px-5 py-3 text-white font-extrabold shadow-[0_14px_26px_rgba(2,132,199,0.22)] hover:bg-sky-700 active:scale-[0.99] transition">
            <i class="fa-solid fa-floppy-disk mr-2"></i> Save Typing Settings
          </button>
          @if($canViewHistory)
            <a href="{{ route('admin.typing-job.index') }}"
               class="w-full sm:w-auto flex-1 rounded-xl border border-slate-200 bg-white px-5 py-3 text-slate-700 font-extrabold hover:bg-slate-50 active:scale-[0.99] transition text-center">
              <i class="fa-solid fa-clock-rotate-left mr-2"></i> Open History
            </a>
          @endif
        </div>
      </form>

      <div class="space-y-5">
        <div class="rounded-2xl border border-slate-200 bg-white p-5 shadow-[0_14px_30px_rgba(2,6,23,0.08)]">
          <div class="text-sm font-extrabold text-slate-900">Live Mechanics</div>
          <div class="mt-4 rounded-2xl bg-gradient-to-br from-sky-600 to-cyan-600 p-5 text-white">
            <div class="text-xs font-extrabold uppercase tracking-[0.18em] text-white/80">Current Reward</div>
            <div class="mt-2 text-3xl font-black">৳{{ number_format((float) ($mechanics['task_reward'] ?? 0), 2) }}</div>
            <div class="mt-3 text-sm font-bold text-white/90">
              প্রতি verified referral-এ {{ (int) ($mechanics['tasks_per_verified_referral'] ?? 0) }}টি task unlock
            </div>
          </div>

          <div class="mt-4 grid grid-cols-1 gap-3">
            <div class="rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div class="text-xs font-extrabold text-slate-700">Operator Mode</div>
              <div class="mt-2 text-xl font-black text-slate-900">{{ $mechanics['operator_label'] ?? '—' }}</div>
              <div class="mt-1 text-xs font-semibold text-slate-500">
                Range: {{ $mechanics['left_operand_min'] ?? 0 }}-{{ $mechanics['left_operand_max'] ?? 0 }}
                / {{ $mechanics['right_operand_min'] ?? 0 }}-{{ $mechanics['right_operand_max'] ?? 0 }}
              </div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div class="text-xs font-extrabold text-slate-700">Launch Count From</div>
              <div class="mt-2 text-lg font-black text-slate-900">
                {{ $mechanics['launch_starts_at']?->format('d M Y, h:i A') ?? '—' }}
              </div>
              <div class="mt-1 text-xs font-semibold text-slate-500">
                এই সময়ের আগের verified referral আর task unlock করবে না।
              </div>
            </div>
            <div class="grid grid-cols-3 gap-3">
              <div class="rounded-xl border border-emerald-100 bg-emerald-50 p-4">
                <div class="text-xs font-extrabold text-emerald-700">Tasks</div>
                <div class="mt-2 text-xl font-black text-slate-900">{{ number_format((int) ($summary['total_tasks'] ?? 0)) }}</div>
              </div>
              <div class="rounded-xl border border-sky-100 bg-sky-50 p-4">
                <div class="text-xs font-extrabold text-sky-700">Members</div>
                <div class="mt-2 text-xl font-black text-slate-900">{{ number_format((int) ($summary['total_members'] ?? 0)) }}</div>
              </div>
              <div class="rounded-xl border border-amber-100 bg-amber-50 p-4">
                <div class="text-xs font-extrabold text-amber-700">Earned</div>
                <div class="mt-2 text-xl font-black text-slate-900">৳{{ number_format((float) ($summary['total_earned'] ?? 0), 2) }}</div>
              </div>
            </div>
          </div>

          <div class="mt-4 space-y-3">
            <div class="rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div class="text-xs font-extrabold text-slate-700">Resolved Page Title</div>
              <div class="mt-2 text-sm font-extrabold text-slate-900">{{ $contentPreview['page_title'] ?? '' }}</div>
              <div class="mt-2 text-xs font-semibold text-slate-500">{{ $contentPreview['page_summary'] ?? '' }}</div>
            </div>
            <div class="rounded-xl border border-slate-200 bg-slate-50 p-4">
              <div class="text-xs font-extrabold text-slate-700">Available Tokens</div>
              <div class="mt-2 text-xs font-semibold text-slate-600 leading-6">
                <code>:tasks_per_referral</code>,
                <code>:reward</code>,
                <code>:launch_at</code>,
                <code>:earned</code>,
                <code>:completed</code>,
                <code>:remaining</code>,
                <code>:verified_referrals</code>,
                <code>:total_unlocked</code>,
                <code>:task_quota</code>,
                <code>:operator_label</code>
              </div>
            </div>
            <div class="rounded-xl border {{ $tableAvailable ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : 'border-amber-200 bg-amber-50 text-amber-800' }} p-4 text-sm font-bold">
              @if($tableAvailable)
                `typing_job_submissions` table ready আছে। Save করলে live user page-এ সাথে সাথে reflect হবে।
              @else
                `typing_job_submissions` table ready না থাকলেও copy/settings save হবে। History submit চালু করতে migration ready লাগবে।
              @endif
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection
