// HimLocal — v2.8 Lightbox + Onboarding tour (desktop + mobile shared)

const { useState: useStateWLb, useEffect: useEffectWLb, useRef: useRefWLb } = React;

// ─── Lightbox / image gallery ─────────────────────────
function WebLightbox({ images, startIdx = 0, onClose, mode = 'desktop' }) {
  const [i, setI] = useStateWLb(startIdx);
  useEffectWLb(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') setI(x => Math.max(0, x - 1));
      if (e.key === 'ArrowRight') setI(x => Math.min(images.length - 1, x + 1));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [images.length]);
  if (!images || images.length === 0) return null;
  const cur = images[i];
  const src = typeof cur === 'string' ? cur : cur.url;
  const caption = typeof cur === 'string' ? null : cur.caption;
  const isM = mode === 'mobile';

  return (
    <div className={isM ? 'app-lb-back' : 'w2-lb-back'} onClick={onClose}>
      <div className={isM ? 'app-lb__head' : 'w2-lb__head'} onClick={e => e.stopPropagation()}>
        <span className="w2-lb__count">{i + 1} / {images.length}</span>
        <button className="w2-lb__close" onClick={onClose}>×</button>
      </div>
      <div className={isM ? 'app-lb__main' : 'w2-lb__main'} onClick={e => e.stopPropagation()}>
        {!isM && (
          <button className="w2-lb__nav w2-lb__nav--prev" disabled={i === 0} onClick={() => setI(x => Math.max(0, x - 1))}>‹</button>
        )}
        <img className={isM ? 'app-lb__img' : 'w2-lb__img'} src={src} alt=""/>
        {!isM && (
          <button className="w2-lb__nav w2-lb__nav--next" disabled={i >= images.length - 1} onClick={() => setI(x => Math.min(images.length - 1, x + 1))}>›</button>
        )}
      </div>
      {caption && !isM && <div className="w2-lb__caption">{caption}</div>}
      <div className={isM ? 'app-lb__thumbs' : 'w2-lb__thumbs'} onClick={e => e.stopPropagation()}>
        {images.map((img, idx) => {
          const url = typeof img === 'string' ? img : img.url;
          return (
            <div key={idx}
              className={`${isM ? 'app-lb__thumb' : 'w2-lb__thumb'} ${idx === i ? 'is-on' : ''}`}
              style={{ backgroundImage:`url(${url})` }}
              onClick={() => setI(idx)}/>
          );
        })}
      </div>
    </div>
  );
}
window.WebLightbox = WebLightbox;

// ─── Onboarding tour (desktop) ─────────────────────────
const TOUR_STEPS = [
  { selector:'.v2-search-strip',
    title:<>Find your way <em>in.</em></>,
    body:'Search for a region, a season, or a vibe — Spiti in autumn, Parvati in spring, Triund for a weekend. Or just dive into the map.' },
  { selector:'.v2-tiles',
    title:<>Four ways to <em>begin.</em></>,
    body:'Explore (map + list + itinerary), Shop (local makers), Adventures (paragliding, rafting, treks), and Cafés (dine-in, takeaway, delivery).' },
  { selector:'.v2-continue',
    title:<>Trips persist <em>between visits.</em></>,
    body:'Your itinerary lives across sessions. Free plan gives you 5 trips; Pro unlocks 50.' },
];

function WebTour({ onDone, steps = TOUR_STEPS, mode = 'desktop' }) {
  const [step, setStep] = useStateWLb(0);
  const [pos, setPos] = useStateWLb(null);
  const targetRef = useRefWLb(null);

  useEffectWLb(() => {
    const target = document.querySelector(steps[step]?.selector);
    if (!target) { setPos({ top:120, left:'50%', marginLeft:-180, place:'center' }); return; }
    target.classList.add('w2-tour-target');
    targetRef.current = target;
    const r = target.getBoundingClientRect();
    const cardH = 200;
    const cardW = 360;
    const below = r.bottom + 16;
    const above = r.top - cardH - 16;
    const useBelow = below + cardH < window.innerHeight - 20;
    const top = useBelow ? below : (above > 20 ? above : 20);
    const left = Math.max(16, Math.min(window.innerWidth - cardW - 16, r.left + r.width / 2 - cardW / 2));
    setPos({ top, left, place:useBelow ? 'top' : 'bottom' });
    return () => target.classList.remove('w2-tour-target');
  }, [step]);

  const last = step === steps.length - 1;
  return (
    <>
      <div className="w2-tour-back" onClick={onDone}/>
      <div className="w2-tour-card" style={pos ? { top:pos.top, left:pos.left } : {}}>
        {pos?.place === 'top'    && <div className="w2-tour-card__arrow w2-tour-card__arrow--top"/>}
        {pos?.place === 'bottom' && <div className="w2-tour-card__arrow w2-tour-card__arrow--bottom"/>}
        <div className="w2-tour-card__step">Step {step + 1} of {steps.length}</div>
        <div className="w2-tour-card__t">{steps[step].title}</div>
        <div className="w2-tour-card__body">{steps[step].body}</div>
        <div className="w2-tour-card__row">
          <div className="w2-tour-card__dots">{steps.map((_, i) => <span key={i} className={`w2-tour-card__dot ${i === step ? 'is-on' : ''}`}/>)}</div>
          <div style={{display:'flex',gap:8}}>
            <button className="skip" onClick={onDone}>Skip tour</button>
            <button className="next" onClick={() => last ? onDone() : setStep(s => s + 1)}>{last ? 'Got it →' : 'Next →'}</button>
          </div>
        </div>
      </div>
    </>
  );
}
window.WebTour = WebTour;

// Helpers to launch the tour (also used for the "first-visit" auto-open)
window.HL_TOUR_KEY = 'himlocal_tour_seen_v1';
window.HL_TOUR_SEEN = () => {
  try { return localStorage.getItem(window.HL_TOUR_KEY) === '1'; } catch { return false; }
};
window.HL_TOUR_MARK = () => { try { localStorage.setItem(window.HL_TOUR_KEY, '1'); } catch {} };
