/* Telegram Mini App – JS (vanilla, no deps)
   - Theme sync with Telegram
   - Bottom sheets (infos/categories)
   - Search filter (index)
   - Slider + price chips (detail)
*/

(() => {
  'use strict';

  const tg = window.Telegram?.WebApp;
  const root = document.documentElement;

  const setVar = (k, v) => {
    if (typeof v === 'string' && v.trim()) root.style.setProperty(k, v.trim());
  };

  const applyTgTheme = () => {
    if (!tg?.themeParams) return;
    const p = tg.themeParams;

    // Telegram theme params may be undefined depending on client
    setVar('--bg', p.bg_color);
    setVar('--surface', p.secondary_bg_color);
    setVar('--surface2', p.bg_color);
    setVar('--text', p.text_color);
    setVar('--muted', p.hint_color);
    setVar('--accent', p.button_color || p.link_color);
    setVar('--border', p.section_separator_color);

    // Improve contrast if hint color is too close to text
    if (p.text_color && !p.hint_color) setVar('--muted', p.text_color);
  };

  try {
    if (tg) {
      tg.ready?.();
      tg.expand?.();
      applyTgTheme();
      tg.onEvent?.('themeChanged', applyTgTheme);
    }
  } catch (_) {
    // no-op
  }

  // ---------- Utils ----------
  const $ = (sel, ctx = document) => ctx.querySelector(sel);
  const $$ = (sel, ctx = document) => Array.from(ctx.querySelectorAll(sel));

  // ---------- Sheets ----------
  const syncSheetState = () => {
    document.body.classList.toggle('sheet-open', !!document.querySelector('.sheet.open'));
  };

  const openSheet = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    el.classList.add('open');
    syncSheetState();
    try { tg?.HapticFeedback?.impactOccurred?.('light'); } catch {}
  };
  const closeSheet = (id) => {
    const el = document.getElementById(id);
    if (!el) return;
    el.classList.remove('open');
    syncSheetState();
  };

  document.addEventListener('click', (e) => {
    const openBtn = e.target.closest?.('[data-sheet-open]');
    if (openBtn) {
      e.preventDefault();
      openSheet(openBtn.getAttribute('data-sheet-open'));
      return;
    }

    const closeBtn = e.target.closest?.('[data-sheet-close]');
    if (closeBtn) {
      e.preventDefault();
      closeSheet(closeBtn.getAttribute('data-sheet-close'));
      return;
    }

    const scrim = e.target.closest?.('[data-sheet-scrim]');
    if (scrim) {
      e.preventDefault();
      closeSheet(scrim.getAttribute('data-sheet-scrim'));
      return;
    }

    // Telegram-friendly link opening
    const tgLink = e.target.closest?.('a[data-tg-link]');
    if (tgLink && tg) {
      const href = tgLink.getAttribute('href');
      if (!href) return;
      e.preventDefault();
      try {
        if (/^https:\/\/t\.me\//i.test(href) && tg.openTelegramLink) tg.openTelegramLink(href);
        else if (tg.openLink) tg.openLink(href);
        else window.open(href, '_blank', 'noopener');
      } catch {
        window.open(href, '_blank', 'noopener');
      }
    }
  }, { passive: false });

  // Close sheets on Escape
  document.addEventListener('keydown', (e) => {
    if (e.key !== 'Escape') return;
    $$('.sheet.open').forEach((s) => s.classList.remove('open'));
    syncSheetState();
  });

  // ---------- Image fallback ----------
  const placeholder = $('meta[name="app-placeholder"]')?.content || 'assets/placeholder.svg';
  $$('img[data-fallback]').forEach((img) => {
    img.addEventListener('error', () => {
      if (img.getAttribute('src') !== placeholder) img.setAttribute('src', placeholder);
    }, { once: true });
  });

  // ---------- Index: search filter ----------
  const searchInput = $('[data-search]');
  if (searchInput) {
    const cards = $$('[data-card]');
    let raf = 0;

    const apply = () => {
      raf = 0;
      const q = (searchInput.value || '').trim().toLowerCase();
      if (!q) {
        cards.forEach((c) => c.classList.remove('hidden'));
        return;
      }
      cards.forEach((c) => {
        const hay = (c.getAttribute('data-name') || '').toLowerCase();
        c.classList.toggle('hidden', !hay.includes(q));
      });
    };

    searchInput.addEventListener('input', () => {
      if (raf) cancelAnimationFrame(raf);
      raf = requestAnimationFrame(apply);
    }, { passive: true });
  }

  // ---------- Detail: slider ----------
  const slider = $('[data-slider]');
  if (slider) {
    const slides = $('[data-slides]', slider);
    if (slides) {
      const items = Array.from(slides.children);
      const dots = $('[data-dots]', slider);
      let index = 0;

      const update = () => {
        slides.style.transform = `translateX(${-index * 100}%)`;
        if (dots) {
          Array.from(dots.children).forEach((d, i) => d.classList.toggle('active', i === index));
        }
      };

      const clampIndex = (i) => {
        const n = items.length || 1;
        return (i + n) % n;
      };

      const go = (next) => {
        index = clampIndex(next);
        update();
      };

      // dots
      if (dots) {
        dots.innerHTML = '';
        items.forEach((_, i) => {
          const d = document.createElement('span');
          d.className = 'dot';
          d.addEventListener('click', () => go(i));
          dots.appendChild(d);
        });
      }

      // buttons
      $('[data-prev]', slider)?.addEventListener('click', () => go(index - 1));
      $('[data-next]', slider)?.addEventListener('click', () => go(index + 1));

      // swipe (pointer)
      let startX = 0;
      let isDown = false;
      const onDown = (e) => {
        isDown = true;
        startX = e.clientX ?? (e.touches?.[0]?.clientX || 0);
      };
      const onUp = (e) => {
        if (!isDown) return;
        isDown = false;
        const endX = e.clientX ?? (e.changedTouches?.[0]?.clientX || 0);
        const dx = endX - startX;
        if (Math.abs(dx) < 40) return;
        go(index + (dx < 0 ? 1 : -1));
      };

      slider.addEventListener('pointerdown', onDown, { passive: true });
      slider.addEventListener('pointerup', onUp, { passive: true });
      slider.addEventListener('touchstart', onDown, { passive: true });
      slider.addEventListener('touchend', onUp, { passive: true });

      update();
    }
  }

  // ---------- Detail: price chips -> order link ----------
  const chipsWrap = $('[data-prices]');
  const orderBtn = $('[data-order-btn]');
  const picked = $('[data-picked]');

  if (chipsWrap && orderBtn) {
    const chips = $$('button[data-label][data-price]', chipsWrap);
    const baseLink = orderBtn.getAttribute('data-base') || orderBtn.getAttribute('href') || '';

    const setActive = (btn) => {
      chips.forEach((c) => c.classList.remove('active'));
      btn.classList.add('active');
      const label = btn.getAttribute('data-label') || '';
      const price = btn.getAttribute('data-price') || '';
      if (picked) picked.textContent = `Choisi : ${label} — ${Number(price).toFixed(2)} €`;
      const enc = encodeURIComponent(label);
      orderBtn.setAttribute('href', `${baseLink}_${enc}`);
    };

    if (chips[0]) setActive(chips[0]);
    chips.forEach((btn) => btn.addEventListener('click', () => setActive(btn)));
  }
})();
