@php
  use Illuminate\Support\Facades\Route;
  use Illuminate\Support\Str;
  $registerUrl = Route::has('register') ? route('register') : url('auth/register-cover');
  $orgAccents = ['#f58220', '#602d91', '#15265c', '#0d9488', '#be185d', '#2563eb'];
@endphp

@extends('layouts/guest')

@section('title', 'Bacheca eventi')

@section('page-meta')
  <script>document.documentElement.classList.add('welcome-bacheca-page');</script>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,400;0,500;0,600;0,700;0,800;1,400&display=swap" rel="stylesheet" />
@endsection

@section('page-style')
  @vite(['resources/css/welcome.css'])
@endsection

@section('content')
  <div class="welcome-bacheca__bg" data-bg="soft" aria-hidden="true">
    <div class="welcome-bacheca__bg-stripe"></div>
  </div>

  <div class="welcome-bacheca">
    <header class="welcome-bacheca__masthead" aria-labelledby="bacheca-title">
      <div class="welcome-bacheca__masthead-row">
        <div class="welcome-bacheca__brand">
          <img
            src="{{ asset('assets/img/logo_fest_L.png') }}"
            alt="{{ config('app.name') }}"
            class="welcome-bacheca__logo"
            width="200"
            height="60"
          >
        </div>
        <div class="welcome-bacheca__masthead-actions">
          <a href="{{ route('login') }}" class="welcome-bacheca__btn welcome-bacheca__btn--ghost">
            Accedi
          </a>
        </div>
      </div>
      <h1 id="bacheca-title" class="welcome-bacheca__title">Bacheca eventi</h1>
    </header>

    @if($organizzazioni->isEmpty())
      <div class="welcome-bacheca__empty">
        <div class="welcome-bacheca__empty-icon">
          <i class="bx bx-calendar-event"></i>
        </div>
        <h2 class="welcome-bacheca__empty-title">Nessuna attività in bacheca</h2>
        <p class="welcome-bacheca__empty-text">Al momento non ci sono eventi pubblicati. Torna a trovarci presto.</p>
        <a href="{{ route('login') }}" class="welcome-bacheca__btn welcome-bacheca__btn--primary">
          Area operatore
        </a>
      </div>
    @else
      <section class="welcome-bacheca__board" aria-label="Organizzazioni e attività">
        @if($totaleAttivita > 3 || $organizzazioni->count() > 1)
          <label class="welcome-bacheca__search" for="welcomeBachecaSearch">
            <i class="bx bx-search" aria-hidden="true"></i>
            <input
              type="search"
              id="welcomeBachecaSearch"
              class="welcome-bacheca__search-input"
              placeholder="Cerca…"
              autocomplete="off"
            >
          </label>
        @endif

        @if($organizzazioni->count() > 1)
          <div class="welcome-bacheca__carousel" id="welcomeOrgCarousel" aria-roledescription="carousel" aria-label="Organizzazioni in programma">
            <button
              type="button"
              class="welcome-bacheca__carousel-nav welcome-bacheca__carousel-nav--prev"
              id="welcomeCarouselPrev"
              aria-label="Organizzazione precedente"
            >
              <i class="bx bx-chevron-left" aria-hidden="true"></i>
            </button>

            <div class="welcome-bacheca__carousel-viewport">
              <div class="welcome-bacheca__carousel-track" id="welcomeCarouselTrack">
                @foreach($organizzazioni as $orgIndex => $organizzazione)
                  @include('welcome._partials.org-slide', [
                    'organizzazione' => $organizzazione,
                    'orgIndex' => $orgIndex,
                    'orgAccents' => $orgAccents,
                    'isActive' => $orgIndex === 0,
                  ])
                @endforeach
              </div>
            </div>

            <button
              type="button"
              class="welcome-bacheca__carousel-nav welcome-bacheca__carousel-nav--next"
              id="welcomeCarouselNext"
              aria-label="Organizzazione successiva"
            >
              <i class="bx bx-chevron-right" aria-hidden="true"></i>
            </button>

            <div class="welcome-bacheca__carousel-dots" id="welcomeCarouselDots" role="tablist" aria-label="Seleziona organizzazione"></div>
          </div>
        @else
          @php $soloOrg = $organizzazioni->first(); @endphp
          <div class="welcome-bacheca__org-solo" style="--org-accent: {{ $soloOrg->attivita->first()?->colore ?: $orgAccents[0] }}">
            @include('welcome._partials.org-slide', [
              'organizzazione' => $soloOrg,
              'orgIndex' => 0,
              'orgAccents' => $orgAccents,
              'isActive' => true,
            ])
          </div>
        @endif

        <div class="welcome-bacheca__org-stage" id="welcomeOrgStage">
          <div class="welcome-bacheca__org-stage-body" id="welcomeOrgStageBody">
            @foreach($organizzazioni as $orgIndex => $organizzazione)
              @include('welcome._partials.org-panel', [
                'organizzazione' => $organizzazione,
                'orgIndex' => $orgIndex,
                'orgAccents' => $orgAccents,
                'isActive' => $orgIndex === 0,
              ])
            @endforeach
          </div>
        </div>

        <p class="welcome-bacheca__search-empty" id="welcomeBachecaSearchEmpty" hidden>
          Nessuna organizzazione o attività corrisponde alla ricerca.
        </p>
      </section>
    @endif

    <footer class="welcome-bacheca__footer">
      {{ config('app.name') }} · la bacheca digitale per feste e sagre
    </footer>
  </div>

  <div class="modal fade" id="welcomeAttivitaModal" tabindex="-1" aria-labelledby="welcomeAttivitaModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered welcome-bacheca__modal-dialog">
      <div class="modal-content welcome-bacheca__modal" id="welcomeModalShell">
        <div class="welcome-bacheca__modal-hero" id="welcomeModalHero" aria-hidden="true"></div>

        <div class="welcome-bacheca__modal-panel">
          <div class="welcome-bacheca__modal-header">
            <div class="welcome-bacheca__modal-head">
              <span class="welcome-bacheca__modal-media" id="welcomeModalMedia"></span>
              <div class="welcome-bacheca__modal-copy">
                <h5 class="welcome-bacheca__modal-title" id="welcomeAttivitaModalLabel"></h5>
                <p class="welcome-bacheca__modal-desc" id="welcomeModalDesc"></p>
              </div>
            </div>
            <button type="button" class="btn-close welcome-bacheca__modal-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
          </div>

          <div class="welcome-bacheca__modal-body">
            <p class="welcome-bacheca__modal-hint">Cosa vuoi fare?</p>
            <div class="welcome-bacheca__modal-actions">
              <a href="#" class="welcome-bacheca__action" id="welcomeActionSaltacoda" data-action="saltacoda" hidden>
                <span class="welcome-bacheca__action-icon welcome-bacheca__action-icon--orange">
                  <i class="bx bx-food-menu"></i>
                </span>
                <span>
                  <strong>Ordina (saltacoda)</strong>
                  <small>Menu e ordine dal telefono</small>
                </span>
              </a>
              <a href="#" class="welcome-bacheca__action" id="welcomeActionScheda" data-action="scheda">
                <span class="welcome-bacheca__action-icon welcome-bacheca__action-icon--purple">
                  <i class="bx bx-detail"></i>
                </span>
                <span>
                  <strong>Apri scheda</strong>
                  <small>Info, orari e dettagli dell’attività</small>
                </span>
              </a>
              <a href="{{ route('login') }}" class="welcome-bacheca__action" id="welcomeActionLogin" data-action="login">
                <span class="welcome-bacheca__action-icon welcome-bacheca__action-icon--navy">
                  <i class="bx bx-log-in"></i>
                </span>
                <span>
                  <strong>Area operatore</strong>
                  <small>Accedi per gestire l’attività</small>
                </span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
@endsection

@section('page-script')
<script>
(function () {
  const stageEl = document.getElementById('welcomeOrgStage');
  const carouselEl = document.getElementById('welcomeOrgCarousel');
  const trackEl = document.getElementById('welcomeCarouselTrack');
  const dotsEl = document.getElementById('welcomeCarouselDots');
  const prevBtn = document.getElementById('welcomeCarouselPrev');
  const nextBtn = document.getElementById('welcomeCarouselNext');
  const searchInput = document.getElementById('welcomeBachecaSearch');
  const searchEmpty = document.getElementById('welcomeBachecaSearchEmpty');

  const slides = Array.from(document.querySelectorAll('[data-org-slide]'));
  const panels = Array.from(document.querySelectorAll('[data-org-panel]'));
  let activeOrgId = panels.find(function (panel) { return !panel.hidden; })?.dataset.orgPanel || null;
  let carouselIndex = 0;

  function visibleSlides() {
    return slides.filter(function (slide) { return !slide.hidden; });
  }

  function slideByOrgId(orgId) {
    return slides.find(function (slide) { return slide.dataset.orgId === String(orgId); });
  }

  function panelByOrgId(orgId) {
    return panels.find(function (panel) { return panel.dataset.orgPanel === String(orgId); });
  }

  function updateStageHead(slide) {
    if (!slide || !stageEl) return;
    stageEl.style.setProperty('--org-accent', slide.dataset.orgAccent || '#f58220');
  }

  function renderDots() {
    if (!dotsEl) return;

    const items = visibleSlides();
    dotsEl.innerHTML = '';

    items.forEach(function (slide, index) {
      const dot = document.createElement('button');
      dot.type = 'button';
      dot.className = 'welcome-bacheca__carousel-dot' + (slide.dataset.orgId === String(activeOrgId) ? ' is-active' : '');
      dot.setAttribute('role', 'tab');
      dot.setAttribute('aria-label', slide.dataset.orgNome || 'Organizzazione');
      dot.setAttribute('aria-selected', slide.dataset.orgId === String(activeOrgId) ? 'true' : 'false');
      dot.addEventListener('click', function () {
        goToSlide(index);
      });
      dotsEl.appendChild(dot);
    });
  }

  function updateCarouselPosition() {
    if (!trackEl || !carouselEl) return;

    const items = visibleSlides();
    if (!items.length) return;

    if (carouselIndex >= items.length) {
      carouselIndex = 0;
    }

    const slide = items[carouselIndex];
    const offset = slide.offsetLeft - (carouselEl.querySelector('.welcome-bacheca__carousel-viewport').clientWidth - slide.clientWidth) / 2;

    trackEl.style.transform = 'translateX(' + (-offset) + 'px)';

    slides.forEach(function (item) {
      item.classList.toggle('is-active', item === slide);
    });

    if (prevBtn) prevBtn.disabled = carouselIndex <= 0;
    if (nextBtn) nextBtn.disabled = carouselIndex >= items.length - 1;
    renderDots();
  }

  function selectOrg(orgId) {
    const slide = slideByOrgId(orgId);
    const panel = panelByOrgId(orgId);
    if (!panel) return;

    activeOrgId = String(orgId);

    panels.forEach(function (item) {
      const isActive = item.dataset.orgPanel === activeOrgId;
      item.hidden = !isActive;
      item.classList.toggle('is-active', isActive);
    });

    if (slide) {
      updateStageHead(slide);
      const visible = visibleSlides();
      carouselIndex = Math.max(0, visible.indexOf(slide));
      updateCarouselPosition();
    }
  }

  function goToSlide(index) {
    const items = visibleSlides();
    if (!items.length) return;

    carouselIndex = Math.max(0, Math.min(index, items.length - 1));
    updateCarouselPosition();
    selectOrg(items[carouselIndex].dataset.orgId);
  }

  if (prevBtn) {
    prevBtn.addEventListener('click', function () {
      goToSlide(carouselIndex - 1);
    });
  }

  if (nextBtn) {
    nextBtn.addEventListener('click', function () {
      goToSlide(carouselIndex + 1);
    });
  }

  slides.forEach(function (slide) {
    slide.addEventListener('click', function () {
      const visible = visibleSlides();
      const index = visible.indexOf(slide);
      if (index >= 0) {
        goToSlide(index);
      }
    });
  });

  if (searchInput) {
    searchInput.addEventListener('input', function () {
      const query = searchInput.value.trim().toLowerCase();
      let visibleOrgCount = 0;

      slides.forEach(function (slide) {
        const orgHaystack = slide.dataset.orgSearch || '';
        const panel = panelByOrgId(slide.dataset.orgId);
        const cards = panel ? Array.from(panel.querySelectorAll('.welcome-bacheca__card[data-search]')) : [];
        let visibleCards = 0;

        cards.forEach(function (card) {
          const haystack = card.dataset.search || '';
          const match = !query || haystack.includes(query) || orgHaystack.includes(query);
          card.hidden = !match;
          if (match) visibleCards++;
        });

        const showOrg = !query || orgHaystack.includes(query) || visibleCards > 0;
        slide.hidden = !showOrg;
        if (panel) panel.hidden = !showOrg || panel.dataset.orgPanel !== String(activeOrgId);
        if (showOrg) visibleOrgCount++;
      });

      if (query) {
        const firstVisible = visibleSlides()[0];
        if (firstVisible && firstVisible.dataset.orgId !== String(activeOrgId)) {
          selectOrg(firstVisible.dataset.orgId);
        } else if (activeOrgId) {
          const activePanel = panelByOrgId(activeOrgId);
          if (activePanel) {
            activePanel.hidden = false;
          }
        }
      } else if (activeOrgId) {
        selectOrg(activeOrgId);
      }

      updateCarouselPosition();
      const activeSlide = slideByOrgId(activeOrgId);
      if (activeSlide) updateStageHead(activeSlide);

      if (searchEmpty) {
        searchEmpty.hidden = visibleOrgCount > 0 || !query;
      }
      if (stageEl) {
        stageEl.hidden = visibleOrgCount === 0 && !!query;
      }
      if (carouselEl) {
        carouselEl.hidden = visibleOrgCount === 0 && !!query;
      }
    });
  }

  if (activeOrgId) {
    const initialSlide = slideByOrgId(activeOrgId);
    if (initialSlide) updateStageHead(initialSlide);
    updateCarouselPosition();
  }

  let welcomeModalReady = false;

  function initWelcomeAttivitaModal() {
    if (welcomeModalReady) return;

    const modalEl = document.getElementById('welcomeAttivitaModal');
    if (!modalEl) return;

    if (modalEl.parentElement !== document.body) {
      document.body.appendChild(modalEl);
    }

    if (typeof bootstrap === 'undefined') {
      window.setTimeout(initWelcomeAttivitaModal, 50);
      return;
    }

    const modal = bootstrap.Modal.getOrCreateInstance(modalEl, {
      backdrop: true,
      focus: true,
    });
    const modalShell = document.getElementById('welcomeModalShell');
    const heroEl = document.getElementById('welcomeModalHero');
    const titleEl = document.getElementById('welcomeAttivitaModalLabel');
    const descEl = document.getElementById('welcomeModalDesc');
    const mediaEl = document.getElementById('welcomeModalMedia');
    const saltacodaLink = document.getElementById('welcomeActionSaltacoda');
    const schedaLink = document.getElementById('welcomeActionScheda');

    if (!modalShell || !heroEl || !titleEl || !descEl || !mediaEl || !saltacodaLink || !schedaLink) return;

    function cleanupModalOverlay() {
      document.querySelectorAll('body > .modal-backdrop').forEach(function (backdrop) {
        backdrop.remove();
      });
      document.body.classList.remove('modal-open');
      document.body.style.removeProperty('overflow');
      document.body.style.removeProperty('padding-right');
    }

    modalEl.addEventListener('hidden.bs.modal', cleanupModalOverlay);
    modalEl.addEventListener('shown.bs.modal', function () {
      const backdrops = document.querySelectorAll('body > .modal-backdrop');
      if (backdrops.length > 1) {
        backdrops.forEach(function (backdrop, index) {
          if (index < backdrops.length - 1) {
            backdrop.remove();
          }
        });
      }
    });

    function renderAvatar(iniziali, accent) {
      mediaEl.innerHTML = '';
      mediaEl.style.setProperty('--card-accent', accent || '#f58220');
      const span = document.createElement('span');
      span.className = 'welcome-bacheca__modal-avatar';
      span.textContent = iniziali || '?';
      mediaEl.appendChild(span);
    }

    function renderMedia(logo, iniziali, accent) {
      mediaEl.innerHTML = '';
      mediaEl.style.setProperty('--card-accent', accent || '#f58220');

      if (logo) {
        const img = document.createElement('img');
        img.src = logo;
        img.alt = '';
        img.className = 'welcome-bacheca__modal-logo';
        img.onerror = function () {
          renderAvatar(iniziali, accent);
        };
        mediaEl.appendChild(img);
      } else {
        renderAvatar(iniziali, accent);
      }
    }

    function renderHero(cover, accent, hasCustomCover) {
      heroEl.innerHTML = '';
      heroEl.style.setProperty('--card-accent', accent || '#f58220');
      heroEl.classList.toggle('welcome-bacheca__modal-hero--placeholder', !hasCustomCover);

      if (hasCustomCover && cover) {
        const img = document.createElement('img');
        img.src = cover;
        img.alt = '';
        img.className = 'welcome-bacheca__modal-hero-img';
        heroEl.appendChild(img);
        return;
      }

      const placeholder = document.createElement('span');
      placeholder.className = 'welcome-bacheca__modal-hero-placeholder';
      const logo = document.createElement('img');
      logo.src = cover || '';
      logo.alt = '';
      logo.className = 'welcome-bacheca__modal-hero-placeholder-logo';
      placeholder.appendChild(logo);
      heroEl.appendChild(placeholder);
    }

    document.addEventListener('click', function (event) {
      const trigger = event.target.closest('.welcome-bacheca__card-menu');
      if (!trigger) return;

      event.preventDefault();
      event.stopPropagation();

      const nome = trigger.dataset.attivitaNome || '';
      const descrizione = trigger.dataset.attivitaDescrizione || '';
      const logo = trigger.dataset.attivitaLogo || '';
      const cover = trigger.dataset.attivitaCover || '';
      const hasCustomCover = trigger.dataset.attivitaHasCover === '1';
      const iniziali = trigger.dataset.attivitaIniziali || '?';
      const accent = trigger.dataset.attivitaAccent || '#f58220';
      const saltacodaUrl = trigger.dataset.saltacodaUrl || '#';
      const schedaUrl = trigger.dataset.schedaUrl || '#';
      const saltacodaAttivo = trigger.dataset.saltacodaAttivo === '1';

      modalShell.style.setProperty('--card-accent', accent);

      titleEl.textContent = nome;
      descEl.textContent = descrizione;
      descEl.hidden = !descrizione;

      renderHero(cover, accent, hasCustomCover);
      renderMedia(logo, iniziali, accent);

      saltacodaLink.href = saltacodaUrl;
      saltacodaLink.hidden = !saltacodaAttivo;
      schedaLink.href = schedaUrl;
      schedaLink.hidden = false;

      modal.show();
    });

    welcomeModalReady = true;
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initWelcomeAttivitaModal);
  } else {
    initWelcomeAttivitaModal();
  }

  window.addEventListener('resize', function () {
    updateCarouselPosition();
  });
})();
</script>
@endsection
