@extends('layouts.user')

@section('title', __('user_profile.edit_profile_title'))

@section('content')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.css"/>

@php
  $photoUrl = $user->photo
      ? asset($user->photo)
      : 'https://ui-avatars.com/api/?name='.urlencode($user->name).'&background=E2E8F0&color=0F172A';
@endphp

<div class="w-full px-1 sm:px-2 lg:px-3 space-y-4">

  <div class="mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
    <div>
      <div class="inline-flex items-center gap-2 border border-blue-100 bg-blue-50 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-blue-700">
        <span>👤</span>
        <span>{{ __('user_profile.profile_settings') }}</span>
      </div>
      <h1 class="mt-3 text-base font-bold tracking-tight text-slate-900">
        {{ __('user_profile.edit_profile_title') }}
      </h1>
      <p class="mt-1 text-xs text-slate-500">
        {{ __('user_profile.edit_profile_subtitle') }}
      </p>
    </div>

    <div class="flex flex-wrap gap-2">
      <a href="{{ route('user.profile.show') }}"
         class="inline-flex items-center justify-center border border-slate-300 bg-white px-4 py-2 text-xs font-semibold text-slate-700 shadow-sm transition hover:bg-slate-50">
        {{ __('user_profile.back_to_profile') }}
      </a>
    </div>
  </div>

  @if($errors->any())
    <div class="mb-4 border border-rose-200 bg-rose-50 px-4 py-3 text-xs text-rose-800 shadow-sm">
      <div class="flex items-start gap-3">
        <span class="text-sm">⚠️</span>
        <div>
          <div class="font-semibold">{{ __('user_profile.fix_following_issues') }}</div>
          <ul class="mt-2 list-disc pl-5 space-y-1">
            @foreach($errors->all() as $e)
              <li>{{ $e }}</li>
            @endforeach
          </ul>
        </div>
      </div>
    </div>
  @endif

  <form method="POST" action="{{ route('user.profile.update') }}" enctype="multipart/form-data">
    @csrf

    <div class="grid gap-4 lg:grid-cols-3">

      <div class="lg:col-span-1">
        <div class="overflow-hidden border border-slate-200 bg-slate-900 text-white shadow-sm">
          <div class="p-4">
            <div class="flex h-11 w-11 items-center justify-center border border-white/10 bg-white/5 text-lg">
              ✨
            </div>

            <h2 class="mt-4 text-sm font-bold">{{ __('user_profile.profile_overview') }}</h2>
            <p class="mt-1.5 text-xs leading-5 text-slate-300">
              {{ __('user_profile.edit_profile_overview_text') }}
            </p>

            <div class="mt-4 flex items-center gap-3 border border-white/10 bg-white/5 p-3">
              <div class="h-14 w-14 overflow-hidden border border-white/10 bg-white/10">
                <img id="avatarPreview"
                     src="{{ $photoUrl }}"
                     class="h-full w-full object-cover"
                     alt="{{ __('user_profile.profile_photo_alt') }}">
              </div>

              <div class="min-w-0">
                <div class="truncate text-sm font-bold">{{ $user->name }}</div>
                <div class="truncate text-[11px] text-slate-300">{{ $user->email }}</div>
              </div>
            </div>

            <div class="mt-4 space-y-2">
              <div class="border border-white/10 bg-white/5 p-3">
                <div class="text-xs font-semibold">{{ __('user_profile.username_locked') }}</div>
                <div class="mt-1 text-[11px] leading-5 text-slate-300">
                  {{ __('user_profile.username_locked_edit_text') }}
                </div>
              </div>

              <div class="border border-white/10 bg-white/5 p-3">
                <div class="text-xs font-semibold">{{ __('user_profile.photo_upload') }}</div>
                <div class="mt-1 text-[11px] leading-5 text-slate-300">
                  {{ __('user_profile.photo_upload_text') }}
                </div>
              </div>

              <div class="border border-white/10 bg-white/5 p-3">
                <div class="text-xs font-semibold">{{ __('user_profile.keep_it_updated') }}</div>
                <div class="mt-1 text-[11px] leading-5 text-slate-300">
                  {{ __('user_profile.keep_it_updated_text') }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="lg:col-span-2">
        <div class="overflow-hidden border border-slate-200 bg-white shadow-sm">
          <div class="border-b border-slate-200 bg-slate-50 px-4 py-4">
            <h2 class="text-sm font-bold text-slate-900">{{ __('user_profile.basic_information') }}</h2>
            <p class="mt-1 text-xs text-slate-500">
              {{ __('user_profile.basic_information_text') }}
            </p>
          </div>

          <div class="p-4">

            <div class="mb-4 border border-slate-200 bg-slate-50 p-4">
              <div class="flex flex-col gap-4 md:flex-row md:items-center">
                <div class="relative shrink-0">
                  <img id="avatarPreviewTop"
                       src="{{ $photoUrl }}"
                       class="h-24 w-24 border border-slate-200 bg-white object-cover shadow-sm"
                       alt="{{ __('user_profile.profile_photo_alt') }}">

                  <button type="button" id="openPickerBtn"
                          class="absolute -bottom-1 -right-1 flex h-9 w-9 items-center justify-center border-2 border-white bg-slate-900 text-white shadow-sm transition hover:bg-slate-800"
                          title="{{ __('user_profile.upload_photo') }}">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                      <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                      <circle cx="12" cy="13" r="4"/>
                    </svg>
                  </button>
                </div>

                <div class="min-w-0 flex-1">
                  <div class="text-sm font-bold text-slate-900">{{ __('user_profile.profile_photo') }}</div>
                  <div class="mt-1 text-xs text-slate-500">
                    {{ __('user_profile.profile_photo_text') }}
                  </div>
                  <div class="mt-3 inline-flex items-center border border-slate-200 bg-white px-3 py-2 text-[11px] font-medium text-slate-600">
                    {{ __('user_profile.supported_formats') }}
                  </div>

                  <input id="photoInput" type="file" name="photo" accept="image/*" class="hidden">
                  <input id="photoBase64" type="hidden" name="photo_base64" value="">
                </div>
              </div>
            </div>

            <div class="grid gap-4 md:grid-cols-2">
              <div>
                <label class="mb-1.5 block text-xs font-semibold text-slate-700">{{ __('user_profile.uid') }}</label>
                <input value="{{ $user->uid }}" disabled
                       class="w-full border border-slate-300 bg-slate-50 px-3 py-2.5 text-xs text-slate-600 shadow-sm">
              </div>

              <div>
                <label class="mb-1.5 block text-xs font-semibold text-slate-700">{{ __('user_profile.username_fixed') }}</label>
                <input value="{{ $user->username }}" disabled
                       class="w-full border border-slate-300 bg-slate-50 px-3 py-2.5 text-xs text-slate-600 shadow-sm">
              </div>

              <div>
                <label class="mb-1.5 block text-xs font-semibold text-slate-700">{{ __('user_profile.full_name') }}</label>
                <input name="name"
                       value="{{ old('name', $user->name) }}"
                       required
                       class="w-full border border-slate-300 bg-white px-3 py-2.5 text-xs text-slate-800 shadow-sm outline-none transition hover:border-slate-400 focus:border-slate-900 focus:ring-0">
              </div>

              <div>
                <label class="mb-1.5 block text-xs font-semibold text-slate-700">{{ __('user_profile.phone_number') }}</label>
                <input name="phone"
                       value="{{ old('phone', $user->phone) }}"
                       required
                       class="w-full border border-slate-300 bg-white px-3 py-2.5 text-xs text-slate-800 shadow-sm outline-none transition hover:border-slate-400 focus:border-slate-900 focus:ring-0">
              </div>

              <div class="md:col-span-2">
                <label class="mb-1.5 block text-xs font-semibold text-slate-700">{{ __('user_profile.email_address') }}</label>
                <input name="email"
                       type="email"
                       value="{{ old('email', $user->email) }}"
                       required
                       class="w-full border border-slate-300 bg-white px-3 py-2.5 text-xs text-slate-800 shadow-sm outline-none transition hover:border-slate-400 focus:border-slate-900 focus:ring-0">
              </div>
            </div>

            <div class="mt-6 flex flex-col gap-2 sm:flex-row">
              <button type="submit"
                      class="inline-flex items-center justify-center bg-slate-900 px-5 py-2.5 text-xs font-semibold text-white shadow-sm transition hover:bg-slate-800">
                {{ __('user_profile.save_changes') }}
              </button>

              <a href="{{ route('user.profile.show') }}"
                 class="inline-flex items-center justify-center border border-slate-300 bg-white px-5 py-2.5 text-xs font-semibold text-slate-700 transition hover:bg-slate-50">
                {{ __('user_profile.cancel') }}
              </a>
            </div>

          </div>
        </div>
      </div>

    </div>
  </form>
</div>

<div id="cropModal" class="fixed inset-0 hidden z-50">
  <div class="absolute inset-0 bg-slate-950/60"></div>

  <div class="relative mx-auto mt-6 max-w-4xl overflow-hidden border border-slate-200 bg-white shadow-2xl">
    <div class="flex items-center justify-between border-b border-slate-200 px-4 py-3">
      <div>
        <div class="text-sm font-bold text-slate-900">{{ __('user_profile.crop_profile_photo') }}</div>
        <div class="text-xs text-slate-500">{{ __('user_profile.crop_profile_photo_text') }}</div>
      </div>

      <button id="closeModalBtn"
              type="button"
              class="grid h-9 w-9 place-items-center border border-slate-300 bg-white text-slate-600 hover:bg-slate-50">
        ✕
      </button>
    </div>

    <div class="p-4">
      <div class="grid gap-4 lg:grid-cols-[1fr_240px]">
        <div>
          <div class="relative overflow-hidden border border-slate-200 bg-slate-50">
            <img id="imageToCrop" src="" alt="{{ __('user_profile.to_crop_alt') }}" class="max-w-full">
            <div class="absolute left-1/2 top-3 -translate-x-1/2 border border-white/10 bg-slate-900/80 px-3 py-1 text-[10px] font-medium text-white">
              {{ __('user_profile.drag_to_reposition') }}
            </div>
          </div>

          <div class="mt-4 flex items-center gap-3">
            <button id="zoomOut" type="button" class="grid h-9 w-9 place-items-center border border-slate-300 bg-white text-base hover:bg-slate-50">−</button>
            <input id="zoomRange" type="range" min="0" max="100" value="20" class="w-full">
            <button id="zoomIn" type="button" class="grid h-9 w-9 place-items-center border border-slate-300 bg-white text-base hover:bg-slate-50">+</button>
          </div>
        </div>

        <div class="border border-slate-200 bg-slate-50 p-4">
          <div class="text-xs font-bold text-slate-900">{{ __('user_profile.preview') }}</div>
          <p class="mt-1 text-[11px] leading-5 text-slate-500">
            {{ __('user_profile.preview_text') }}
          </p>

          <div class="mt-4 flex justify-center">
            <div class="h-20 w-20 overflow-hidden border border-slate-200 bg-white shadow-sm">
              <img id="circlePreview" src="" class="h-full w-full object-cover" alt="{{ __('user_profile.preview_alt') }}">
            </div>
          </div>

          <div class="mt-5 space-y-2">
            <button id="cropBtn" type="button"
                    class="inline-flex w-full items-center justify-center border border-slate-300 bg-white px-4 py-2.5 text-xs font-semibold text-slate-700 hover:bg-slate-50">
              {{ __('user_profile.crop_preview') }}
            </button>

            <button id="saveCropBtn" type="button"
                    class="inline-flex w-full items-center justify-center bg-blue-600 px-4 py-2.5 text-xs font-semibold text-white shadow-sm hover:bg-blue-700">
              {{ __('user_profile.save_photo') }}
            </button>

            <button id="cancelCropBtn" type="button"
                    class="inline-flex w-full items-center justify-center border border-slate-300 bg-white px-4 py-2.5 text-xs font-semibold text-slate-700 hover:bg-slate-50">
              {{ __('user_profile.cancel') }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="discardModal" class="fixed inset-0 hidden z-[60]">
  <div class="absolute inset-0 bg-slate-950/50"></div>
  <div class="relative mx-auto mt-28 max-w-lg overflow-hidden border border-slate-200 bg-white shadow-2xl">
    <div class="flex items-center justify-between border-b border-slate-200 px-4 py-3">
      <div class="text-sm font-bold text-slate-900">{{ __('user_profile.discard_changes') }}</div>
      <button id="discardCloseX" type="button" class="grid h-9 w-9 place-items-center border border-slate-300 bg-white text-slate-600 hover:bg-slate-50">✕</button>
    </div>
    <div class="p-4 text-xs text-slate-700">
      {{ __('user_profile.discard_changes_text') }}
      <div class="mt-5 flex justify-end gap-2">
        <button id="discardCancel" type="button" class="border border-slate-300 bg-white px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50">
          {{ __('user_profile.cancel') }}
        </button>
        <button id="discardOk" type="button" class="bg-blue-600 px-4 py-2 text-xs font-semibold text-white hover:bg-blue-700">
          {{ __('user_profile.discard') }}
        </button>
      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.2/cropper.min.js"></script>
<script>
(function () {
  const photoInput = document.getElementById('photoInput');
  const openPickerBtn = document.getElementById('openPickerBtn');
  const cropModal = document.getElementById('cropModal');
  const discardModal = document.getElementById('discardModal');

  const imageToCrop = document.getElementById('imageToCrop');
  const avatarPreview = document.getElementById('avatarPreview');
  const avatarPreviewTop = document.getElementById('avatarPreviewTop');
  const circlePreview = document.getElementById('circlePreview');
  const photoBase64 = document.getElementById('photoBase64');

  const closeModalBtn = document.getElementById('closeModalBtn');
  const cancelCropBtn = document.getElementById('cancelCropBtn');

  const cropBtn = document.getElementById('cropBtn');
  const saveCropBtn = document.getElementById('saveCropBtn');

  const zoomRange = document.getElementById('zoomRange');
  const zoomIn = document.getElementById('zoomIn');
  const zoomOut = document.getElementById('zoomOut');

  const discardOk = document.getElementById('discardOk');
  const discardCancel = document.getElementById('discardCancel');
  const discardCloseX = document.getElementById('discardCloseX');

  let cropper = null;
  let currentObjectUrl = null;
  let hasUnsavedCrop = false;

  function openCropModal() {
    cropModal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
  }

  function closeCropModal() {
    cropModal.classList.add('hidden');
    document.body.style.overflow = '';
  }

  function openDiscardModal() {
    discardModal.classList.remove('hidden');
  }

  function closeDiscardModal() {
    discardModal.classList.add('hidden');
  }

  openPickerBtn?.addEventListener('click', () => photoInput.click());

  photoInput?.addEventListener('change', () => {
    const file = photoInput.files?.[0];
    if (!file) return;

    if (currentObjectUrl) URL.revokeObjectURL(currentObjectUrl);
    currentObjectUrl = URL.createObjectURL(file);

    imageToCrop.src = currentObjectUrl;
    circlePreview.src = currentObjectUrl;
    photoBase64.value = "";
    hasUnsavedCrop = true;

    openCropModal();

    imageToCrop.onload = () => {
      if (cropper) cropper.destroy();

      cropper = new Cropper(imageToCrop, {
        viewMode: 1,
        dragMode: 'move',
        aspectRatio: 1,
        autoCropArea: 1,
        background: false,
        guides: false,
        center: true,
        responsive: true,
        cropBoxMovable: false,
        cropBoxResizable: false,
        ready() {
          zoomRange.value = 20;
        },
        crop() {
          const canvas = cropper.getCroppedCanvas({ width: 200, height: 200 });
          circlePreview.src = canvas.toDataURL('image/png');
        }
      });
    };
  });

  function askDiscardOrClose() {
    if (hasUnsavedCrop) openDiscardModal();
    else closeCropModal();
  }

  closeModalBtn?.addEventListener('click', askDiscardOrClose);
  cancelCropBtn?.addEventListener('click', askDiscardOrClose);

  discardCancel?.addEventListener('click', closeDiscardModal);
  discardCloseX?.addEventListener('click', closeDiscardModal);

  discardOk?.addEventListener('click', () => {
    closeDiscardModal();
    closeCropModal();
    hasUnsavedCrop = false;
    photoInput.value = "";
    photoBase64.value = "";
    if (cropper) { cropper.destroy(); cropper = null; }
    if (currentObjectUrl) { URL.revokeObjectURL(currentObjectUrl); currentObjectUrl = null; }
  });

  function setZoomFromRange() {
    if (!cropper) return;
    const v = Number(zoomRange.value) || 0;
    const zoom = v / 100 * 1.5;
    cropper.zoomTo(1 + zoom);
  }

  zoomRange?.addEventListener('input', setZoomFromRange);

  zoomIn?.addEventListener('click', () => {
    zoomRange.value = Math.min(100, Number(zoomRange.value) + 5);
    setZoomFromRange();
  });

  zoomOut?.addEventListener('click', () => {
    zoomRange.value = Math.max(0, Number(zoomRange.value) - 5);
    setZoomFromRange();
  });

  cropBtn?.addEventListener('click', () => {
    if (!cropper) return;
    const canvas = cropper.getCroppedCanvas({ width: 600, height: 600 });
    circlePreview.src = canvas.toDataURL('image/png');
  });

  saveCropBtn?.addEventListener('click', () => {
    if (!cropper) return;
    const canvas = cropper.getCroppedCanvas({ width: 600, height: 600 });
    const dataUrl = canvas.toDataURL('image/png');

    avatarPreview.src = dataUrl;
    if (avatarPreviewTop) avatarPreviewTop.src = dataUrl;
    photoBase64.value = dataUrl;

    hasUnsavedCrop = false;
    closeCropModal();
  });
})();
</script>
@endsection