// 360° Panorama walk – drag-to-pan wide image with clickable hotspots
// Placeholder photography from picsum.photos (deterministic seeds).
// Real 360° photos to be supplied by client.

const PANORAMA_PLACES = [
  {
    id: 'grenada-bay',
    label: { ru: 'Grand Anse Beach, Гренада', en: 'Grand Anse Beach, Grenada' },
    img: 'https://picsum.photos/seed/migronis-pano-grenada/2800/780',
    hotspots: [
      { x: 18, y: 56, t: { ru: 'Marine Village – yacht-club', en: 'Marine Village – yacht-club' } },
      { x: 42, y: 68, t: { ru: '5★ резорт-отели и виллы', en: '5★ resort hotels & villas' } },
      { x: 64, y: 48, t: { ru: 'Прозрачная вода, +27 °C', en: 'Clear water, +27 °C' } },
      { x: 84, y: 60, t: { ru: 'Школы для детей экспатов', en: 'Expat-friendly schools' } },
    ],
  },
  {
    id: 'lisbon',
    label: { ru: 'Алфама, Лиссабон', en: 'Alfama, Lisbon' },
    img: 'https://picsum.photos/seed/migronis-pano-lisbon/2800/780',
    hotspots: [
      { x: 14, y: 52, t: { ru: 'Трамвай 28, исторический центр', en: 'Tram 28, historic centre' } },
      { x: 38, y: 64, t: { ru: 'Mercado da Ribeira – еда и вино', en: 'Mercado da Ribeira – food & wine' } },
      { x: 60, y: 44, t: { ru: 'Виды на реку Тежу', en: 'Tagus river views' } },
      { x: 80, y: 56, t: { ru: 'Beachfront в 25 мин (Кашкайш)', en: 'Beachfront in 25 min (Cascais)' } },
    ],
  },
  {
    id: 'istanbul',
    label: { ru: 'Босфор, Стамбул', en: 'Bosphorus, Istanbul' },
    img: 'https://picsum.photos/seed/migronis-pano-istanbul/2800/780',
    hotspots: [
      { x: 16, y: 58, t: { ru: 'Босфорский мост – Европа↔Азия', en: 'Bosphorus Bridge – Europe↔Asia' } },
      { x: 40, y: 50, t: { ru: 'Bebek – премиум-район', en: 'Bebek – premium district' } },
      { x: 64, y: 62, t: { ru: 'Marine taxis, личные пристани', en: 'Marine taxis, private docks' } },
      { x: 86, y: 46, t: { ru: 'Galata + Topkapı', en: 'Galata + Topkapı' } },
    ],
  },
  {
    id: 'limassol',
    label: { ru: 'Лимасол, Кипр', en: 'Limassol, Cyprus' },
    img: 'https://picsum.photos/seed/migronis-pano-limassol/2800/780',
    hotspots: [
      { x: 20, y: 60, t: { ru: 'Marina Limassol – yacht district', en: 'Marina Limassol – yacht district' } },
      { x: 44, y: 50, t: { ru: 'Бизнес-офисы, IT-сектор', en: 'Business offices, IT sector' } },
      { x: 66, y: 64, t: { ru: 'Английский medium-school', en: 'English-medium schools' } },
      { x: 84, y: 52, t: { ru: '340 солнечных дней / год', en: '340 sunny days / year' } },
    ],
  },
];

function PanoramaViewer({ lang }) {
  const [placeIdx, setPlaceIdx] = React.useState(0);
  const [pan, setPan] = React.useState(0); // 0..1 - normalized horizontal position
  const [dragging, setDragging] = React.useState(false);
  const [hoverHs, setHoverHs] = React.useState(null);
  const trackRef = React.useRef(null);
  const dragStartRef = React.useRef(null);

  const place = PANORAMA_PLACES[placeIdx];

  // Auto-drift when idle (gentle ambient motion)
  React.useEffect(() => {
    let raf;
    let last = performance.now();
    let direction = 1;
    const tick = (now) => {
      const dt = (now - last) / 1000;
      last = now;
      if (!dragging) {
        setPan((p) => {
          let np = p + direction * dt * 0.012;
          if (np > 1) { direction = -1; np = 1; }
          if (np < 0) { direction = 1; np = 0; }
          return np;
        });
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [dragging]);

  const onPointerDown = (e) => {
    setDragging(true);
    dragStartRef.current = { x: e.clientX, pan };
    e.currentTarget.setPointerCapture?.(e.pointerId);
  };
  const onPointerMove = (e) => {
    if (!dragging || !trackRef.current) return;
    const dx = e.clientX - dragStartRef.current.x;
    const width = trackRef.current.clientWidth;
    const newPan = Math.max(0, Math.min(1, dragStartRef.current.pan - dx / (width * 1.5)));
    setPan(newPan);
  };
  const onPointerUp = () => { setDragging(false); };

  // Compute image offset: we shift the image left by (panoExtra * pan)
  // Image native ratio: 2800/780 ≈ 3.59, viewport will be wider than tall
  // The image will be larger than container width – slide horizontally
  const imgScale = 1.6; // image renders 1.6× container width to allow panning
  const offsetPct = pan * (imgScale - 1) * 100;

  return (
    <div>
      {/* Place picker */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {PANORAMA_PLACES.map((p, i) => (
          <button key={p.id}
            onClick={() => { setPlaceIdx(i); setPan(0); }}
            className="chip"
            style={{
              height: 36, padding: '0 16px', cursor: 'pointer',
              background: placeIdx === i ? 'var(--accent-soft)' : 'var(--surface)',
              borderColor: placeIdx === i ? 'var(--accent)' : 'var(--border)',
              color: 'var(--fg)',
            }}>
            {p.label[lang]}
          </button>
        ))}
      </div>

      {/* Viewer */}
      <div ref={trackRef}
           style={{
             position: 'relative', borderRadius: 'var(--r-xl)',
             overflow: 'hidden', border: '1px solid var(--border)',
             aspectRatio: '3 / 1.05',
             background: 'var(--bg-elev-2)',
             cursor: dragging ? 'grabbing' : 'grab',
             userSelect: 'none', touchAction: 'none',
           }}
           onPointerDown={onPointerDown}
           onPointerMove={onPointerMove}
           onPointerUp={onPointerUp}
           onPointerCancel={onPointerUp}>
        {/* Image */}
        <img src={place.img} alt={place.label[lang]} draggable="false" loading="lazy"
             style={{
               position: 'absolute', top: 0, height: '100%',
               width: `${imgScale * 100}%`,
               left: `-${offsetPct}%`,
               objectFit: 'cover',
               filter: 'saturate(1.1)',
               transition: dragging ? 'none' : 'left .15s linear',
               pointerEvents: 'none',
             }} />

        {/* Vignette */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none',
          background: 'radial-gradient(ellipse at center, transparent 55%, rgba(0,0,0,0.35) 100%)',
        }} />

        {/* Hotspots */}
        {place.hotspots.map((h, i) => {
          // Convert hotspot world-X (0..100 within image) to viewer-X
          const localX = (h.x * imgScale - offsetPct) / 1;
          const visible = localX > -5 && localX < 105;
          return (
            <div key={i}
                 onMouseEnter={() => setHoverHs(i)}
                 onMouseLeave={() => setHoverHs(null)}
                 onClick={(e) => { e.stopPropagation(); }}
                 style={{
                   position: 'absolute',
                   left: `${localX}%`, top: `${h.y}%`,
                   transform: 'translate(-50%, -50%)',
                   opacity: visible ? 1 : 0,
                   transition: 'opacity .3s',
                   pointerEvents: visible ? 'auto' : 'none',
                   cursor: 'pointer',
                 }}>
              <span style={{
                position: 'absolute', inset: 0,
                width: 22, height: 22, borderRadius: 999,
                background: 'var(--accent)', opacity: .5,
                animation: 'pulse 1.6s ease-out infinite',
              }} />
              <span style={{
                position: 'relative', display: 'block',
                width: 22, height: 22, borderRadius: 999,
                background: 'var(--accent)',
                border: '2px solid #fff',
                boxShadow: '0 0 0 1px var(--accent), 0 8px 24px rgba(0,0,0,0.4)',
              }}>
                <span style={{
                  position: 'absolute', inset: 7, borderRadius: 999, background: '#fff',
                }} />
              </span>
              {hoverHs === i && (
                <div style={{
                  position: 'absolute', left: '50%', bottom: 'calc(100% + 10px)',
                  transform: 'translateX(-50%)',
                  background: 'rgba(0,0,0,0.85)', color: '#fff',
                  padding: '8px 14px', borderRadius: 8,
                  fontSize: 12, whiteSpace: 'nowrap',
                  backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
                }}>
                  {h.t[lang]}
                  <span style={{
                    position: 'absolute', top: '100%', left: '50%',
                    transform: 'translateX(-50%)',
                    width: 0, height: 0,
                    borderLeft: '5px solid transparent',
                    borderRight: '5px solid transparent',
                    borderTop: '5px solid rgba(0,0,0,0.85)',
                  }} />
                </div>
              )}
            </div>
          );
        })}

        {/* Bottom bar */}
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          padding: '12px 20px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          background: 'linear-gradient(0deg, rgba(0,0,0,0.5), transparent)',
          color: '#fff', pointerEvents: 'none',
        }}>
          <div>
            <div style={{ fontSize: 12, opacity: 0.7, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
              {lang === 'ru' ? 'Локация' : 'Location'}
            </div>
            <div style={{ fontSize: 16, fontWeight: 500, marginTop: 2 }}>
              {place.label[lang]}
            </div>
          </div>
          <div style={{ fontSize: 11, opacity: 0.7, fontFamily: 'var(--f-mono)' }}>
            {lang === 'ru' ? '← перетащите для обзора →' : '← drag to look around →'}
          </div>
        </div>

        {/* Pan progress mini */}
        <div style={{
          position: 'absolute', right: 18, top: 18,
          width: 100, height: 4, borderRadius: 4,
          background: 'rgba(255,255,255,0.25)',
          overflow: 'hidden',
        }}>
          <div style={{
            width: '32%', height: '100%',
            background: '#fff',
            transform: `translateX(${pan * 210}%)`,
            transition: dragging ? 'none' : 'transform .15s linear',
          }} />
        </div>
      </div>
    </div>
  );
}

function PanoramaSection({ lang }) {
  return (
    <section className="section" style={{ paddingTop: 80, paddingBottom: 24 }}>
      <div className="container-wide">
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          marginBottom: 32, flexWrap: 'wrap', gap: 24,
        }}>
          <div style={{ maxWidth: 640 }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>
              {lang === 'ru' ? '– 360° обзор локаций' : '– 360° location preview'}
            </div>
            <h2 className="display h-2" style={{ margin: 0 }}>
              {lang === 'ru'
                ? <>Посмотрите туда,<br/>где вы будете <em>жить</em></>
                : <>See where you'll<br/><em>actually</em> live</>}
            </h2>
            <p style={{ color: 'var(--fg-muted)', fontSize: 16, marginTop: 18, maxWidth: 540 }}>
              {lang === 'ru'
                ? 'Перетащите для обзора. Точки на изображении – реальные ориентиры: яхт-клубы, школы, медицинские центры, бизнес-районы.'
                : 'Drag to look around. The pins are real anchor points: marinas, schools, hospitals, business districts.'}
            </p>
          </div>
          <span className="chip mono" style={{ height: 32 }}>
            {lang === 'ru' ? 'placeholder · реальные 360° фото от клиента' : 'placeholder · real 360° photos pending'}
          </span>
        </div>
        <PanoramaViewer lang={lang} />
      </div>
    </section>
  );
}

window.PanoramaSection = PanoramaSection;
