// Main app — scroll-driven, Leaflet camera. Lazy-mounts stop extras only for
// the active scene so weather + thumbnail render only when in the viewport.
const { useEffect, useRef, useState, useMemo, useCallback } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "defaultTrek": "ebc"
}/*EDITMODE-END*/;

function buildScenes(activeTrekId) {
  const data = window.LUMORA_DATA;
  const scenes = [];
  scenes.push({ kind: 'intro', cam: { kind: 'world' } });
  if (activeTrekId) {
    const trek = data.treks.find(t => t.id === activeTrekId);
    scenes.push({ kind: 'approach', trek, cam: { kind: 'trek', trekId: trek.id } });
    trek.stops.forEach((stop, i) => {
      scenes.push({ kind: 'stop', trek, stop, stopIndex: i, cam: { kind: 'stop', trekId: trek.id, stopIndex: i } });
    });
    scenes.push({ kind: 'recap', trek, cam: { kind: 'trek', trekId: trek.id } });
    scenes.push({ kind: 'contact', trek, cam: { kind: 'trek', trekId: trek.id } });
  }
  return scenes;
}

// Recognize both the pretty URL and the .html form so direct page links
// and SPA-internal navigation share state cleanly.
const pathToTrek = {
  '/treks/everest-base-camp': 'ebc',
  '/treks/everest-base-camp.html': 'ebc',
  '/treks/annapurna-sanctuary': 'abc',
  '/treks/annapurna-sanctuary.html': 'abc',
  '/treks/langtang-valley': 'lang',
  '/treks/langtang-valley.html': 'lang'
};
const trekToPath = {
  'ebc': '/treks/everest-base-camp',
  'abc': '/treks/annapurna-sanctuary',
  'lang': '/treks/langtang-valley'
};

function App() {
  const hookFn = window.useTweaks || (() => [TWEAK_DEFAULTS, () => {}]);
  const [tweaks, setTweak] = hookFn(TWEAK_DEFAULTS);
  
  // Initialize from URL first, then tweaks, then fallback
  const initialTrek = pathToTrek[window.location.pathname] || tweaks.defaultTrek || 'ebc';
  const [activeTrekId, setActiveTrekId] = useState(initialTrek);
  const scenes = useMemo(() => buildScenes(activeTrekId), [activeTrekId]);

  const scrollRef = useRef(null);
  const [sceneIndex, setSceneIndex] = useState(0);
  const rafRef = useRef(null);

  const onScroll = useCallback(() => {
    if (rafRef.current) return;
    rafRef.current = requestAnimationFrame(() => {
      rafRef.current = null;
      const el = scrollRef.current;
      if (!el) return;
      const vh = el.clientHeight;
      const idx = Math.min(scenes.length - 1, Math.max(0, Math.round(el.scrollTop / vh)));
      setSceneIndex(idx);
    });
  }, [scenes.length]);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    el.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => el.removeEventListener('scroll', onScroll);
  }, [onScroll]);

  const initialMountRef = useRef(true);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    // Always start at top on first load (intro card)
    if (initialMountRef.current) {
      initialMountRef.current = false;
      el.scrollTo({ top: 0, behavior: 'auto' });
      return;
    }
    const target = scenes.findIndex(s => s.kind === 'approach');
    if (target >= 0) {
      const vh = el.clientHeight;
      el.scrollTo({ top: target * vh, behavior: 'auto' });
    }
  }, [activeTrekId]);

  const currentScene = scenes[sceneIndex];
  const cameraTarget = currentScene?.cam;

  const activeStopIndex = useMemo(() => {
    if (!currentScene) return null;
    if (currentScene.kind === 'stop') return currentScene.stopIndex;
    if (currentScene.kind === 'approach') return -1;
    if (currentScene.kind === 'recap' || currentScene.kind === 'contact') {
      const trek = window.LUMORA_DATA.treks.find(t => t.id === activeTrekId);
      return trek ? trek.stops.length - 1 : null;
    }
    return null;
  }, [currentScene, activeTrekId]);

  const trekForMap = currentScene?.kind === 'intro' ? null : activeTrekId;
  const activeTrek = window.LUMORA_DATA.treks.find(t => t.id === activeTrekId);

  const handlePick = (id) => {
    setActiveTrekId(id);
    setTweak('defaultTrek', id);
    if (trekToPath[id]) {
      window.history.pushState(null, '', trekToPath[id]);
    }
  };

  const scrollToContact = () => {
    const el = scrollRef.current;
    if (!el) return;
    const idx = scenes.findIndex(s => s.kind === 'contact');
    if (idx >= 0) el.scrollTo({ top: idx * el.clientHeight, behavior: 'smooth' });
  };

  const LumoraMap = window.LumoraMap;
  const TweaksPanel = window.TweaksPanel;
  const TweakSection = window.TweakSection;
  const TweakSelect = window.TweakSelect;
  const { IntroCard, ApproachCard, StopCard, RecapCard, ContactCard } = window.LumoraScenes;

  function renderScene(scene, isActive) {
    if (scene.kind === 'intro')    return <IntroCard onPick={handlePick} activeTrekId={activeTrekId} />;
    if (scene.kind === 'approach') return <ApproachCard trek={scene.trek} />;
    if (scene.kind === 'stop')     return <StopCard trek={scene.trek} stop={scene.stop} stopIndex={scene.stopIndex} isActive={isActive} />;
    if (scene.kind === 'recap')    return <RecapCard trek={scene.trek} onContact={scrollToContact} />;
    if (scene.kind === 'contact')  return <ContactCard trek={scene.trek} />;
    return null;
  }

  // Compute "now on" label for top bar
  const nowOnLabel = (() => {
    if (!currentScene) return '';
    if (currentScene.kind === 'intro')    return 'Choosing a route';
    if (currentScene.kind === 'approach') return 'Route overview';
    if (currentScene.kind === 'stop')     return currentScene.stop.name + ' · ' + currentScene.stop.alt;
    if (currentScene.kind === 'recap')    return 'Trip summary';
    if (currentScene.kind === 'contact')  return 'Enquire';
    return '';
  })();

  // Day count for stops (Day X / Y)
  const dayCounter = (() => {
    if (currentScene?.kind === 'stop' && activeTrek) {
      return 'Day ' + (currentScene.stopIndex + 1) + ' / ' + activeTrek.stops.length;
    }
    return null;
  })();

  return (
    <div style={{ height: '100vh', overflow: 'hidden', position: 'relative', background: '#F3F0E1' }}>

      {/* Live map — framed inset, tighter gaps so narrative card has cleaner separation */}
      <div style={{
        position: 'absolute',
        top: 56, bottom: 18, left: 18, right: 18,
        zIndex: 1,
        border: '1px solid #C05A2A',
      }}>
        <LumoraMap
          activeTrekId={trekForMap}
          activeStopIndex={activeStopIndex}
          onPickTrek={handlePick}
          onPickStop={(trekId, stopIndex) => {
            if (trekId !== activeTrekId) setActiveTrekId(trekId);
            setTimeout(() => {
              const el = scrollRef.current;
              if (!el) return;
              const idx = scenes.findIndex(s => s.kind === 'stop' && s.trek.id === trekId && s.stopIndex === stopIndex);
              if (idx >= 0) el.scrollTo({ top: idx * el.clientHeight, behavior: 'smooth' });
            }, trekId !== activeTrekId ? 50 : 0);
          }}
          cameraTarget={cameraTarget}
          panAnchor="left"
        />
      </div>

      {/* Top bar — brand + live "you are here" + book CTA */}
      <div className="lumora-topbar" style={{
        position: 'absolute', top: 0, left: 0, right: 0, zIndex: 1000,
        padding: '12px 22px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        background: 'linear-gradient(to bottom, rgba(243,240,225,0.95), rgba(243,240,225,0))',
        pointerEvents: 'none',
        gap: 16,
      }}>
        {/* Brand */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <img
            src={(window.__resources && window.__resources.lumoraLogo) || "assets/lumora-logo.png"}
            alt="Lumora Treks"
            style={{ width: 28, height: 'auto', display: 'block' }}
          />
          <div style={{ fontFamily: 'Arial', fontSize: 11, fontWeight: 700, letterSpacing: 2.4, color: '#2E2822' }}>
            LUMORA TREKS
          </div>
        </div>

        {/* Center: live "you are here" indicator */}
        <div className="lumora-topbar-center" style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: '#F3F0E1', border: '1px solid #E8DFC4',
          padding: '6px 12px',
          fontFamily: 'Arial', fontSize: 11, color: '#2E2822',
          pointerEvents: 'auto',
        }}>
          {/* Pulsing locator dot */}
          <span style={{ position: 'relative', width: 8, height: 8, display: 'inline-block' }}>
            <span style={{
              position: 'absolute', inset: 0, borderRadius: '50%',
              background: '#C05A2A',
            }} />
            <span style={{
              position: 'absolute', inset: -3, borderRadius: '50%',
              border: '1.5px solid #C05A2A', opacity: 0.5,
              animation: 'topbarPulse 1.8s ease-out infinite',
            }} />
          </span>
          {dayCounter && (
            <span style={{
              fontWeight: 700, letterSpacing: 1.2, fontSize: 9,
              color: '#C05A2A', textTransform: 'uppercase',
              borderRight: '1px solid #E8DFC4', paddingRight: 10,
            }}>{dayCounter}</span>
          )}
          <span style={{ fontWeight: 500 }}>{nowOnLabel}</span>
          {activeTrek && currentScene?.kind !== 'intro' && (
            <span style={{
              borderLeft: '1px solid #E8DFC4', paddingLeft: 10, marginLeft: 2,
              fontSize: 10, color: '#7A6A5A', fontStyle: 'italic',
            }}>{activeTrek.name}</span>
          )}
        </div>

        {/* Right: Book CTA */}
        <div className="lumora-topbar-right" style={{ display: 'flex', alignItems: 'center', gap: 12, pointerEvents: 'auto' }}>
          <a className="lumora-topbar-email" href="mailto:hello@lumoratreks.com" style={{
            fontFamily: 'Arial', fontSize: 11, color: '#2E2822',
            textDecoration: 'none', borderBottom: '1px solid #C05A2A',
            paddingBottom: 1,
          }}>hello@lumoratreks.com</a>
          <span className="lumora-topbar-sep">/</span>
          <div className="lumora-topbar-phone" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor">
              <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a12.8 12.8 0 0 0-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/>
            </svg>
            <a href="https://wa.me/9779847259352" target="_blank" rel="noreferrer" style={{
              display: 'inline-flex', alignItems: 'center',
              fontFamily: 'Arial', fontSize: 11, color: '#2E2822',
              textDecoration: 'none', borderBottom: '1px solid #C05A2A',
              paddingBottom: 1,
            }}>
              +977 9847259352
            </a>
          </div>
          <button
            onClick={scrollToContact}
            style={{
              background: '#C05A2A', color: '#FFFFFF', border: 'none',
              padding: '7px 14px', fontFamily: 'Arial', fontWeight: 700,
              fontSize: 10, letterSpacing: 1.5, textTransform: 'uppercase',
              cursor: 'pointer',
            }}>Book a trek →</button>
        </div>
      </div>
      <div style={{ position: 'absolute', top: 50, left: 22, right: 22, height: 1, background: '#C05A2A', opacity: 0.5, zIndex: 1000, pointerEvents: 'none' }} />

      {/* Scene progress (right edge) */}
      <div style={{
        position: 'absolute', top: '50%', right: 12, transform: 'translateY(-50%)',
        zIndex: 1000, display: 'flex', flexDirection: 'column', gap: 5, alignItems: 'center',
        pointerEvents: 'none',
      }}>
        {scenes.map((s, i) => (
          <div key={i} style={{
            width: i === sceneIndex ? 16 : 8, height: 2,
            background: i <= sceneIndex ? '#C05A2A' : '#D9CFB3',
            transition: 'all .3s ease',
          }} />
        ))}
      </div>

      {/* Scrollable narrative — left column only, so map gets wheel events on the right */}
      <div ref={scrollRef} className="scenes" style={{
        position: 'absolute',
        top: 0, bottom: 0, left: 0,
        width: 460, maxWidth: '95vw',
        zIndex: 5,
        overflowY: 'auto',
        background: 'transparent',
      }}>
        {scenes.map((scene, i) => {
          const isActive = i === sceneIndex;
          return (
            <div
              key={`${scene.kind}-${i}`}
              style={{
                height: '100vh', display: 'flex', alignItems: 'center',
                justifyContent: 'flex-start',
                padding: '0 36px',
              }}
            >
              <div style={{ width: 360, maxWidth: '92vw' }}>
                {renderScene(scene, isActive)}
              </div>
            </div>
          );
        })}
      </div>

      {/* Pulse keyframe for top-bar locator + mobile collapses */}
      <style>{`
        @keyframes topbarPulse {
          0%   { transform: scale(0.7); opacity: 0.6; }
          100% { transform: scale(1.6); opacity: 0; }
        }
        /* Below ~880px: drop the center "you are here" pill — it's noise on a phone. */
        @media (max-width: 880px) {
          .lumora-topbar-center { display: none !important; }
        }
        /* Below ~640px: collapse the email/phone block, keep only the Book CTA. */
        @media (max-width: 640px) {
          .lumora-topbar { padding: 10px 14px !important; gap: 10px !important; }
          .lumora-topbar-email,
          .lumora-topbar-sep,
          .lumora-topbar-phone { display: none !important; }
        }
      `}</style>

      {/* Tweaks */}
      {TweaksPanel && (
        <TweaksPanel title="Tweaks">
          <TweakSection title="Trek">
            <TweakSelect
              label="Selected trek"
              value={activeTrekId}
              onChange={(v) => handlePick(v)}
              options={[
                { value: 'ebc', label: 'Everest Base Camp' },
                { value: 'abc', label: 'Annapurna Sanctuary' },
                { value: 'lang', label: 'Langtang Valley' },
              ]}
            />
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
