// Home page — unique duration-dial hero + vibe + map

const DurationDial = ({ days, setDays }) => {
  const marks = [1, 2, 3, 4, 5, 6, 7];
  return (
    <div style={{ width: '100%', maxWidth: 720, position: 'relative' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 14, alignItems: 'flex-end' }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', color: 'var(--muted)', textTransform: 'uppercase' }}>
          Drag → set your duration
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.14em' }}>
          {days === 1 ? 'a single day' : days === 7 ? 'a full week' : `${days} days`}
        </div>
      </div>
      <input
        type="range"
        min="1" max="7" step="1"
        value={days}
        onChange={(e) => setDays(Number(e.target.value))}
        className="duration-slider"
      />
      <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 16 }}>
        {marks.map((m) => (
          <button key={m} onClick={() => setDays(m)}
            style={{
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              opacity: days === m ? 1 : 0.4, transition: 'opacity .15s',
            }}>
            <span className="serif" style={{
              fontSize: days === m ? 28 : 20,
              fontWeight: 400,
              color: days === m ? 'var(--ink)' : 'var(--ink-soft)',
              transition: 'font-size .2s',
              fontVariationSettings: '"opsz" 144, "WONK" 1',
            }}>
              {m}
            </span>
            <span className="mono" style={{ fontSize: 9, color: 'var(--muted)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
              {m === 1 ? 'day' : 'days'}
            </span>
          </button>
        ))}
      </div>
    </div>
  );
};

// Little India outline map with dots for each tour
const MiniMap = ({ tours, selected, setSelected }) => {
  // Coordinates per CITY (extracted from tour.location). Anything not listed
  // falls back to a deterministic offset so dots never collapse to the centre.
  const cityCoords = {
    'Ahmedabad': { x: 26, y: 46 },
    'Alleppey':  { x: 38, y: 86 },
    'Jaisalmer': { x: 22, y: 35 },
    'Kasol':     { x: 45, y: 14 },
    'Mumbai':    { x: 28, y: 60 },
    'Delhi':     { x: 44, y: 24 },
    'Chennai':   { x: 55, y: 78 },
    'Mysuru':    { x: 42, y: 78 },
    'Kaza':      { x: 48, y: 12 },
    'Udaipur':   { x: 28, y: 42 },
    'Varanasi':  { x: 56, y: 38 },
    'Hampi':     { x: 44, y: 70 },
    'Darjeeling':{ x: 70, y: 32 },
    'Gangtok':   { x: 71, y: 30 },
    'Shillong':  { x: 78, y: 36 },
    'Tawang':    { x: 80, y: 26 },
    'Goa':       { x: 33, y: 66 },
    'Andamans':  { x: 82, y: 78 },
    'Pondicherry':{x: 56, y: 80 },
    'Coorg':     { x: 41, y: 76 },
    'Ooty':      { x: 44, y: 80 },
    'Rishikesh': { x: 47, y: 22 },
    'Leh':       { x: 49, y: 14 },
    'Nubra Valley':{x:50, y: 12 },
    'Pangong':   { x: 52, y: 14 },
    'Manali':    { x: 46, y: 16 },
    'Shimla':    { x: 46, y: 20 },
    'Dharamshala':{x:44, y: 18 },
    'Amritsar':  { x: 42, y: 22 },
    'Rann of Kutch':{x:18,y: 44 },
    'Somnath':   { x: 21, y: 52 },
    'Gir':       { x: 22, y: 52 },
    'Saputara':  { x: 28, y: 54 },
    'Hyderabad': { x: 48, y: 64 },
    'Bengaluru': { x: 44, y: 74 },
    'Kodaikanal':{ x: 45, y: 82 },
    'Thekkady':  { x: 42, y: 84 },
    'Wayanad':   { x: 41, y: 79 },
    'Varkala':   { x: 40, y: 88 },
    'Kanyakumari':{x:44, y: 92 },
    'Rameshwaram':{x:50, y: 86 },
    'Khajuraho': { x: 50, y: 40 },
    'Orchha':    { x: 48, y: 38 },
    'Agra Extended':{x:46,y: 30 },
    'Mount Abu': { x: 26, y: 40 },
    'Pushkar':   { x: 30, y: 36 },
    'Bikaner':   { x: 26, y: 30 },
    'Jodhpur':   { x: 25, y: 38 },
    'Chandigarh':{ x: 44, y: 22 },
    'Mussoorie': { x: 46, y: 20 },
    'Nainital':  { x: 49, y: 22 },
    'Jim Corbett':{ x:50, y: 24 },
    'Ranthambore':{x:32, y: 36 },
  };
  const fallback = (id) => {
    let h = 0; for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) | 0;
    return { x: 25 + (Math.abs(h) % 40), y: 20 + (Math.abs(h >> 5) % 60) };
  };
  const coordFor = (t) => {
    const city = (t.location || '').split(',')[0].trim();
    return cityCoords[city] || fallback(t.id);
  };
  // limit to 12 dots so the small map doesn't get visually clogged
  const dots = (tours || []).slice(0, 12);
  return (
    <svg viewBox="0 0 100 100" style={{ width: '100%', height: '100%', overflow: 'visible' }}>
      <path
        d="M 35 6 Q 42 4 48 8 Q 56 6 60 10 Q 68 10 72 16 Q 74 22 70 26 Q 66 32 62 34 Q 64 40 62 44 Q 66 48 68 54 Q 70 60 66 68 Q 62 76 58 82 Q 54 90 48 94 Q 42 96 38 92 Q 32 88 30 80 Q 28 72 32 66 Q 28 60 26 52 Q 22 44 20 36 Q 22 28 28 22 Q 30 14 35 6 Z"
        fill="var(--sage-soft)"
        stroke="var(--sage)"
        strokeWidth="0.3"
        opacity="0.55"
      />
      {dots.map((t) => {
        const c = coordFor(t);
        const isSel = selected === t.id;
        return (
          <g key={t.id} style={{ cursor: 'pointer' }}
             onMouseEnter={() => setSelected(t.id)}
             onClick={() => setSelected(t.id)}>
            {/* invisible hit target */}
            <circle cx={c.x} cy={c.y} r="4" fill="transparent" />
            <circle cx={c.x} cy={c.y} r={isSel ? 2.6 : 1.4}
              fill={isSel ? 'var(--clay)' : 'var(--ink)'}
              stroke="var(--bg)" strokeWidth="0.5"
              style={{ transition: 'r .2s' }}
            />
            {isSel && (
              <>
                <circle cx={c.x} cy={c.y} r="4" fill="none" stroke="var(--clay)" strokeWidth="0.25" opacity="0.5">
                  <animate attributeName="r" from="2.6" to="6" dur="1.5s" repeatCount="indefinite" />
                  <animate attributeName="opacity" from="0.6" to="0" dur="1.5s" repeatCount="indefinite" />
                </circle>
                <g transform={`translate(${c.x}, ${c.y - 5})`}>
                  <rect x="-12" y="-3.6" width="24" height="4.6" rx="0.6" fill="var(--ink)" />
                  <text x="0" y="-0.2" textAnchor="middle" fontSize="2.4" fontFamily="Fraunces" fontStyle="italic" fill="var(--bg)">
                    {(t.location || '').split(',')[0]}
                  </text>
                </g>
              </>
            )}
          </g>
        );
      })}
    </svg>
  );
};

const TourChip = ({ tour, onClick, featured }) => (
  <button
    onClick={onClick}
    style={{
      display: 'flex',
      alignItems: 'stretch',
      gap: 14,
      padding: 14,
      borderRadius: 4,
      textAlign: 'left',
      background: 'var(--white)',
      border: '1px solid var(--line)',
      transition: 'all .18s',
      width: '100%',
    }}
    onMouseEnter={(e) => {
      e.currentTarget.style.borderColor = 'var(--ink)';
      e.currentTarget.style.transform = 'translateY(-2px)';
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.borderColor = 'var(--line)';
      e.currentTarget.style.transform = 'translateY(0)';
    }}
  >
    <div style={{ width: 76, height: 76, flexShrink: 0, borderRadius: 2, overflow: 'hidden' }}>
      <Placeholder tone={tour.hero.tone} img={tour.hero.img} label="" />
    </div>
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', minWidth: 0 }}>
      <div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--muted)', textTransform: 'uppercase', marginBottom: 4 }}>
          {tour.location.split(',')[0]} · {tour.days} {tour.days === 1 ? 'day' : 'days'}
        </div>
        <div className="serif" style={{ fontSize: 18, fontWeight: 400, lineHeight: 1.15, letterSpacing: '-0.02em' }}>
          {tour.title}
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: 8 }}>
        <div style={{ fontSize: 13, color: 'var(--ink-soft)' }}>from <span className="serif" style={{ fontSize: 17, fontWeight: 500 }}>₹{tour.price.toLocaleString('en-IN')}</span></div>
        <Icon name="arrow" size={14} />
      </div>
    </div>
  </button>
);

const HomePage = ({ setPage, savedTours, toggleSaved }) => {
  const [days, setDays] = React.useState(3);
  const [vibe, setVibe] = React.useState('all');
  const [region, setRegion] = React.useState('all');
  const [hovered, setHovered] = React.useState(null);

  const filtered = React.useMemo(() => {
    return (window.TOURS || []).filter(Boolean).filter((t) => {
      if (t.days !== days) return false;
      if (vibe !== 'all' && t.vibe !== vibe) return false;
      if (region !== 'all' && t.region !== region) return false;
      return true;
    });
  }, [days, vibe, region]);

  // if nothing matches, relax region & vibe
  const shown = filtered.length ? filtered : (window.TOURS || []).filter(Boolean).filter((t) => t.days === days);

  React.useEffect(() => {
    if (!hovered && shown.length) setHovered(shown[0].id);
  }, [shown, hovered]);

  return (
    <div className="fade-in">
      {/* HERO */}
      <section style={{ padding: '50px 36px 60px', position: 'relative' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 80, alignItems: 'start' }}>
          <div>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 32, display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{ width: 32, height: 1, background: 'var(--muted)' }} /> Pan-India · 1–7 day tours · small groups
            </div>
            <h1 className="serif" style={{
              fontSize: 96,
              fontWeight: 300,
              lineHeight: 0.95,
              letterSpacing: '-0.04em',
              margin: '0 0 28px',
              fontVariationSettings: '"opsz" 144, "SOFT" 100, "WONK" 1',
            }}>
              How long<br />
              do you have<br />
              <em style={{
                fontStyle: 'italic',
                color: 'var(--clay)',
                display: 'inline-block',
                fontVariationSettings: '"opsz" 144, "WONK" 1',
              }}>
                this time<span style={{ color: 'var(--ink)' }}>?</span>
              </em>
            </h1>
            <p style={{ fontSize: 17, color: 'var(--ink-soft)', maxWidth: 480, lineHeight: 1.5, marginBottom: 48 }}>
              Tours across India, sized for whatever weekend or week you can spare. Drag the dial, pick a vibe, see what appears.
            </p>

            <DurationDial days={days} setDays={setDays} />

            {/* Filter chips */}
            <div style={{ display: 'flex', gap: 20, marginTop: 40, alignItems: 'flex-start', flexWrap: 'wrap' }}>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--muted)', textTransform: 'uppercase', marginBottom: 8 }}>Vibe</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {VIBES.map((v) => (
                    <button key={v.id} className={`chip ${vibe === v.id ? 'active' : ''}`} onClick={() => setVibe(v.id)}>
                      <span style={{ fontSize: 12 }}>{v.icon}</span> {v.label}
                    </button>
                  ))}
                </div>
              </div>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--muted)', textTransform: 'uppercase', marginBottom: 8 }}>Region</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {REGIONS.map((r) => (
                    <button key={r.id} className={`chip ${region === r.id ? 'active' : ''}`} onClick={() => setRegion(r.id)}>
                      {r.label}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* Right column — big numeral + map + results */}
          <div>
            <div style={{
              position: 'relative',
              background: 'var(--bg-2)',
              border: '1px solid var(--line)',
              borderRadius: 4,
              padding: '28px 28px 24px',
              marginBottom: 20,
              overflow: 'hidden',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--muted)' }}>
                  Tours for <span style={{ color: 'var(--ink)' }}>{days}</span> {days === 1 ? 'day' : 'days'}
                </div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--muted)' }}>
                  {shown.length} {shown.length === 1 ? 'match' : 'matches'}
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
                <div className="numeral" style={{ fontSize: 180, color: 'var(--ink)', marginTop: -8, marginBottom: -16 }}>
                  {days}
                </div>
                <div style={{ width: 160, height: 160, marginLeft: 'auto' }}>
                  <MiniMap tours={shown} selected={hovered} setSelected={setHovered} />
                </div>
              </div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>→ hover the dots</span>
                {hovered && (() => {
                  const t = shown.find(x => x.id === hovered);
                  return t ? <span style={{ color: 'var(--ink)' }}>{t.location.split(',')[0]} · ₹{t.price.toLocaleString('en-IN')}</span> : null;
                })()}
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {shown.slice(0, 3).map((t) => (
                <div key={t.id}
                  onMouseEnter={() => setHovered(t.id)}
                >
                  <TourChip tour={t} onClick={() => setPage({ name: 'detail', id: t.id })} />
                </div>
              ))}
              {shown.length > 3 && (
                <button className="btn btn-outline" style={{ alignSelf: 'center', marginTop: 4 }}
                  onClick={() => setPage({ name: 'listing', filters: { days } })}>
                  See all {shown.length} →
                </button>
              )}
              {shown.length === 0 && (
                <div style={{ padding: 32, textAlign: 'center', color: 'var(--muted)', background: 'var(--white)', border: '1px dashed var(--line)', borderRadius: 4 }}>
                  <div className="serif" style={{ fontSize: 24, color: 'var(--ink)', fontStyle: 'italic', marginBottom: 6 }}>nothing yet</div>
                  <div className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>loosen a filter?</div>
                </div>
              )}
            </div>
          </div>
        </div>
      </section>

      <Ticker items={[
        'NEW: Spiti winter tours for 2026',
        'Small groups · never more than 12 travellers',
        'Customize any 3+ day tour',
        'Now booking April through September',
        'Handpicked homestays in every city',
      ]} />

      {/* Featured strip */}
      <FeaturedSection setPage={setPage} />

      {/* How it works — editorial */}
      <HowItWorks />

      <Footer />
    </div>
  );
};

const FeaturedSection = ({ setPage }) => {
  const _all = (window.TOURS || []).filter(Boolean);
  const featured = [_all[2], _all[4], _all[6]].filter(Boolean);
  return (
    <section style={{ padding: '100px 36px 60px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 40 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--muted)', marginBottom: 12 }}>
            ✶ Spring ’26 picks
          </div>
          <h2 className="serif" style={{ fontSize: 56, fontWeight: 300, letterSpacing: '-0.03em', margin: 0, lineHeight: 1 }}>
            The ones we’re <em style={{ color: 'var(--clay)', fontStyle: 'italic' }}>quietly proud of</em>.
          </h2>
        </div>
        <button className="btn btn-ghost" onClick={() => setPage({ name: 'listing' })}>Browse all 47 tours →</button>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
        {featured.map((t, i) => (
          <button key={t.id} onClick={() => setPage({ name: 'detail', id: t.id })}
            style={{
              display: 'flex', flexDirection: 'column', alignItems: 'stretch', textAlign: 'left',
              background: 'transparent',
              transform: i === 1 ? 'translateY(40px)' : 'none',
            }}>
            <div style={{ aspectRatio: '4 / 5', position: 'relative', marginBottom: 20, overflow: 'hidden' }}>
              <Placeholder tone={t.hero.tone} img={t.hero.img} label={t.hero.label} />
              <div style={{
                position: 'absolute', top: 16, left: 16,
                background: 'var(--bg)', padding: '4px 10px', borderRadius: 999,
              }}>
                <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>
                  {t.days} {t.days === 1 ? 'day' : 'days'}
                </span>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
              <h3 className="serif" style={{ fontSize: 28, margin: 0, fontWeight: 400, letterSpacing: '-0.02em' }}>{t.title}</h3>
              <span className="mono" style={{ fontSize: 13 }}>₹{t.price.toLocaleString('en-IN')}</span>
            </div>
            <p style={{ margin: 0, color: 'var(--ink-soft)', fontSize: 14, lineHeight: 1.5 }}>{t.tagline}</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 14, color: 'var(--ink)', fontSize: 13 }}>
              <Icon name="arrow" size={14} /> <span style={{ borderBottom: '1px solid var(--ink)', paddingBottom: 1 }}>See itinerary</span>
            </div>
          </button>
        ))}
      </div>
    </section>
  );
};

const HowItWorks = () => (
  <section style={{ padding: '120px 36px', background: 'var(--sage)', color: 'var(--bg)', marginTop: 60 }}>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 60, alignItems: 'start' }}>
      <div>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.6)', marginBottom: 16 }}>
          How it actually works
        </div>
        <div className="serif" style={{ fontSize: 72, fontWeight: 300, lineHeight: 0.95, letterSpacing: '-0.04em' }}>
          Three<br />steps.<br />
          <em style={{ fontStyle: 'italic', color: 'var(--butter)', fontVariationSettings: '"WONK" 1' }}>No more.</em>
        </div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 40 }}>
        {[
          { n: '01', title: 'Pick your length', body: 'One day, one week, or somewhere in between. The dial shows what exists at your duration.' },
          { n: '02', title: 'Choose your vibe', body: 'Adventure, culture, coastal, a bit of everything. Filter in seconds, preview itinerary in one click.' },
          { n: '03', title: 'Pack light', body: 'We handle stays, transport, guides, and the small stuff. You bring a notebook or don’t.' },
        ].map((s) => (
          <div key={s.n} style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 24, borderTop: '1px solid rgba(255,255,255,0.2)', paddingTop: 28 }}>
            <div className="numeral" style={{ fontSize: 54, color: 'var(--butter)' }}>{s.n}</div>
            <div>
              <div className="serif" style={{ fontSize: 28, fontWeight: 400, marginBottom: 8, letterSpacing: '-0.02em' }}>{s.title}</div>
              <div style={{ fontSize: 15, color: 'rgba(255,255,255,0.75)', lineHeight: 1.6, maxWidth: 480 }}>{s.body}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  </section>
);

Object.assign(window, { HomePage });
