// Scenes — narrative cards. Concise trekking-company copy.
const { useEffect, useState } = React;

function SectionBanner({ children }) {
  return (
    <div style={{
      background: '#C05A2A', color: '#FFFFFF', padding: '6px 14px',
      fontFamily: 'Arial', fontWeight: 700, fontSize: 11,
      letterSpacing: 1.4, textTransform: 'uppercase', display: 'inline-block',
    }}>{children}</div>
  );
}

function IntroCard({ onPick, activeTrekId }) {
  const treks = window.LUMORA_DATA.treks;
  const [tick, setTick] = useState(0);
  // Rotating "live counter" — small kinetic detail to draw the eye on land
  useEffect(() => {
    const t = setInterval(() => setTick(x => x + 1), 2400);
    return () => clearInterval(t);
  }, []);
  const stats = [
    { n: '5,545', u: 'm', label: 'Highest point on our trails' },
    { n: '1,247', u: 'trekkers', label: 'Walked with us since 2009' },
    { n: '0', u: 'evacuations', label: 'In the last 4 seasons' },
    { n: '15', u: 'yrs', label: 'Average guide experience' },
  ];
  const stat = stats[tick % stats.length];

  return (
    <div className="card">
      {/* Live kinetic stat — replaces the static "expert-guided · Since 2009" tag */}
      <div style={{
        display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 14,
        paddingBottom: 12, borderBottom: '1px solid #E8DFC4',
      }}>
        <span style={{
          fontFamily: '"Courier New", ui-monospace, monospace',
          fontSize: 28, fontWeight: 700, color: '#C05A2A',
          letterSpacing: -0.5, lineHeight: 1,
          transition: 'opacity .4s',
        }} key={tick}>{stat.n}</span>
        <span style={{
          fontFamily: 'Arial', fontSize: 11, fontWeight: 700,
          color: '#C05A2A', textTransform: 'uppercase', letterSpacing: 1.4,
        }}>{stat.u}</span>
        <span style={{
          fontFamily: 'Arial', fontSize: 11, color: '#7A6A5A',
          marginLeft: 'auto', textAlign: 'right', fontStyle: 'italic',
        }}>{stat.label}</span>
      </div>

      <h1 style={{
        fontFamily: 'Arial, Helvetica, sans-serif', fontWeight: 700,
        fontSize: 40, lineHeight: 1.0, color: '#2E2822',
        margin: 0, letterSpacing: -1.2,
      }}>
        The map is<br/>
        <span style={{
          background: 'linear-gradient(180deg, transparent 60%, #F0C896 60%, #F0C896 92%, transparent 92%)',
          paddingLeft: 4, paddingRight: 4,
        }}>the route.</span>
      </h1>

      <p style={{
        fontFamily: 'Arial', fontSize: 13.5, lineHeight: 1.55, color: '#2E2822',
        marginTop: 14, marginBottom: 18,
      }}>
        Pick a Himalayan trek. Scroll. The map flies you over real terrain,
        village by village, the same path your boots will walk. No stock
        photos, no fluff — just the route, the days, the weather, the cost.
      </p>

      <SectionBanner>Choose your trek</SectionBanner>
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 8, marginTop: 14,
        // Cap height once we go past ~6 treks so the card doesn't run off-screen
        // — internal scroll keeps the rest reachable. For ≤6 treks the list
        // sizes naturally with no scrollbar.
        maxHeight: treks.length > 6 ? 360 : 'none',
        overflowY: treks.length > 6 ? 'auto' : 'visible',
        paddingRight: treks.length > 6 ? 4 : 0,
      }}>
        {treks.map(t => {
          const active = t.id === activeTrekId;
          // Tighten rows when the list is long, keep the airy version for ≤4
          const dense = treks.length > 4;
          return (
            <button
              key={t.id}
              onClick={() => onPick(t.id)}
              style={{
                textAlign: 'left',
                background: active ? '#C05A2A' : '#FAF8F3',
                color: active ? '#FFFFFF' : '#2E2822',
                border: '1px solid ' + (active ? '#C05A2A' : '#E8DFC4'),
                padding: dense ? '9px 12px' : '12px 14px',
                fontFamily: 'Arial', cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                gap: 16,
              }}
              onMouseEnter={e => { if (!active) e.currentTarget.style.backgroundColor = '#F0EBE0'; }}
              onMouseLeave={e => { if (!active) e.currentTarget.style.backgroundColor = '#FAF8F3'; }}
            >
              <div>
                <div style={{ fontWeight: 700, fontSize: dense ? 13.5 : 15, marginBottom: 2 }}>{t.name}</div>
                <div style={{ fontSize: dense ? 10.5 : 11, opacity: active ? 0.9 : 0.7 }}>{t.tagline}</div>
              </div>
              <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: 1.2, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>
                {t.altitude} {active ? '↗' : '→'}
              </div>
            </button>
          );
        })}
      </div>

      <div style={{
        marginTop: 18, paddingTop: 14, borderTop: '1px solid #E8DFC4',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, fontFamily: 'Arial',
      }}>
        {[['LICENSED', 'Govt. of Nepal'], ['EXPERT GUIDES', '15+ yrs avg'], ['SMALL GROUP', 'small groups; flexible sizing']].map(([k, v]) => (
          <div key={k}>
            <div style={{ fontSize: 8.5, letterSpacing: 1.4, color: '#7A6A5A', fontWeight: 700, marginBottom: 3 }}>{k}</div>
            <div style={{ fontSize: 11, color: '#2E2822' }}>{v}</div>
          </div>
        ))}
      </div>

      <div style={{ marginTop: 20, display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 32, height: 32, borderRadius: '50%', border: '1.5px solid #2E2822',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="10" height="13" viewBox="0 0 14 18">
            <path d="M7 2 V 16 M 1 10 L 7 16 L 13 10" stroke="#2E2822" strokeWidth="1.5" fill="none" strokeLinecap="round" />
          </svg>
        </div>
        <span style={{ fontFamily: 'Arial', fontSize: 10, letterSpacing: 2, textTransform: 'uppercase', color: '#7A6A5A' }}>
          Scroll to walk the route
        </span>
      </div>
    </div>
  );
}

function ApproachCard({ trek }) {
  const permits = (window.LUMORA_DATA.permits || {})[trek.id] || [];
  const Extras = window.LumoraExtras;
  return (
    <div className="card">
      <SectionBanner>{trek.name}</SectionBanner>
      <h2 style={{ fontFamily: 'Arial', fontWeight: 700, fontSize: 26, color: '#2E2822', margin: '14px 0 10px', letterSpacing: -0.4 }}>
        The route at a glance
      </h2>
      <p style={{ fontFamily: 'Arial', fontSize: 13, lineHeight: 1.6, color: '#2E2822', margin: 0 }}>
        {trek.id === 'ebc' && 'Our flagship. 12 days into the Khumbu — flight to Lukla, two acclimatisation nights at Namche, then a steady ascent to base camp.'}
        {trek.id === 'abc' && '9 days from Pokhara into a glacial amphitheatre ringed by 7,000-metre peaks. Moderate ascent; no flights required.'}
        {trek.id === 'lang' && '8 days in the valley nearest Kathmandu. A drive in, a steady walk up through forest to Kyanjin Gompa, and an optional summit at Tserko Ri.'}
      </p>
      <div style={{ marginTop: 16, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        {[['DURATION', trek.tagline.split('·')[0].trim()], ['DISTANCE', trek.tagline.split('·')[1]?.trim()],
          ['MAX ALT.', trek.altitude], ['DIFFICULTY', trek.difficulty],
          ['SEASON', trek.season], ['FROM', trek.price + ' / person']].map(([k, v]) => (
          <div key={k} style={{ borderLeft: '2px solid #C05A2A', paddingLeft: 10 }}>
            <div style={{ fontFamily: 'Arial', fontSize: 9, letterSpacing: 1.5, color: '#7A6A5A', fontWeight: 700, marginBottom: 4 }}>{k}</div>
            <div style={{ fontFamily: 'Arial', fontSize: 13, color: '#2E2822', fontWeight: 500 }}>{v}</div>
          </div>
        ))}
      </div>

      {Extras && Extras.ElevationProfile ? (
        <div style={{ marginTop: 16 }}>
          <div style={{ fontFamily: 'Arial', fontSize: 9, letterSpacing: 1.5, color: '#7A6A5A', fontWeight: 700, marginBottom: 6, textTransform: 'uppercase' }}>
            Elevation profile
          </div>
          <Extras.ElevationProfile trek={trek} activeIndex={-1} />
        </div>
      ) : null}

      {permits.length ? (
        <div style={{ marginTop: 16 }}>
          <div style={{ fontFamily: 'Arial', fontSize: 9, letterSpacing: 1.5, color: '#7A6A5A', fontWeight: 700, marginBottom: 8, textTransform: 'uppercase' }}>
            Permits — included in trip price
          </div>
          {permits.map((p, i) => (
            <div key={i} style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              padding: '5px 0', borderBottom: i < permits.length - 1 ? '1px dashed #E8DFC4' : 'none',
              fontFamily: 'Arial', fontSize: 12, color: '#2E2822',
            }}>
              <span style={{ paddingRight: 10 }}>{p.name}</span>
              <span style={{ fontFamily: '"Courier New", monospace', fontSize: 11, color: '#7A6A5A', whiteSpace: 'nowrap' }}>
                {p.cost} <span style={{ color: '#C05A2A' }}>{p.usd}</span>
              </span>
            </div>
          ))}
        </div>
      ) : null}
    </div>
  );
}

// StopCard — only mounts thumbnail + weather when `isActive` is true.
// This means Open-Meteo is fetched only for the stop currently in the viewport.
function StopCard({ trek, stop, stopIndex, isActive }) {
  const total = trek.stops.length;
  const num = String(stopIndex + 1).padStart(2, '0');
  const Extras = window.LumoraExtras;

  const kindLabel =
    stop.kind === 'flight' ? 'Mountain flight' :
    stop.kind === 'peak'   ? 'Optional summit' :
    stop.kind === 'view'   ? 'Viewpoint' :
    stop.kind === 'camp'   ? 'High camp' :
    stop.kind === 'start'  ? 'Departure' :
    stop.kind === 'end'    ? 'Destination' :
                             'Walking day';

  return (
    <div className="card">
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <div style={{ fontFamily: 'Arial', fontSize: 11, letterSpacing: 2, color: '#C05A2A', fontWeight: 700, textTransform: 'uppercase' }}>
          Day {num} / {String(total).padStart(2, '0')}
        </div>
        <div style={{ fontFamily: 'Arial', fontSize: 11, color: '#7A6A5A', fontStyle: 'italic' }}>{trek.name}</div>
      </div>

      <h3 style={{ fontFamily: 'Arial', fontWeight: 700, fontSize: 24, color: '#2E2822', margin: '0 0 4px', letterSpacing: -0.4 }}>
        {stop.name}
      </h3>
      <div style={{
        fontFamily: 'Arial', fontSize: 12, color: '#7A6A5A', marginBottom: 12,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10,
      }}>
        <span>{kindLabel} · {stop.alt}</span>
        {Extras && Extras.AmsBadge ? <Extras.AmsBadge alt={stop.alt} /> : null}
      </div>

      {/* Lazy-mount thumbnail: only when active */}
      {isActive && Extras ? (
        <Extras.StopThumb stop={stop} height={140} />
      ) : (
        <div style={{
          height: 140,
          background: 'repeating-linear-gradient(135deg, #E8DFC4 0 14px, #F0EBE0 14px 28px)',
          border: '1px solid #D9CFB3',
        }} />
      )}

      <p style={{ fontFamily: 'Arial', fontSize: 13, lineHeight: 1.55, color: '#2E2822', marginTop: 12, marginBottom: 0 }}>
        {stop.blurb}
      </p>

      {/* Lazy-mount weather: only when active */}
      {isActive && Extras ? <Extras.WeatherStrip stop={stop} /> : null}

      <div style={{ marginTop: 14, display: 'flex', gap: 3 }}>
        {trek.stops.map((s, i) => (
          <div key={s.id + i} style={{
            flex: 1, height: 3,
            background: i <= stopIndex ? '#C05A2A' : '#E8DFC4',
            transition: 'background .4s ease',
          }} />
        ))}
      </div>
    </div>
  );
}

function RecapCard({ trek, onContact }) {
  const gear = window.LUMORA_DATA.gear || { bring: [], rentable: [], provided: [] };
  return (
    <div className="card">
      <SectionBanner>Trip summary</SectionBanner>
      <h2 style={{ fontFamily: 'Arial', fontWeight: 700, fontSize: 24, color: '#2E2822', margin: '14px 0 4px', letterSpacing: -0.4 }}>
        {trek.name}
      </h2>
      <p style={{ fontFamily: 'Arial', fontSize: 12.5, color: '#7A6A5A', margin: '0 0 16px' }}>
        {trek.stops.length} stops · {trek.tagline}
      </p>

      <div style={{ background: '#2E2822', color: '#FFFFFF', padding: '14px 16px', display: 'flex', alignItems: 'baseline', gap: 12 }}>
        <div style={{ fontFamily: 'Arial', fontSize: 10, letterSpacing: 2, opacity: 0.7 }}>FROM</div>
        <div style={{ fontFamily: 'Arial', fontSize: 28, fontWeight: 700, letterSpacing: -0.5 }}>
          {trek.price}
        </div>
        <div style={{ fontFamily: 'Arial', fontSize: 10, letterSpacing: 1.2, opacity: 0.7 }}>USD / person</div>
      </div>

      <ul style={{ listStyle: 'none', padding: 0, margin: '14px 0 16px', fontFamily: 'Arial', fontSize: 12.5, lineHeight: 1.6, color: '#2E2822' }}>
        {[
          ['Includes', 'Teahouse stays, all permits, internal flights, guide & porter, airport transfers.'],
          ['Group size', 'Small groups by default. Solo bookings, couples, families, and corporate groups all welcome — we tailor the size to your party.'],
          ['Safety', 'Daily oximeter checks above 3,500 m; emergency evacuation insurance required.'],
        ].map(([k, v]) => (
          <li key={k} style={{ display: 'flex', gap: 10, marginBottom: 6 }}>
            <span style={{ color: '#C05A2A', marginTop: 2 }}>●</span>
            <span><b>{k}.</b> {v}</span>
          </li>
        ))}
      </ul>

      <div style={{ borderTop: '1px solid #E8DFC4', paddingTop: 12 }}>
        <div style={{ fontFamily: 'Arial', fontSize: 10, letterSpacing: 1.8, color: '#C05A2A', fontWeight: 700, textTransform: 'uppercase', marginBottom: 10 }}>
          Gear
        </div>
        <GearColumn title="You bring" items={gear.bring} accent="#2E2822" />
        <GearColumn title="Rent in Kathmandu" items={gear.rentable} accent="#7A6A5A" subtle />
        <GearColumn title="We provide" items={gear.provided} accent="#C05A2A" />
      </div>

      <button
        onClick={onContact}
        style={{
          marginTop: 16, width: '100%',
          background: '#C05A2A', color: '#FFFFFF', border: 'none',
          padding: '13px', fontFamily: 'Arial', fontWeight: 700,
          fontSize: 12, letterSpacing: 1.5, textTransform: 'uppercase', cursor: 'pointer',
        }}>Enquire about this trek →</button>
    </div>
  );
}

function GearColumn({ title, items, accent, subtle }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <div style={{
        fontFamily: 'Arial', fontSize: 9, letterSpacing: 1.4, color: accent,
        fontWeight: 700, textTransform: 'uppercase', marginBottom: 4,
      }}>
        {title}
      </div>
      <ul style={{ listStyle: 'none', padding: 0, margin: 0, fontFamily: 'Arial', fontSize: 11.5, lineHeight: 1.5, color: subtle ? '#5E5448' : '#2E2822' }}>
        {items.map((it, i) => (
          <li key={i} style={{ display: 'flex', gap: 8, padding: '2px 0' }}>
            <span style={{
              flexShrink: 0, marginTop: 5,
              width: 6, height: 6, border: '1px solid ' + accent,
              background: subtle ? 'transparent' : accent,
            }} />
            <span>{it}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

// ContactCard — quick enquiry form with selected trek pre-filled.
function ContactCard({ trek }) {
  const [form, setForm] = useState({
    name: '', email: '', date: '', people: '2',
    msg: '', trekId: trek.id,
  });
  const [sent, setSent] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    setForm(f => ({ ...f, trekId: trek.id }));
  }, [trek.id]);

  const update = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      // Replace this URL with your actual Cloudflare Worker URL
      const WORKER_URL = 'https://lumora-contact.foo-4ef.workers.dev';

      const res = await fetch(WORKER_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form)
      });

      if (res.ok) {
        setSent(true);
      } else {
        alert('Something went wrong. Please try again or contact us directly.');
      }
    } catch (err) {
      alert('Network error. Please try again or contact us directly.');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (sent) {
    return (
      <div className="card">
        <SectionBanner>Thanks!</SectionBanner>
        <h2 style={{ fontFamily: 'Arial', fontWeight: 700, fontSize: 24, color: '#2E2822', margin: '14px 0 8px', letterSpacing: -0.4 }}>
          We&rsquo;ll be in touch.
        </h2>
        <p style={{ fontFamily: 'Arial', fontSize: 13, lineHeight: 1.6, color: '#2E2822', margin: '0 0 16px' }}>
          Prajjwal will reply within 24 hours from Kathmandu — usually with a draft itinerary
          and a short list of questions about your fitness and timing.
        </p>
        <div style={{
          background: '#FAF8F3', border: '1px solid #E8DFC4', padding: '12px 14px',
          fontFamily: 'Arial', fontSize: 12, color: '#2E2822',
        }}>
          <div style={{ fontSize: 9, letterSpacing: 1.4, color: '#7A6A5A', fontWeight: 700, textTransform: 'uppercase', marginBottom: 6 }}>
            Or reach us directly
          </div>
          <div>hello@lumoratreks.com</div>
          <div>WhatsApp: +977 9847259352</div>
        </div>
      </div>
    );
  }

  const inputStyle = {
    width: '100%',
    background: '#FAF8F3', border: '1px solid #E8DFC4',
    padding: '9px 11px', fontFamily: 'Arial', fontSize: 13, color: '#2E2822',
    outline: 'none', borderRadius: 0,
  };
  const labelStyle = {
    fontFamily: 'Arial', fontSize: 9, letterSpacing: 1.4, color: '#7A6A5A',
    fontWeight: 700, textTransform: 'uppercase', marginBottom: 4, display: 'block',
  };

  return (
    <div className="card">
      <SectionBanner>Enquire</SectionBanner>
      <h2 style={{ fontFamily: 'Arial', fontWeight: 700, fontSize: 24, color: '#2E2822', margin: '14px 0 4px', letterSpacing: -0.4 }}>
        Plan your trek
      </h2>
      <p style={{ fontFamily: 'Arial', fontSize: 12.5, color: '#7A6A5A', margin: '0 0 16px' }}>
        For:{' '}
        <select value={form.trekId} onChange={update('trekId')} style={{
          fontFamily: 'Arial', fontSize: 12.5, fontWeight: 700, color: '#2E2822',
          background: 'transparent', border: 'none', borderBottom: '1px dashed #C05A2A',
          outline: 'none', cursor: 'pointer', padding: '0 18px 0 0',
          appearance: 'none', WebkitAppearance: 'none',
          backgroundImage: 'url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20width%3D%2210%22%20height%3D%226%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cpath%20d%3D%22M1%201l4%204%204-4%22%20stroke%3D%22%23C05A2A%22%20stroke-width%3D%221.5%22%20fill%3D%22none%22%20stroke-linecap%3D%22round%22%2F%3E%3C%2Fsvg%3E")',
          backgroundRepeat: 'no-repeat', backgroundPosition: 'right center',
        }}>
          {window.LUMORA_DATA.treks.map(t => (
            <option key={t.id} value={t.id}>{t.name}</option>
          ))}
          <option value="other">Other / Custom Trek</option>
        </select>
        {' '}· we reply within 24 hrs
      </p>

      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div>
          <label style={labelStyle}>Name</label>
          <input required style={inputStyle} value={form.name} onChange={update('name')} placeholder="Your full name" />
        </div>
        <div>
          <label style={labelStyle}>Email</label>
          <input required type="email" style={inputStyle} value={form.email} onChange={update('email')} placeholder="you@example.com" />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 10 }}>
          <div>
            <label style={labelStyle}>Preferred month</label>
            <input style={inputStyle} value={form.date} onChange={update('date')} placeholder="e.g. October 2026" />
          </div>
          <div>
            <label style={labelStyle}>Trekkers</label>
            <input style={inputStyle} type="number" min="1" max="20" value={form.people} onChange={update('people')} />
          </div>
        </div>
        <div>
          <label style={labelStyle}>Anything we should know</label>
          <textarea style={{ ...inputStyle, height: 70, resize: 'vertical', fontFamily: 'Arial' }}
            value={form.msg} onChange={update('msg')}
            placeholder="Fitness, prior trekking experience, dietary needs…" />
        </div>
        <button type="submit" disabled={isSubmitting} style={{
          background: isSubmitting ? '#E8DFC4' : '#C05A2A',
          color: isSubmitting ? '#7A6A5A' : '#FFFFFF',
          border: 'none',
          padding: '13px', fontFamily: 'Arial', fontWeight: 700,
          fontSize: 12, letterSpacing: 1.5, textTransform: 'uppercase',
          cursor: isSubmitting ? 'not-allowed' : 'pointer',
        }}>
          {isSubmitting ? 'Sending...' : 'Send enquiry →'}
        </button>
      </form>

      <div style={{
        marginTop: 14, paddingTop: 12, borderTop: '1px solid #E8DFC4',
        fontFamily: 'Arial', fontSize: 11, color: '#7A6A5A', lineHeight: 1.5,
      }}>
        Lumora Treks Pvt. Ltd. · Satungal, Kathmandu
      </div>
    </div>
  );
}

window.LumoraScenes = { IntroCard, ApproachCard, StopCard, RecapCard, ContactCard };
