// ============================================================================
// Screens v2 — Home + Map
// Apple cleanliness + Airbnb warmth + Polarsteps travel emotion
// ============================================================================

const { useState: uS, useEffect: uE, useMemo: uM, useRef: uR, Fragment: uF } = React;

// ---------- HOME ----------
function HomeScreen({ openLightbox }) {
  const nav = useNav();
  const pq = usePhotoQuest();
  const day = window.todayInTrip();
  const point = window.primaryPointForDay(day);
  const hero = day.hero || point?.images?.[0];
  const wx = point ? window.WEATHER[point.id] : null;
  const now = new Date();
  const start = new Date(window.TRIP.startDate);
  const daysToGo = Math.max(0, Math.ceil((start - now) / 86400000));
  const isPretrip = now < start;
  const me = window.TEAM[0];

  const scrollRef = uR(null);
  const [scrolled, setScrolled] = uS(false);
  uE(() => {
    const el = scrollRef.current;
    if (!el) return;
    const h = () => setScrolled(el.scrollTop > 40);
    el.addEventListener('scroll', h);
    return () => el.removeEventListener('scroll', h);
  }, []);

  const todayDateLabel = uM(() => {
    const d = new Date(day.date + 'T12:00:00');
    return d.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
  }, [day]);

  return (
    <div className="screen" ref={scrollRef}>
      <div className={`top-bar floating ${scrolled ? 'scrolled' : ''}`}>
        <button className="rbtn" onClick={() => nav.push({ screen: 'checklist' })}>
          <Icon name="check" size={16} />
        </button>
        <div className="tb-title">{isPretrip ? 'Trip Companion' : `Day ${day.n}`}</div>
        <div className="tb-actions">
          <button className="rbtn" onClick={() => nav.push({ screen: 'docs' })}>
            <Icon name="doc" size={16} />
          </button>
        </div>
      </div>

      <div className="screen-inner">
        {/* Greeting */}
        <div className="home-head">
          <div>
            <div className="home-greeting">{isPretrip ? `In ${daysToGo} days` : todayDateLabel}</div>
            <div className="home-date">
              {isPretrip ? 'Almost ready.' : day.title}
            </div>
          </div>
          <div className="home-ava" style={{ backgroundImage: `url(${me.avatar})` }} />
        </div>

        {/* Hero card */}
        <div className="hero-card" onClick={() => point && nav.push({ screen: 'place', pointId: point.id })}>
          {hero && <img src={hero.src} alt={hero.alt} />}
          <div className="hero-card-content">
            <div className="hero-kicker">
              <span className="dot" />
              <span>{isPretrip ? `${daysToGo} days to go` : `Day ${day.n} of 12`}</span>
            </div>
            <h1 className="hero-title display">{point?.name || day.title}</h1>
            <p className="hero-sub">{day.brief}</p>
          </div>
        </div>

        {/* Quick stats */}
        <div className="day-strip">
          <button className="cell" onClick={() => nav.push({ screen: 'weather' })}>
            <span className="mono">Weather</span>
            <span className="v">{wx ? `${wx.t_max}°` : '—'}</span>
          </button>
          <button className="cell" onClick={() => nav.push({ screen: 'map', initialDay: day.id })}>
            <span className="mono">Route</span>
            <span className="v">{day.distance || 'City'}</span>
          </button>
          <button className="cell" onClick={() => point && nav.push({ screen: 'place', pointId: point.id, tab: 'nearby' })}>
            <span className="mono">Nearby</span>
            <span className="v">{point?.nearby?.cheap_eats?.length || 0} eats</span>
          </button>
        </div>

        {/* Today's plan */}
        <div className="section">
          <div className="section-head">
            <h3>Today</h3>
            <button className="action" onClick={() => nav.push({ screen: 'map', initialDay: day.id })}>
              See on map <Icon name="chev" size={12} />
            </button>
          </div>
          <div className="events-card">
            {day.events.slice(0, 5).map((ev, i) => (
              <button key={i} className="event-row"
                      onClick={() => point && nav.push({ screen: 'place', pointId: point.id })}>
                <span className="time">{ev.time}</span>
                <span className="title"><span className="kind-dot" />{ev.title}</span>
                <span className="chev"><Icon name="chev" size={16} /></span>
              </button>
            ))}
          </div>
        </div>

        {/* Day guide from Rainbow Tours */}
        {day.guide && (
          <div className="section">
            <div className="section-head"><h3>Program dnia</h3></div>
            <p className="day-guide-text">{day.guide}</p>
          </div>
        )}

        {/* Weather card */}
        {wx && point && (
          <div className="section">
            <div className="section-head">
              <h3>{point.shortName}</h3>
              <button className="action" onClick={() => nav.push({ screen: 'weather' })}>
                Forecast <Icon name="chev" size={12} />
              </button>
            </div>
            <button onClick={() => nav.push({ screen: 'weather' })} style={{ width: '100%', margin: '0 -22px', padding: '0 22px' }}>
              <div className={`wx-card ${wx.code}`}>
                <div className="wc-top">
                  <div>
                    <div className="wc-loc">{point.shortName}</div>
                    <div className="wc-date">{day.dow} · {wx.summary}</div>
                  </div>
                  <div className="wc-glyph">{wxGlyph(wx.code)}</div>
                </div>
                <div className="wc-temp display">{wx.t_max}°</div>
                <div className="wc-range">H {wx.t_max}°  ·  L {wx.t_min}°  ·  Wind {wx.wind} km/h</div>
                <div className="wc-hint">
                  <div className="h">
                    <div className="h-label">Wear</div>
                    <div>{wx.clothing}</div>
                  </div>
                </div>
              </div>
            </button>
          </div>
        )}

        {/* Photo Quest tile */}
        {(() => {
          const todayId = pq.getTodayDayId();
          if (!todayId) return null;
          const s = pq.getDaySummary(todayId);
          return (
            <button className="pq-home-tile" onClick={() => nav.push({ screen: 'challenges' })}>
              <div className="pq-home-tile-ring">
                <ProgressRing pct={s.pct} size={48} stroke={4} />
                <div className="pq-home-tile-count">{s.filled}</div>
              </div>
              <div className="pq-home-tile-body">
                <div className="pq-home-tile-label">Photo Quest · Today</div>
                <div className="pq-home-tile-title">{s.filled === 20 ? 'Complete!' : `${s.filled} of 20 captured`}</div>
                <div className="pq-home-tile-sub">{20 - s.filled} shots remaining · tap to continue</div>
              </div>
              <div className="pq-home-tile-chev"><Icon name="chev" size={16} /></div>
            </button>
          );
        })()}

        {/* Quick actions */}
        <div className="section">
          <div className="section-head"><h3>Explore</h3></div>
          <div className="quick-grid">
            <button className="quick" onClick={() => nav.push({ screen: 'place', pointId: point?.id, tab: 'nearby' })}>
              <Icon name="nearby" /><span>Nearby</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'tips', pointId: point?.id })}>
              <Icon name="sparkle" /><span>Hidden eats</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'slang', pointId: point?.id })}>
              <Icon name="info" /><span>Slang</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'challenges' })}>
              <Icon name="heart" /><span>Family</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'flights' })}>
              <Icon name="flight" /><span>Flights</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'hotels' })}>
              <Icon name="hotel" /><span>Hotels</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'team' })}>
              <Icon name="team" /><span>Team</span>
            </button>
            <button className="quick" onClick={() => nav.push({ screen: 'docs' })}>
              <Icon name="doc" /><span>Documents</span>
            </button>
          </div>
        </div>

        {/* All days */}
        <div className="section">
          <div className="section-head">
            <h3>All 12 days</h3>
            <button className="action" onClick={() => nav.push({ screen: 'map' })}>
              Map <Icon name="chev" size={12} />
            </button>
          </div>
        </div>
        <div className="days-scroll">
          {window.DAYS.map((d) => {
            const p = window.primaryPointForDay(d);
            const img = d.hero || p?.images?.[0];
            const isToday = d.id === day.id;
            return (
              <button key={d.id} className={`day-tile ${isToday ? 'is-today' : ''}`}
                      onClick={() => p && nav.push({ screen: 'place', pointId: p.id })}>
                <div className="img" style={{ backgroundImage: img ? `url(${img.src})` : 'none' }}>
                  <div className="badge">{isToday ? 'Today' : `Day ${d.n}`}</div>
                </div>
                <div className="body">
                  <div className="place">{p?.shortName || '—'}</div>
                  <div className="date">{d.dow} · {d.date.slice(5)}</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------- MAP ----------
function MapScreen({ initialDay = null, initialPointId = null }) {
  const nav = useNav();
  const [activeDay, setActiveDay] = uS(initialDay);
  const [activePointId, setActivePointId] = uS(initialPointId);

  uE(() => {
    if (initialDay) {
      const d = window.DAYS.find((x) => x.id === initialDay);
      if (d && d.pointIds[0] && !activePointId) setActivePointId(d.pointIds[0]);
    }
  }, [initialDay]);

  const orderedPoints = uM(() => {
    const seen = new Set(); const out = [];
    window.DAYS.forEach((d) => d.pointIds.forEach((pid) => {
      if (!seen.has(pid)) { seen.add(pid); out.push(window.POINTS[pid]); }
    }));
    return out;
  }, []);

  const activePoint = activePointId ? window.POINTS[activePointId] : null;
  const activeWx = activePoint ? window.WEATHER[activePoint.id] : null;

  const visiblePoints = uM(() => {
    if (!activeDay) return orderedPoints;
    const d = window.DAYS.find((x) => x.id === activeDay);
    return d ? d.pointIds.map((id) => window.POINTS[id]).filter(Boolean) : orderedPoints;
  }, [activeDay, orderedPoints]);

  return (
    <div className="map-screen">
      <div className="map-canvas">
        <svg className="map-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
          <defs>
            <linearGradient id="mapbg2" x1="0" y1="0" x2="1" y2="1">
              <stop offset="0%" stopColor="oklch(94% 0.006 200)" />
              <stop offset="100%" stopColor="oklch(90% 0.006 200)" />
            </linearGradient>
          </defs>
          <rect width="100" height="100" fill="url(#mapbg2)" />
          {/* Simplified US landmass */}
          <path d="M 8 30 Q 6 28 8 26 L 14 22 L 22 20 L 32 19 L 44 19 L 58 19 L 72 20 L 82 22 L 88 25 L 92 30 L 94 36 L 93 42 L 92 48 L 94 52 L 95 58 L 92 62 L 88 66 L 82 68 L 74 72 L 66 74 L 58 74 L 50 74 L 42 74 L 34 72 L 26 70 L 20 68 L 14 64 L 10 58 L 6 50 L 5 42 L 6 34 Z"
                fill="oklch(97% 0.005 110)" stroke="oklch(82% 0.005 200)" strokeWidth="0.2" />
          {/* Route */}
          <polyline
            points={orderedPoints.map((p) => {
              const { x, y } = window.pointToMapXY(p);
              return `${x * 100},${y * 100}`;
            }).join(' ')}
            fill="none" stroke="oklch(62% 0.14 40)" strokeWidth="0.5"
            strokeDasharray="1.2 0.9" strokeLinecap="round" opacity="0.9"
          />
        </svg>
        {orderedPoints.map((p, i) => {
          const { x, y } = window.pointToMapXY(p);
          const isActive = p.id === activePointId;
          const visible = visiblePoints.some((vp) => vp.id === p.id);
          if (!visible) return null;
          return (
            <uF key={p.id}>
              <button className={`pin-v2${isActive ? ' active' : ''}`}
                      style={{ left: `${x * 100}%`, top: `${y * 100}%` }}
                      onClick={() => setActivePointId(p.id)}>
                <div className="p-shape">
                  <svg viewBox="0 0 26 33">
                    <path d="M13 0 C5.82 0 0 5.82 0 13 C0 22.5 13 33 13 33 C13 33 26 22.5 26 13 C26 5.82 20.18 0 13 0 Z"
                          fill={isActive ? 'oklch(62% 0.14 40)' : 'oklch(34% 0.08 230)'} />
                  </svg>
                </div>
                <div className="p-inner-num">{i + 1}</div>
              </button>
              {isActive && (
                <div className={`pin-label-v2 active`} style={{ left: `${x * 100}%`, top: `${y * 100 + 4.5}%` }}>
                  {p.shortName}
                </div>
              )}
            </uF>
          );
        })}
      </div>

      {/* Day chips */}
      <div className="day-chips">
        <button className={`day-chip${!activeDay ? ' active' : ''}`} onClick={() => { setActiveDay(null); setActivePointId(null); }}>
          All 12
        </button>
        {window.DAYS.map((d) => (
          <button key={d.id} className={`day-chip${activeDay === d.id ? ' active' : ''}`}
                  onClick={() => { setActiveDay(d.id); setActivePointId(d.pointIds[0]); }}>
            <span className="dn">D{d.n}</span>
            <span>{window.POINTS[d.pointIds[0]]?.shortName.split(' ')[0] || d.dow}</span>
          </button>
        ))}
      </div>

      {/* Back button */}
      <button onClick={() => nav.back()} style={{
        position: 'absolute', top: 48, left: 14, zIndex: 25,
        width: 40, height: 40, borderRadius: '50%',
        background: 'oklch(100% 0 0 / 0.95)', backdropFilter: 'blur(16px)',
        border: '0.5px solid var(--line)', boxShadow: 'var(--sh-sm)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name="back" size={18} />
      </button>

      {/* Sheet */}
      {activePoint ? (
        <div className="sheet">
          <div className="sheet-handle" />
          <div className="sheet-hero" onClick={() => activePoint.images[0] && window.__lightbox(activePoint.images, 0)}>
            {activePoint.images?.[0] && <img src={activePoint.images[0].src} alt={activePoint.images[0].alt} />}
          </div>
          <div className="sheet-body">
            <div className="sheet-title display">{activePoint.name}</div>
            <div className="sheet-meta">{activePoint.region} · {activePoint.coords.lat.toFixed(2)}, {activePoint.coords.lng.toFixed(2)}</div>
            {activeWx && (
              <div className="sheet-weather">
                <span className="gly">{wxGlyph(activeWx.code)}</span>
                <span className="temps">{activeWx.t_min}° / {activeWx.t_max}°</span>
                <span className="summ">· {activeWx.summary}</span>
              </div>
            )}
            <div className="sheet-actions">
              <button className="sa-btn primary" onClick={() => nav.push({ screen: 'place', pointId: activePoint.id })}>
                Open place
              </button>
              <button className="sa-btn" onClick={() => window.open(activePoint.mapsUrl, '_blank')}>
                <Icon name="directions" size={14} /> Directions
              </button>
              <button className="sa-btn icon-only" onClick={() => nav.push({ screen: 'weather' })}>
                <Icon name="weather" size={14} />
              </button>
              <button className="sa-btn icon-only" onClick={() => nav.push({ screen: 'place', pointId: activePoint.id, tab: 'nearby' })}>
                <Icon name="nearby" size={14} />
              </button>
            </div>
            {activePoint.highlights?.length > 0 && (
              <div>
                <div className="mono" style={{ marginBottom: 8 }}>Highlights</div>
                <div className="highlights">
                  {activePoint.highlights.map((h, i) => <span key={i} className="highlight-chip">{h}</span>)}
                </div>
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="sheet" style={{ maxHeight: 120 }}>
          <div className="sheet-handle" />
          <div style={{ padding: '0 24px 20px', textAlign: 'center' }}>
            <div style={{ fontSize: 13, color: 'var(--ink-3)', fontWeight: 500 }}>Tap a pin or pick a day above to focus</div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { HomeScreen, MapScreen });
