
// RMTCTRL Web App — New screens: Accommodation, What's On, Remote Jobs, Location Info

// ── Accommodation photo component ─────────────────────────────────────────────
// With GOOGLE_PLACES_KEY: fetches real listing photos via Places API.
// Without key: uses curated Unsplash photos per listing type (no API required).
// On any image error: gracefully falls back to the branded gradient placeholder.
const LISTING_UNSPLASH_PHOTOS = {
  'Selina Chiado':         ['photo-1555881400-74d7acaacd8b', 'photo-1497366216548-37526070297c', 'photo-1522708323590-d24dbb6b0267', 'photo-1555881400-74d7acaacd8b', 'photo-1497366216548-37526070297c', 'photo-1522708323590-d24dbb6b0267'],
  'The Independent Hotel': ['photo-1566073771259-6a8506099945', 'photo-1445019980597-93fa8acb246c', 'photo-1582719508461-905c673536f4', 'photo-1566073771259-6a8506099945', 'photo-1445019980597-93fa8acb246c', 'photo-1582719508461-905c673536f4'],
  'NomadX Apartments':     ['photo-1522708323590-d24dbb6b0267', 'photo-1493809842364-78817add7ffb', 'photo-1502672260266-1c1ef2d93688', 'photo-1522708323590-d24dbb6b0267', 'photo-1493809842364-78817add7ffb', 'photo-1502672260266-1c1ef2d93688'],
  'LX Hostel & Co':        ['photo-1578683010236-d716f9a3f461', 'photo-1555854877634-1dc0f68f66c4', 'photo-1595433707802-40e5bfbd05a7', 'photo-1578683010236-d716f9a3f461', 'photo-1555854877634-1dc0f68f66c4', 'photo-1595433707802-40e5bfbd05a7'],
  'Casa da Saudade':       ['photo-1554995207-c18c203602cb', 'photo-1416339306562-f3d12fefd36f', 'photo-1484154218962-a197022b5858', 'photo-1554995207-c18c203602cb', 'photo-1416339306562-f3d12fefd36f', 'photo-1484154218962-a197022b5858'],
  'Ericeira Surf & Work':  ['photo-1502877338535-766e1452684a', 'photo-1505118380757-91f5f5632de0', 'photo-1519046904884-53103b34b206', 'photo-1502877338535-766e1452684a', 'photo-1505118380757-91f5f5632de0', 'photo-1519046904884-53103b34b206'],
};

function AccommodationPhoto({ listing, index = 0, height = 130, borderRadius = 0, style = {} }) {
  const [imgSrc, setImgSrc] = React.useState(null);
  const [placesPhotos, setPlacesPhotos] = React.useState(null);
  const [imgError, setImgError] = React.useState(false);
  const emojiMap = { Hotel: '🏨', Coliving: '🏢', Hostel: '🛏️', Airbnb: '🏡', 'Serviced Apt': '🏠' };
  const fallbackEmoji = emojiMap[listing.type] || '🏠';

  React.useEffect(() => {
    setImgError(false);
    setImgSrc(null);
    setPlacesPhotos(null);

    if (typeof GOOGLE_PLACES_KEY !== 'undefined' && GOOGLE_PLACES_KEY) {
      // Google Places Text Search → get place_id, then Photos endpoint
      const query = encodeURIComponent(`${listing.name} ${listing.city}`);
      fetch(`https://maps.googleapis.com/maps/api/place/textsearch/json?query=${query}&key=${GOOGLE_PLACES_KEY}`)
        .then(r => r.json())
        .then(data => {
          const photos = data.results?.[0]?.photos;
          if (photos?.length) {
            const refs = photos.slice(0, 6).map(p =>
              `https://maps.googleapis.com/maps/api/place/photo?maxwidth=600&photoreference=${p.photo_reference}&key=${GOOGLE_PLACES_KEY}`
            );
            setPlacesPhotos(refs);
            setImgSrc(refs[Math.min(index, refs.length - 1)]);
          } else {
            useUnsplash();
          }
        })
        .catch(() => useUnsplash());
    } else {
      useUnsplash();
    }

    function useUnsplash() {
      const photos = LISTING_UNSPLASH_PHOTOS[listing.name];
      if (photos) {
        setImgSrc(`https://images.unsplash.com/${photos[index % photos.length]}?w=600&q=75&auto=format&fit=crop`);
      }
    }
  }, [listing.name, index]);

  // Fallback gradient if image fails to load or no source found
  if (imgError || !imgSrc) {
    return (
      <div style={{ height, background: `linear-gradient(135deg, ${listing.color}22, ${listing.color}55)`, borderRadius, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 48, ...style }}>
        {fallbackEmoji}
      </div>
    );
  }

  return (
    <img
      src={imgSrc}
      alt={listing.name}
      onError={() => setImgError(true)}
      style={{ height, width: '100%', objectFit: 'cover', borderRadius, display: 'block', ...style }}
      loading="lazy"
    />
  );
}

// ── Accommodation ─────────────────────────────────────────────────────────────
function AccommodationScreen() {
  const [query, setQuery] = React.useState('');
  const [saved, setSaved] = useLocalStorage('rmt:accom:saved', []);
  const [activeFilters, setActiveFilters] = useLocalStorage('rmt:accom:filters', ['All']);
  const [sortBy, setSortBy] = useLocalStorage('rmt:accom:sortBy', 'recommended');
  const [showSavedOnly, setShowSavedOnly] = useLocalStorage('rmt:accom:savedOnly', false);
  const [selectedCard, setSelectedCard] = React.useState(null);
  const [tab, setTab] = React.useState('Details');

  const typeFilters = ['All', 'Hotel', 'Coliving', 'Hostel', 'Airbnb', 'Serviced Apt'];
  const amenityFilters = ['Fast Wi-Fi', 'Kitchen', 'Workspace', 'Pool', 'Gym', '24/7 Desk'];

  const toggleFilter = (f) => {
    if (f === 'All') { setActiveFilters(['All']); return; }
    setActiveFilters(prev => {
      const without = prev.filter(x => x !== 'All');
      return without.includes(f) ? (without.filter(x => x !== f).length ? without.filter(x => x !== f) : ['All']) : [...without, f];
    });
  };

  const listings = [
    { name: 'Selina Chiado', type: 'Coliving', city: 'Lisbon', price: 42, per: 'night', rating: 4.6, reviews: 128, wifi: '85 Mbps', amenities: ['Fast Wi-Fi', 'Kitchen', 'Pool', 'Workspace'], badge: 'POPULAR', color: TOKENS.color.accent, desc: 'Community-first coliving in the heart of Lisbon. Private rooms and dorms. Rooftop pool and coworking included.' },
    { name: 'The Independent Hotel', type: 'Hotel', city: 'Lisbon', price: 89, per: 'night', rating: 4.8, reviews: 310, wifi: '72 Mbps', amenities: ['Fast Wi-Fi', 'Gym', '24/7 Desk'], badge: 'TOP RATED', color: TOKENS.color.info, desc: 'Boutique hotel in São Pedro de Alcântara. Stunning views, concierge service and fast fiber Wi-Fi throughout.' },
    { name: 'NomadX Apartments', type: 'Serviced Apt', city: 'Lisbon', price: 65, per: 'night', rating: 4.4, reviews: 57, wifi: '120 Mbps', amenities: ['Fast Wi-Fi', 'Kitchen', 'Workspace'], badge: 'NOMAD PICK', color: TOKENS.color.purple, desc: 'Fully-furnished serviced apartments designed for remote workers. Monthly discounts available. Standing desks in every room.' },
    { name: 'LX Hostel & Co', type: 'Hostel', city: 'Lisbon', price: 28, per: 'night', rating: 4.2, reviews: 203, wifi: '55 Mbps', amenities: ['Fast Wi-Fi', 'Kitchen'], badge: null, color: TOKENS.color.warn, desc: 'Social hostel near LX Factory. Private rooms from €28. Strong community vibe and weekly events for nomads.' },
    { name: 'Casa da Saudade', type: 'Airbnb', city: 'Lisbon', price: 74, per: 'night', rating: 4.9, reviews: 44, wifi: '95 Mbps', amenities: ['Fast Wi-Fi', 'Kitchen', 'Workspace'], badge: 'SUPERHOST', color: TOKENS.color.error, desc: 'Entire apartment in Mouraria. Dedicated work desk, ultrafast fiber, walking distance to all co-working spaces.' },
    { name: 'Ericeira Surf & Work', type: 'Coliving', city: 'Ericeira', price: 55, per: 'night', rating: 4.7, reviews: 89, wifi: '90 Mbps', amenities: ['Fast Wi-Fi', 'Kitchen', 'Pool', 'Workspace', 'Gym'], badge: 'NEW', color: TOKENS.color.accent, desc: '45 min from Lisbon. Surf in the morning, work in the afternoon. World Surf Reserve + reliable gigabit Wi-Fi.' },
  ];

  const toggleSave = (i, e) => { e.stopPropagation(); setSaved(prev => prev.includes(i) ? prev.filter(x => x !== i) : [...prev, i]); };

  const filtered = listings.filter(l => {
    // Type filters are OR within the group; amenity filters are AND within the group; the two groups combine with AND
    const selectedTypes = activeFilters.filter(f => typeFilters.slice(1).includes(f)); // exclude 'All'
    const selectedAmenities = activeFilters.filter(f => amenityFilters.includes(f));
    const matchesType = activeFilters.includes('All') || selectedTypes.length === 0 || selectedTypes.some(f => l.type === f);
    const matchesAmenities = selectedAmenities.every(f => l.amenities.includes(f));
    const matchesSearch = !query || l.name.toLowerCase().includes(query.toLowerCase()) || l.city.toLowerCase().includes(query.toLowerCase());
    const matchesSaved = !showSavedOnly || saved.includes(listings.indexOf(l));
    return matchesType && matchesAmenities && matchesSearch && matchesSaved;
  });

  const sorted = [...filtered].sort((a, b) => {
    if (sortBy === 'price-low')  return a.price - b.price;
    if (sortBy === 'price-high') return b.price - a.price;
    if (sortBy === 'rating')     return b.rating - a.rating;
    if (sortBy === 'wifi')       return parseInt(b.wifi) - parseInt(a.wifi);
    return 0;
  });

  const sel = selectedCard !== null ? listings[selectedCard] : null;
  const emoji = (t) => t === 'Hotel' ? '🏨' : t === 'Coliving' ? '🏢' : t === 'Hostel' ? '🛏️' : t === 'Airbnb' ? '🏡' : '🏠';

  const openDetail = (idx) => { setSelectedCard(idx); setTab('Details'); };

  return (
    <div style={{ flex: 1, position: 'relative', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Filters bar */}
      <div style={{ padding: '14px 32px 12px', borderBottom: '1px solid #26262E', display: 'flex', flexDirection: 'column', gap: 10, flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 8 }}>
          <div style={{ flex: 1, display: 'flex', gap: 8, height: 40, background: TOKENS.color.surface2, borderRadius: 10, alignItems: 'center', padding: '0 14px' }}>
            <SearchIcon size={16} />
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search city, name or type…" style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textPrimary }} />
          </div>
          <button onClick={() => setShowSavedOnly(s => !s)} style={{ height: 40, padding: '0 14px', borderRadius: 10, border: `1px solid ${showSavedOnly ? TOKENS.color.accent : TOKENS.color.border}`, background: showSavedOnly ? 'rgba(0,255,148,0.1)' : 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
            <HeartIcon size={14} filled={showSavedOnly} color={showSavedOnly ? TOKENS.color.accent : TOKENS.color.textSecondary} />
            <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, color: showSavedOnly ? TOKENS.color.accent : TOKENS.color.textSecondary, fontWeight: showSavedOnly ? 600 : 400 }}>Saved only</span>
          </button>
          <select value={sortBy} onChange={e => setSortBy(e.target.value)} style={{ background: TOKENS.color.surface2, border: '1px solid #26262E', borderRadius: 10, padding: '0 14px', fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textPrimary, outline: 'none', cursor: 'pointer' }}>
            <option value="recommended">Recommended</option>
            <option value="price-low">Price: Low to High</option>
            <option value="price-high">Price: High to Low</option>
            <option value="rating">Highest Rated</option>
            <option value="wifi">Fastest Wi-Fi</option>
          </select>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {typeFilters.map(f => <FilterChip key={f} label={f} selected={activeFilters.includes(f)} onClick={() => toggleFilter(f)} />)}
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
          {amenityFilters.map(f => <FilterChip key={f} label={f} selected={activeFilters.includes(f)} onClick={() => toggleFilter(f)} />)}
          <span style={{ marginLeft: 'auto', fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.06em' }}>{filtered.length} LISTINGS</span>
        </div>
      </div>

      {/* Full-width grid of listings */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 32px' }}>
        {sorted.length === 0 ? (
          <EmptyState
            icon={<SearchIcon size={48} />}
            headline="No listings match"
            sub="Try a different search or clear the filters"
            cta="Clear filters"
            onCta={() => { setQuery(''); setActiveFilters(['All']); setShowSavedOnly(false); }}
          />
        ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(min(320px, 100%), 1fr))', gap: 16 }}>
          {sorted.map((listing, i) => {
            const idx = listings.indexOf(listing);
            const isSaved = saved.includes(idx);
            return (
              <Card key={i} onClick={() => openDetail(idx)} style={{ padding: 0, overflow: 'hidden', cursor: 'pointer', display: 'flex', flexDirection: 'column' }}>
                <div style={{ height: 130, position: 'relative', overflow: 'hidden' }}>
                  <AccommodationPhoto listing={listing} index={0} height={130} />
                  {listing.badge && (
                    <span style={{ position: 'absolute', top: 12, left: 12, background: `${listing.color}dd`, color: '#fff', fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 700, padding: '3px 8px', borderRadius: 999, letterSpacing: '0.06em', backdropFilter: 'blur(4px)' }}>{listing.badge}</span>
                  )}
                  <button onClick={e => toggleSave(idx, e)} style={{ position: 'absolute', top: 10, right: 10, width: 32, height: 32, borderRadius: '50%', background: 'rgba(10,10,11,0.6)', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}>
                    <HeartIcon size={16} filled={isSaved} color={isSaved ? TOKENS.color.accent : TOKENS.color.textPrimary} />
                  </button>
                </div>
                <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 15, fontWeight: 700, color: TOKENS.color.textPrimary, marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{listing.name}</div>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{listing.type} · {listing.city}</div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 16, fontWeight: 600, color: TOKENS.color.textPrimary }}>€{listing.price}</div>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 10, color: TOKENS.color.textSecondary }}>per {listing.per}</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 3 }}>
                      <StarIcon size={12} filled={true} color="#FFB800" />
                      <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.warn, fontWeight: 600 }}>{listing.rating}</span>
                      <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textTertiary }}>({listing.reviews})</span>
                    </div>
                    <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.accent }}>{listing.wifi}</span>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
        )}
      </div>

      {/* Slide-out detail with tabs */}
      <SlideOutPanel isOpen={sel !== null} onClose={() => setSelectedCard(null)}>
        {sel && (
          <>
            {/* Hero photo — real photo when available, DetailHero gradient fallback */}
            <div style={{ position: 'relative', height: 160, overflow: 'hidden', flexShrink: 0 }}>
              <AccommodationPhoto listing={sel} index={0} height={160} />
              <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to bottom, transparent 40%, rgba(10,10,11,0.85))' }} />
              {sel.badge && (
                <span style={{ position: 'absolute', top: 14, left: 16, background: `${sel.color}dd`, color: '#fff', fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 700, padding: '3px 10px', borderRadius: 999, letterSpacing: '0.06em', backdropFilter: 'blur(4px)' }}>{sel.badge}</span>
              )}
              <button onClick={() => setSelectedCard(null)} style={{ position: 'absolute', top: 12, right: 12, width: 32, height: 32, borderRadius: '50%', background: 'rgba(10,10,11,0.6)', border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: TOKENS.color.textPrimary, backdropFilter: 'blur(4px)' }}>✕</button>
            </div>

            {/* Title + price */}
            <div style={{ padding: '18px 24px 0', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
              <div>
                <h2 style={{ fontFamily: "'Inter',sans-serif", fontSize: 22, fontWeight: 700, color: TOKENS.color.textPrimary, margin: '0 0 4px' }}>{sel.name}</h2>
                <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textSecondary }}>{sel.type} · {sel.city}</span>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 24, fontWeight: 600, color: TOKENS.color.textPrimary }}>€{sel.price}</div>
                <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textSecondary }}>per night</div>
              </div>
            </div>

            {/* Stats row */}
            <div style={{ padding: '16px 24px' }}>
              <DetailStatsGrid valueSize={15} stats={[
                { label: 'RATING', val: `${sel.rating}/5`, color: TOKENS.color.warn },
                { label: 'WI-FI', val: sel.wifi, color: TOKENS.color.accent },
                { label: 'REVIEWS', val: sel.reviews, color: TOKENS.color.textPrimary },
              ]} />
            </div>

            <DetailTabs tabs={['Map', 'Details', 'Nearby', 'Flights']} active={tab} onChange={setTab} />

            <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
              {tab === 'Map' && (
                <div style={{ height: 360, background: 'linear-gradient(160deg,#0D1117 0%,#111827 60%,#0A0F1A 100%)', borderRadius: 12, position: 'relative', overflow: 'hidden', border: '1px solid #26262E' }}>
                  <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.08 }}>
                    <defs><pattern id="acc-grid" width="40" height="40" patternUnits="userSpaceOnUse"><path d="M 40 0 L 0 0 0 40" fill="none" stroke="#F5F5F7" strokeWidth="0.5"/></pattern></defs>
                    <rect width="100%" height="100%" fill="url(#acc-grid)"/>
                  </svg>
                  <div style={{ position: 'absolute', top: '45%', left: '50%', transform: 'translate(-50%,-50%)' }}>
                    <div style={{ width: 28, height: 28, borderRadius: '50% 50% 50% 0', transform: 'rotate(-45deg)', background: sel.color, boxShadow: `0 0 20px ${sel.color}88` }} />
                  </div>
                  <div style={{ position: 'absolute', bottom: 12, right: 12, background: 'rgba(10,10,11,0.8)', borderRadius: 8, padding: '6px 12px', fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>
                    {sel.city}
                  </div>
                </div>
              )}

              {tab === 'Details' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                  <div>
                    <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 8 }}>ABOUT</div>
                    <p style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textSecondary, lineHeight: 1.65, margin: 0 }}>{sel.desc}</p>
                  </div>

                  {/* Image gallery */}
                  <div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>IMAGES</div>
                      {(typeof GOOGLE_PLACES_KEY === 'undefined' || !GOOGLE_PLACES_KEY) && (
                        <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 10, color: TOKENS.color.textTertiary }}>Add GOOGLE_PLACES_KEY for live photos</span>
                      )}
                    </div>
                    {/* Hero image */}
                    <div style={{ borderRadius: 10, overflow: 'hidden', marginBottom: 6 }}>
                      <AccommodationPhoto listing={sel} index={0} height={200} />
                    </div>
                    {/* 2×2 gallery grid */}
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                      {[1, 2, 3, 4].map(n => (
                        <div key={n} style={{ borderRadius: 8, overflow: 'hidden' }}>
                          <AccommodationPhoto listing={sel} index={n} height={90} />
                        </div>
                      ))}
                    </div>
                  </div>

                  <div>
                    <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 8 }}>AMENITIES</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                      {sel.amenities.map(a => (
                        <div key={a} style={{ display: 'flex', alignItems: 'center', gap: 6, background: TOKENS.color.surface, border: '1px solid #26262E', borderRadius: 8, padding: '6px 12px' }}>
                          <CheckIcon size={12} color="#00FF94" />
                          <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textPrimary }}>{a}</span>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div style={{ display: 'flex', gap: 10 }}>
                    {['Check-in', 'Check-out'].map(label => (
                      <div key={label} style={{ flex: 1, background: TOKENS.color.surface2, borderRadius: 12, border: '1.5px solid #26262E', padding: '10px 14px' }}>
                        <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textSecondary, marginBottom: 4 }}>{label}</div>
                        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 13, color: TOKENS.color.textPrimary }}>{label === 'Check-in' ? '02 MAY 2025' : '16 MAY 2025'}</div>
                      </div>
                    ))}
                    <div style={{ background: TOKENS.color.surface2, borderRadius: 12, border: '1.5px solid #26262E', padding: '10px 14px', minWidth: 70, textAlign: 'center' }}>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textSecondary, marginBottom: 4 }}>Nights</div>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 13, color: TOKENS.color.textPrimary }}>14</div>
                    </div>
                  </div>

                  <Card style={{ padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 16 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary, marginBottom: 2 }}>Total for 14 nights</div>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 22, fontWeight: 600, color: TOKENS.color.textPrimary }}>€{sel.price * 14}</div>
                    </div>
                    <Btn variant="primary" size="md" onClick={() => toast(`Booking confirmed · ${sel.name}`)}>Book now</Btn>
                  </Card>
                </div>
              )}

              {tab === 'Nearby' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>WORKSPACES</div>
                  {[
                    { name: 'Hub Lisbon', dist: '230m', wifi: '78 Mbps' },
                    { name: 'Selina CoWork', dist: '950m', wifi: '56 Mbps' },
                    { name: 'Dear Breakfast', dist: '480m', wifi: '34 Mbps' },
                  ].map(p => (
                    <Card key={p.name} style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 8, background: TOKENS.color.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>💻</div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 600, color: TOKENS.color.textPrimary }}>{p.name}</div>
                        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.textSecondary }}>{p.dist} · {p.wifi}</div>
                      </div>
                      <ChevronRightIcon size={14} />
                    </Card>
                  ))}
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginTop: 6 }}>FOOD & COFFEE</div>
                  {[
                    { name: 'Time Out Market', dist: '320m' },
                    { name: 'Pastéis de Belém', dist: '2.4km' },
                  ].map(p => (
                    <Card key={p.name} style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12 }}>
                      <div style={{ width: 36, height: 36, borderRadius: 8, background: TOKENS.color.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>🍽️</div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 600, color: TOKENS.color.textPrimary }}>{p.name}</div>
                        <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.textSecondary }}>{p.dist}</div>
                      </div>
                      <ChevronRightIcon size={14} />
                    </Card>
                  ))}
                </div>
              )}

              {tab === 'Flights' && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>UPCOMING ARRIVALS</div>
                  {[
                    { route: `SYD → ${sel.city.slice(0, 3).toUpperCase()}`, code: 'QF1', date: '02 MAY · 06:00 → 22:30', price: '€1,210' },
                    { route: `LHR → ${sel.city.slice(0, 3).toUpperCase()}`, code: 'BA492', date: '04 MAY · 08:15 → 10:45', price: '€86' },
                    { route: `CDG → ${sel.city.slice(0, 3).toUpperCase()}`, code: 'AF1124', date: '06 MAY · 11:20 → 12:55', price: '€72' },
                  ].map(f => (
                    <Card key={f.code} style={{ padding: '14px 16px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                        <PlaneIcon size={18} color="#9999A1" />
                        <div style={{ flex: 1 }}>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600, color: TOKENS.color.textPrimary }}>{f.route} · {f.code}</div>
                          <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.textSecondary, marginTop: 2 }}>{f.date}</div>
                        </div>
                        <MonoText size={14} weight={600} color="#FFB800">{f.price}</MonoText>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </div>
          </>
        )}
      </SlideOutPanel>
    </div>
  );
}

// ── What's On ─────────────────────────────────────────────────────────────────
function WhatsOnScreen() {
  const [filter, setFilter] = useLocalStorage('rmt:whatson:typeFilter', 'All');
  const [cityFilter, setCityFilter] = useLocalStorage('rmt:whatson:cityFilter', 'All cities');
  const [rsvpd, setRsvpd] = useLocalStorage('rmt:whatson:rsvpd', []);
  const typeFilters = ['All', 'Meetup', 'Conference', 'Workshop', 'Co-working Day', 'Social'];
  const cities = ['All cities', 'Lisbon', 'Barcelona', 'Berlin', 'Bali', 'Tokyo', 'Bangkok'];
  const typeColors = { Meetup: TOKENS.color.accent, Conference: TOKENS.color.info, Workshop: TOKENS.color.purple, 'Co-working Day': TOKENS.color.warn, Social: TOKENS.color.error };

  const events = [
    { type: 'Meetup', title: 'Lisbon Digital Nomad Meetup', city: 'Lisbon', date: 'Thu 8 May · 19:00', loc: 'Hub Lisbon, Chiado', desc: 'Monthly gathering of remote workers and nomads in Lisbon. Talks, networking and drinks. All welcome.', attendees: 47, capacity: 80, free: true, tags: ['Networking', 'Community'] },
    { type: 'Conference', title: 'Nomad Summit Europe', city: 'Lisbon', date: 'Fri 9 – Sat 10 May', loc: 'LX Factory, Alcântara', desc: '2-day conference for location-independent professionals. 20+ speakers, workshops and a full nomad expo.', attendees: 320, capacity: 500, price: '€89', tags: ['Conference', 'Speakers', 'Expo'] },
    { type: 'Workshop', title: 'Legal for Nomads: NHR & Visas', city: 'Lisbon', date: 'Mon 12 May · 10:00', loc: 'Online + Selina Chiado', desc: "Everything you need to know about Portugal's NHR tax regime, D8 Digital Nomad Visa and freelance setup.", attendees: 28, capacity: 40, price: '€15', tags: ['Legal', 'Taxes', 'Visa'] },
    { type: 'Co-working Day', title: 'Nomad Day @ Ericeira', city: 'Lisbon', date: 'Sat 17 May · 09:00', loc: 'Ericeira Surf House', desc: 'Day trip to Ericeira. Surf in the morning, work in the afternoon, bonfire in the evening. Bus from Lisbon included.', attendees: 22, capacity: 30, price: '€35', tags: ['Surf', 'Co-working', 'Day trip'] },
    { type: 'Social', title: 'Remote Workers Rooftop Drinks', city: 'Lisbon', date: 'Fri 16 May · 18:30', loc: 'Park Bar, Bairro Alto', desc: 'Casual drinks on one of Lisbon\'s best rooftops. No agenda, just good people and great views.', attendees: 61, capacity: 100, free: true, tags: ['Social', 'Drinks'] },
    { type: 'Workshop', title: 'Figma for Non-Designers', city: 'Barcelona', date: 'Wed 14 May · 14:00', loc: 'Betahaus, Eixample', desc: "Practical workshop for developers and PMs who want to get comfortable with Figma. Laptops required.", attendees: 15, capacity: 20, price: '€20', tags: ['Design', 'Tools'] },
    { type: 'Meetup', title: 'Tech & Coffee BCN', city: 'Barcelona', date: 'Tue 13 May · 09:00', loc: 'Federal Café, Eixample', desc: 'Casual morning meetup for tech nomads. BYO laptop, share what you\'re building.', attendees: 19, capacity: 30, free: true, tags: ['Tech', 'Morning'] },
    { type: 'Conference', title: 'Remote Work Summit Asia', city: 'Bangkok', date: 'Sat 24 May · 09:00', loc: 'HUBBA-TO, Thonglor', desc: 'Annual summit bringing together SE Asia\'s remote work community. Deep dives on async culture, tools and freedom.', attendees: 180, capacity: 300, price: '฿1,500', tags: ['Asia', 'Async', 'Culture'] },
  ];

  const filtered = events.filter(e => {
    const matchType = filter === 'All' || e.type === filter;
    const matchCity = cityFilter === 'All cities' || e.city === cityFilter;
    return matchType && matchCity;
  });

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Filter bar */}
      <div style={{ padding: '16px 28px 12px', borderBottom: '1px solid #26262E', display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {typeFilters.map(f => <FilterChip key={f} label={f} selected={filter === f} onClick={() => setFilter(f)} />)}
        </div>
        <div style={{ width: 1, height: 24, background: TOKENS.color.border, flexShrink: 0 }} />
        <select value={cityFilter} onChange={e => setCityFilter(e.target.value)} style={{ background: TOKENS.color.surface2, border: '1px solid #26262E', borderRadius: 8, padding: '6px 12px', fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textPrimary, outline: 'none', cursor: 'pointer' }}>
          {cities.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
        <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.06em', marginLeft: 'auto' }}>{filtered.length} EVENTS</span>
      </div>

      {/* Event cards grid */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '24px 28px' }}>
        {filtered.length === 0 ? (
          <EmptyState
            icon={<CalendarIcon size={48} />}
            headline="No events match"
            sub="Try a different type or city"
            cta="Show all"
            onCta={() => { setFilter('All'); setCityFilter('All cities'); }}
          />
        ) : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(min(320px, 100%), 1fr))', gap: 16 }}>
          {filtered.map((ev, i) => {
            const typeColor = typeColors[ev.type] || TOKENS.color.textSecondary;
            const isRsvpd = rsvpd.includes(i);
            const pctFull = (ev.attendees / ev.capacity) * 100;
            return (
              <Card key={i} style={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
                {/* Color stripe */}
                <div style={{ height: 4, background: `linear-gradient(90deg, ${typeColor}, ${typeColor}66)` }} />
                <div style={{ padding: '18px 20px', display: 'flex', flexDirection: 'column', gap: 12, flex: 1 }}>
                  {/* Header */}
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10 }}>
                    <div style={{ flex: 1 }}>
                      <span style={{ background: `${typeColor}18`, color: typeColor, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999, letterSpacing: '0.06em', display: 'inline-block', marginBottom: 8 }}>{ev.type.toUpperCase()}</span>
                      <h3 style={{ fontFamily: "'Inter',sans-serif", fontSize: 16, fontWeight: 700, color: TOKENS.color.textPrimary, margin: '0 0 4px', lineHeight: 1.3 }}>{ev.title}</h3>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{ev.city}</div>
                    </div>
                    <div style={{ textAlign: 'right', flexShrink: 0 }}>
                      {ev.free ? (
                        <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 13, fontWeight: 600, color: TOKENS.color.accent }}>FREE</span>
                      ) : (
                        <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 14, fontWeight: 600, color: TOKENS.color.textPrimary }}>{ev.price}</span>
                      )}
                    </div>
                  </div>

                  {/* Date + loc */}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                      <CalendarIcon size={13} color="#5C5C66" />
                      <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 12, color: TOKENS.color.textSecondary }}>{ev.date}</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                      <MapPinIcon size={13} color="#5C5C66" />
                      <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{ev.loc}</span>
                    </div>
                  </div>

                  {/* Description */}
                  <p style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textSecondary, lineHeight: 1.6, margin: 0 }}>{ev.desc}</p>

                  {/* Tags */}
                  <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                    {ev.tags.map(t => (
                      <span key={t} style={{ background: TOKENS.color.surface2, border: '1px solid #26262E', borderRadius: 999, padding: '3px 8px', fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textSecondary }}>{t}</span>
                    ))}
                  </div>

                  {/* Attendance */}
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                      <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{ev.attendees} going · {ev.capacity - ev.attendees} spots left</span>
                      {pctFull > 80 && <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.warn }}>FILLING UP</span>}
                    </div>
                    <div style={{ height: 3, background: TOKENS.color.border, borderRadius: 999, overflow: 'hidden' }}>
                      <div style={{ width: `${pctFull}%`, height: '100%', background: pctFull > 80 ? TOKENS.color.warn : typeColor, borderRadius: 999, transition: `width ${TOKENS.anim.slower} ease` }} />
                    </div>
                  </div>

                  {/* CTA */}
                  <button onClick={() => setRsvpd(prev => isRsvpd ? prev.filter(x => x !== i) : [...prev, i])} style={{
                    height: 40, borderRadius: 10, border: `1px solid ${isRsvpd ? TOKENS.color.accent : TOKENS.color.border}`,
                    background: isRsvpd ? 'rgba(0,255,148,0.1)' : typeColor === TOKENS.color.accent ? TOKENS.color.accent : 'transparent',
                    cursor: 'pointer', fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600,
                    color: isRsvpd ? TOKENS.color.accent : typeColor === TOKENS.color.accent ? TOKENS.color.bg : TOKENS.color.textPrimary,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, transition: `all ${TOKENS.anim.fast}`,
                  }}>
                    {isRsvpd ? <><CheckIcon size={14} color="#00FF94" /> RSVP'd</> : `RSVP${ev.free ? ' (Free)' : ''}`}
                  </button>
                </div>
              </Card>
            );
          })}
        </div>
        )}
      </div>
    </div>
  );
}

// ── Remote Jobs Board ─────────────────────────────────────────────────────────
function RemoteJobsScreen() {
  const vw = useViewportWidth();
  const isMobile = vw < 768;
  const [query, setQuery] = React.useState('');
  const [typeFilter, setTypeFilter] = useLocalStorage('rmt:jobs:typeFilter', 'All');
  const [catFilter, setCatFilter] = useLocalStorage('rmt:jobs:catFilter', 'All');
  const [saved, setSaved] = useLocalStorage('rmt:jobs:saved', []);
  const [statuses, setStatuses] = useLocalStorage('rmt:jobs:statuses', {});
  const [salaryMin, setSalaryMin] = useLocalStorage('rmt:jobs:salaryMin', 0);
  const [selectedJob, setSelectedJob] = React.useState(null);
  const SALARY_OPTIONS = [
    { label: 'Any salary', val: 0 },
    { label: '$50k+', val: 50000 },
    { label: '$80k+', val: 80000 },
    { label: '$120k+', val: 120000 },
    { label: '$160k+', val: 160000 },
  ];
  const STATUS_COLORS = { Saved: TOKENS.color.textSecondary, Applied: TOKENS.color.info, Interviewing: TOKENS.color.warn, Offer: TOKENS.color.accent, Rejected: TOKENS.color.error };
  const STATUS_OPTIONS = ['Applied', 'Interviewing', 'Offer', 'Rejected'];
  const setJobStatus = (idx, s) => setStatuses(prev => { const next = {...prev}; if (s) next[idx] = s; else delete next[idx]; return next; });
  const types = ['All', 'Full-time', 'Part-time', 'Contract', 'Freelance'];
  const cats = ['All', 'Engineering', 'Design', 'Marketing', 'Product', 'Writing', 'Support', 'Finance'];
  const tzColors = { 'Any': TOKENS.color.accent, 'Americas': TOKENS.color.info, 'EMEA': TOKENS.color.purple, 'APAC': TOKENS.color.warn };

  const jobs = [
    { title: 'Senior Full-Stack Engineer', company: 'Loom', cat: 'Engineering', type: 'Full-time', salary: '$130k – $160k', tz: 'Any', posted: '2h ago', tags: ['React', 'Node.js', 'PostgreSQL'], desc: "Build the core product experience for Loom's async video platform. We're fully remote and async-first. You'll work across the full stack, ship independently and own significant product areas.", perks: ['Unlimited PTO', 'Home office stipend', 'Health insurance', '$3k learning budget'] },
    { title: 'Product Designer', company: 'Linear', cat: 'Design', type: 'Full-time', salary: '$120k – $150k', tz: 'EMEA', posted: '5h ago', tags: ['Figma', 'Product design', 'Systems'], desc: "Design the future of project management software. Linear is obsessed with quality and speed. You'll work directly with the founders to shape every pixel of the experience.", perks: ['Stock options', 'Retreat twice/year', 'Top-of-market comp', 'No meetings Fridays'] },
    { title: 'Growth Marketing Manager', company: 'Notion', cat: 'Marketing', type: 'Full-time', salary: '$90k – $120k', tz: 'Americas', posted: '1d ago', tags: ['SEO', 'Content', 'Analytics'], desc: "Lead growth initiatives for Notion's global expansion. Own the content strategy, run experiments and collaborate with product to drive activation.", perks: ['Flexible hours', '$2k home office', 'Equity', 'Health + dental'] },
    { title: 'iOS Developer', company: 'Superwall', cat: 'Engineering', type: 'Contract', salary: '$80 – $120/hr', tz: 'Any', posted: '3h ago', tags: ['Swift', 'SwiftUI', 'Payments'], desc: "3-6 month contract to build new paywalling features in our iOS SDK. Used by 1000+ apps. Strong Swift skills required.", perks: ['Flexible hours', 'Remote-only', 'Great rate'] },
    { title: 'Technical Writer', company: 'Vercel', cat: 'Writing', type: 'Full-time', salary: '$85k – $105k', tz: 'Any', posted: '2d ago', tags: ['Docs', 'Markdown', 'APIs'], desc: "Write world-class documentation for Vercel's developer platform. You understand how developers think and can explain complex systems simply.", perks: ['Fully remote', 'Unlimited books', 'Stipend', 'Stock options'] },
    { title: 'Head of Product', company: 'Descript', cat: 'Product', type: 'Full-time', salary: '$160k – $200k', tz: 'Americas', posted: '4h ago', tags: ['Roadmap', 'Strategy', 'AI'], desc: "Own the product strategy for Descript's AI-powered audio and video editing suite. Work with a world-class team reimagining how creators work.", perks: ['Executive comp', 'Equity', '6wk sabbatical', 'Premium benefits'] },
    { title: 'Customer Success Manager', company: 'Intercom', cat: 'Support', type: 'Full-time', salary: '$70k – $90k', tz: 'EMEA', posted: '6h ago', tags: ['SaaS', 'Onboarding', 'Retention'], desc: "Help Intercom's enterprise customers get maximum value from the platform. You'll own a portfolio of accounts and drive expansion revenue.", perks: ['Remote-first', 'Equity', 'Annual retreat', 'L&D budget'] },
    { title: 'Freelance Brand Designer', company: 'Various clients', cat: 'Design', type: 'Freelance', salary: '$50 – $80/hr', tz: 'Any', posted: '1h ago', tags: ['Branding', 'Illustration', 'Identity'], desc: "Multiple clients seeking senior brand designers for identity projects. 2-8 week engagements. Strong portfolio required.", perks: ['Flexible', 'Pick your projects', 'Immediate start'] },
  ];

  // Parse "$130k – $160k" or "$80 – $120/hr" to a numeric annual minimum (USD).
  // Hourly rates are normalized to annual via × 2080 (40h × 52w).
  const parseAnnualMin = (s) => {
    const m = s.match(/\$\s*(\d+(?:\.\d+)?)(k?)/i);
    if (!m) return 0;
    let n = parseFloat(m[1]);
    if (m[2].toLowerCase() === 'k') n *= 1000;
    if (/\/hr/i.test(s)) n *= 2080;
    return n;
  };

  const filtered = jobs.filter(j => {
    const matchType = typeFilter === 'All' || j.type === typeFilter;
    const matchCat = catFilter === 'All' || j.cat === catFilter;
    const matchSal = parseAnnualMin(j.salary) >= salaryMin;
    const matchQ = !query || j.title.toLowerCase().includes(query.toLowerCase()) || j.company.toLowerCase().includes(query.toLowerCase()) || j.tags.some(t => t.toLowerCase().includes(query.toLowerCase()));
    return matchType && matchCat && matchSal && matchQ;
  });

  const sel = selectedJob !== null ? jobs[selectedJob] : null;
  const catEmoji = (c) => c === 'Engineering' ? '⚡' : c === 'Design' ? '✦' : c === 'Marketing' ? '📈' : c === 'Product' ? '🧭' : c === 'Writing' ? '✍️' : '💼';

  return (
    <div style={{ flex: 1, position: 'relative', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* Filters bar */}
      <div style={{ padding: '14px 32px 12px', borderBottom: '1px solid #26262E', display: 'flex', flexDirection: 'column', gap: 10, flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 8, height: 40, background: TOKENS.color.surface2, borderRadius: 10, alignItems: 'center', padding: '0 14px' }}>
          <SearchIcon size={16} />
          <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Role, company or skill…" style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textPrimary }} />
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
          {types.map(t => <FilterChip key={t} label={t} selected={typeFilter === t} onClick={() => setTypeFilter(t)} />)}
          <select value={salaryMin} onChange={e => setSalaryMin(parseInt(e.target.value))} style={{
            marginLeft: 4, height: 36, padding: '0 12px', borderRadius: 999,
            background: salaryMin > 0 ? 'rgba(0,255,148,0.1)' : 'transparent',
            border: `1.5px solid ${salaryMin > 0 ? TOKENS.color.accent : TOKENS.color.border}`,
            color: salaryMin > 0 ? TOKENS.color.accent : TOKENS.color.textSecondary,
            fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 500,
            cursor: 'pointer', outline: 'none',
          }}>
            {SALARY_OPTIONS.map(o => <option key={o.val} value={o.val}>{o.label}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
          {cats.map(c => <FilterChip key={c} label={c} selected={catFilter === c} onClick={() => setCatFilter(c)} />)}
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{ display: 'flex', gap: 8 }}>
              {Object.entries(tzColors).map(([tz, color]) => (
                <div key={tz} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <div style={{ width: 6, height: 6, borderRadius: '50%', background: color }} />
                  <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 10, color: TOKENS.color.textTertiary }}>{tz}</span>
                </div>
              ))}
            </div>
            <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.06em' }}>{filtered.length} JOBS</span>
          </div>
        </div>
      </div>

      {/* Full-width grid of jobs */}
      <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? '14px 14px' : '20px 32px' }}>
        {filtered.length === 0 ? (
          <EmptyState
            icon={<BriefcaseIcon size={48} />}
            headline="No jobs match"
            sub="Try a different search or clear the filters"
            cta="Clear filters"
            onCta={() => { setQuery(''); setTypeFilter('All'); setCatFilter('All'); setSalaryMin(0); }}
          />
        ) : (
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(auto-fill, minmax(420px, 1fr))', gap: 12 }}>
          {filtered.map((job, i) => {
            const idx = jobs.indexOf(job);
            const isSaved = saved.includes(idx);
            const status = statuses[idx];
            return (
              <Card key={i} onClick={() => setSelectedJob(idx)} style={{ padding: '16px 18px', cursor: 'pointer' }}>
                <div style={{ display: 'flex', gap: 12 }}>
                  <div style={{ width: 44, height: 44, borderRadius: 10, background: TOKENS.color.surface2, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, border: '1px solid #26262E' }}>
                    {catEmoji(job.cat)}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10, marginBottom: 2 }}>
                      <div style={{ minWidth: 0, flex: 1 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 15, fontWeight: 700, color: TOKENS.color.textPrimary, marginBottom: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{job.title}</div>
                        </div>
                        <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textSecondary }}>{job.company} · {job.posted}</div>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
                        {status && (
                          <span style={{ background: `${STATUS_COLORS[status]}22`, color: STATUS_COLORS[status], fontFamily: "'JetBrains Mono',monospace", fontSize: 9, fontWeight: 700, padding: '3px 7px', borderRadius: 999, letterSpacing: '0.06em', textTransform: 'uppercase' }}>{status}</span>
                        )}
                        <button onClick={e => { e.stopPropagation(); setSaved(prev => prev.includes(idx) ? prev.filter(x => x !== idx) : [...prev, idx]); }} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 2 }}>
                          <HeartIcon size={16} filled={isSaved} color={isSaved ? TOKENS.color.accent : TOKENS.color.textTertiary} />
                        </button>
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8, alignItems: 'center' }}>
                      <span style={{ background: `${tzColors[job.tz] || TOKENS.color.textSecondary}18`, color: tzColors[job.tz] || TOKENS.color.textSecondary, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999 }}>{job.tz}</span>
                      <span style={{ background: TOKENS.color.surface2, color: TOKENS.color.textSecondary, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999, border: '1px solid #26262E' }}>{job.type}</span>
                      <span style={{ background: TOKENS.color.surface2, color: TOKENS.color.textSecondary, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999, border: '1px solid #26262E' }}>{job.cat}</span>
                      <span style={{ marginLeft: 'auto', fontFamily: "'JetBrains Mono',monospace", fontSize: 12, color: TOKENS.color.accent, fontWeight: 600 }}>{job.salary}</span>
                    </div>
                    <div style={{ display: 'flex', gap: 4, marginTop: 8, flexWrap: 'wrap' }}>
                      {job.tags.slice(0, 4).map(t => <span key={t} style={{ background: TOKENS.color.surface2, border: '1px solid #26262E', borderRadius: 6, padding: '2px 7px', fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textSecondary }}>{t}</span>)}
                    </div>
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
        )}
      </div>

      {/* Slide-out detail */}
      <SlideOutPanel isOpen={sel !== null} onClose={() => setSelectedJob(null)}>
        {sel && (
          <>
            <div style={{ padding: '20px 24px', borderBottom: '1px solid #26262E', display: 'flex', alignItems: 'flex-start', gap: 14, flexShrink: 0 }}>
              <div style={{ width: 52, height: 52, borderRadius: 12, background: TOKENS.color.surface2, border: '1px solid #26262E', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0 }}>
                {catEmoji(sel.cat)}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <h2 style={{ fontFamily: "'Inter',sans-serif", fontSize: 19, fontWeight: 700, color: TOKENS.color.textPrimary, margin: '0 0 2px' }}>{sel.title}</h2>
                <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, color: TOKENS.color.textSecondary }}>{sel.company}</div>
              </div>
              <button onClick={() => setSaved(prev => prev.includes(selectedJob) ? prev.filter(x => x !== selectedJob) : [...prev, selectedJob])} style={{ width: 36, height: 36, borderRadius: 8, border: `1px solid ${saved.includes(selectedJob) ? TOKENS.color.accent : TOKENS.color.border}`, background: saved.includes(selectedJob) ? 'rgba(0,255,148,0.1)' : 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <HeartIcon size={16} filled={saved.includes(selectedJob)} color={saved.includes(selectedJob) ? TOKENS.color.accent : TOKENS.color.textSecondary} />
              </button>
              <button onClick={() => setSelectedJob(null)} style={{ width: 32, height: 32, borderRadius: 8, background: TOKENS.color.surface2, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <XIcon size={14} />
              </button>
            </div>

            <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
                <span style={{ background: `${tzColors[sel.tz]}18`, color: tzColors[sel.tz], fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 999 }}>{sel.tz} timezone</span>
                <span style={{ background: TOKENS.color.surface2, color: TOKENS.color.textSecondary, fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 999, border: '1px solid #26262E' }}>{sel.type}</span>
                <span style={{ background: TOKENS.color.surface2, color: TOKENS.color.textSecondary, fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, padding: '4px 10px', borderRadius: 999, border: '1px solid #26262E' }}>{sel.cat}</span>
              </div>

              <Card style={{ padding: '14px 18px', marginBottom: 18, display: 'flex', alignItems: 'center', gap: 18 }}>
                <div>
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 4 }}>COMPENSATION</div>
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 20, fontWeight: 600, color: TOKENS.color.accent }}>{sel.salary}</div>
                </div>
                <div style={{ width: 1, height: 36, background: TOKENS.color.border }} />
                <div>
                  <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 4 }}>POSTED</div>
                  <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textPrimary }}>{sel.posted}</div>
                </div>
              </Card>

              {/* Application status tracker */}
              <div style={{ marginBottom: 18 }}>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 10 }}>APPLICATION STATUS</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {STATUS_OPTIONS.map(s => {
                    const active = statuses[selectedJob] === s;
                    return (
                      <button key={s} onClick={() => setJobStatus(selectedJob, active ? null : s)} style={{
                        height: 32, padding: '0 12px', borderRadius: 999,
                        border: `1.5px solid ${active ? STATUS_COLORS[s] : TOKENS.color.border}`,
                        background: active ? `${STATUS_COLORS[s]}18` : 'transparent',
                        color: active ? STATUS_COLORS[s] : TOKENS.color.textSecondary,
                        cursor: 'pointer', fontFamily: "'Inter',sans-serif", fontSize: 12, fontWeight: active ? 600 : 500,
                        transition: `all ${TOKENS.anim.fast}`,
                      }}>{s}</button>
                    );
                  })}
                  {statuses[selectedJob] && (
                    <button onClick={() => setJobStatus(selectedJob, null)} style={{
                      height: 32, padding: '0 10px', borderRadius: 999, border: 'none', background: 'none',
                      color: TOKENS.color.textTertiary, cursor: 'pointer', fontFamily: "'Inter',sans-serif", fontSize: 12,
                    }}>Clear</button>
                  )}
                </div>
              </div>

              <div style={{ marginBottom: 18 }}>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 10 }}>ABOUT THE ROLE</div>
                <p style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textSecondary, lineHeight: 1.7, margin: 0 }}>{sel.desc}</p>
              </div>

              <div style={{ marginBottom: 18 }}>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 10 }}>SKILLS</div>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {sel.tags.map(t => <span key={t} style={{ background: TOKENS.color.surface, border: '1px solid #26262E', borderRadius: 8, padding: '5px 11px', fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textPrimary, fontWeight: 500 }}>{t}</span>)}
                </div>
              </div>

              <div style={{ marginBottom: 22 }}>
                <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 10 }}>PERKS & BENEFITS</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
                  {sel.perks.map(p => (
                    <div key={p} style={{ display: 'flex', alignItems: 'center', gap: 8, background: TOKENS.color.surface, borderRadius: 10, padding: '8px 12px', border: '1px solid #26262E' }}>
                      <CheckIcon size={12} color="#00FF94" />
                      <span style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textPrimary }}>{p}</span>
                    </div>
                  ))}
                </div>
              </div>

              <Btn variant="primary" size="lg" fullWidth onClick={() => { setJobStatus(selectedJob, 'Applied'); toast(`Application sent · ${sel.title}`); }}>Apply now →</Btn>
            </div>
          </>
        )}
      </SlideOutPanel>
    </div>
  );
}

// ── Location Info (renamed from Country Profile) ──────────────────────────────
function LocationInfo({ onBack, onNavigate }) {
  // Use global location data (from location-data.js), assign cycling colors
  const COLOR_CYCLE = [
    TOKENS.color.accent, TOKENS.color.error, TOKENS.color.warn,
    TOKENS.color.purple, TOKENS.color.info,
  ];
  const allLocations = (window.LOCATION_DATA || []).map((l, i) => ({
    ...l,
    color: COLOR_CYCLE[i % COLOR_CYCLE.length],
  }));

  // Saved locations: first 5 entries from the dataset
  const savedLocations = allLocations.slice(0, 5).map(l => ({
    flag: l.flag, city: l.city, country: l.country,
  }));

  const vw = useViewportWidth();
  const isMobile = vw < 768;
  const [savedIdx, setSavedIdx] = React.useState(0);
  const [query, setQuery] = React.useState('');
  const [costFilter, setCostFilter] = React.useState('All');
  const [selected, setSelected] = React.useState(null);
  const [tab, setTab] = React.useState('Details');
  const costOptions = ['All', '$', '$$', '$$$'];

  const filtered = allLocations.filter(l => {
    const matchQ = !query || l.city.toLowerCase().includes(query.toLowerCase()) || l.country.toLowerCase().includes(query.toLowerCase());
    const matchC = costFilter === 'All' || l.cost === costFilter;
    return matchQ && matchC;
  });

  const sel = selected !== null ? allLocations[selected] : null;
  const openDetail = (i) => { setSelected(i); setTab('Details'); };

  // Bias the saved list onto the main list when clicked: jump straight to that location's detail
  const openSaved = (savedI) => {
    setSavedIdx(savedI);
    const target = savedLocations[savedI];
    const idx = allLocations.findIndex(l => l.city === target.city);
    if (idx >= 0) openDetail(idx);
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: isMobile ? 'column' : 'row', overflow: 'hidden' }}>
      {/* Saved locations: vertical sidebar on desktop, horizontal scroll on mobile */}
      {isMobile ? (
        <div style={{ display: 'flex', gap: 8, padding: '12px 14px', borderBottom: '1px solid #26262E', overflowX: 'auto', flexShrink: 0, background: TOKENS.color.surfaceDeep }}>
          {savedLocations.map((loc, i) => (
            <button key={i} onClick={() => openSaved(i)} style={{
              flexShrink: 0, display: 'flex', alignItems: 'center', gap: 6,
              padding: '6px 12px', borderRadius: 999,
              background: savedIdx === i ? 'rgba(0,255,148,0.1)' : TOKENS.color.surface2,
              border: `1px solid ${savedIdx === i ? TOKENS.color.accent : TOKENS.color.border}`,
              cursor: 'pointer', fontFamily: "'Inter',sans-serif", fontSize: 13,
              color: savedIdx === i ? TOKENS.color.accent : TOKENS.color.textPrimary, fontWeight: 500,
            }}>
              <span style={{ fontSize: 14 }}>{loc.flag}</span>
              {loc.city}
            </button>
          ))}
        </div>
      ) : (
        <div style={{ width: 220, flexShrink: 0, borderRight: '1px solid #26262E', display: 'flex', flexDirection: 'column', overflowY: 'auto', background: TOKENS.color.surfaceDeep }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid #26262E' }}>
            <span style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>SAVED LOCATIONS</span>
          </div>
          {savedLocations.map((loc, i) => (
            <div key={i} onClick={() => openSaved(i)} style={{
              padding: '12px 16px', borderBottom: '1px solid #26262E', cursor: 'pointer',
              background: savedIdx === i ? TOKENS.color.surface : 'transparent',
              borderLeft: savedIdx === i ? '2px solid #00FF94' : '2px solid transparent',
              display: 'flex', alignItems: 'center', gap: 10,
              transition: `all ${TOKENS.anim.fast}`,
            }}>
              <span style={{ fontSize: 18 }}>{loc.flag}</span>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 600, color: TOKENS.color.textPrimary }}>{loc.city}</div>
                <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 11, color: TOKENS.color.textSecondary }}>{loc.country}</div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* List + slide-out container */}
      <div style={{ flex: 1, position: 'relative', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Filters bar */}
        <div style={{ padding: isMobile ? '12px 14px 10px' : '14px 28px 12px', borderBottom: '1px solid #26262E', display: 'flex', flexDirection: 'column', gap: 10, flexShrink: 0 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ flex: 1, display: 'flex', gap: 8, height: 40, background: TOKENS.color.surface2, borderRadius: 10, alignItems: 'center', padding: '0 14px' }}>
              <SearchIcon size={16} />
              <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search city or country…" style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textPrimary }} />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
            {costOptions.map(c => <FilterChip key={c} label={c === 'All' ? 'All costs' : c} selected={costFilter === c} onClick={() => setCostFilter(c)} />)}
            <span style={{ marginLeft: 'auto', fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.06em' }}>{filtered.length} LOCATIONS</span>
          </div>
        </div>

        {/* Full-width grid of locations */}
        <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? '14px 14px' : '20px 28px' }}>
          {filtered.length === 0 ? (
            <EmptyState
              icon={<GlobeIcon size={48} />}
              headline="No locations match"
              sub="Try a different search or clear the filters"
              cta="Clear filters"
              onCta={() => { setQuery(''); setCostFilter('All'); }}
            />
          ) : (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 14 }}>
            {filtered.map((l, i) => {
              const idx = allLocations.indexOf(l);
              return (
                <Card key={i} onClick={() => openDetail(idx)} style={{ padding: 0, overflow: 'hidden', cursor: 'pointer' }}>
                  <div style={{ height: 90, background: `linear-gradient(135deg, ${l.color}22, ${l.color}55)`, position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 44 }}>
                    {l.flag}
                  </div>
                  <div style={{ padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <div>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 15, fontWeight: 700, color: TOKENS.color.textPrimary }}>{l.city}</div>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{l.country}</div>
                    </div>
                    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                      <span style={{ background: 'rgba(0,255,148,0.08)', color: TOKENS.color.accent, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999 }}>{l.wifi}</span>
                      <span style={{ background: TOKENS.color.surface2, color: TOKENS.color.warn, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999, border: '1px solid #26262E' }}>{l.cost}</span>
                      <span style={{ background: TOKENS.color.surface2, color: TOKENS.color.textSecondary, fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, padding: '3px 8px', borderRadius: 999, border: '1px solid #26262E' }}>{l.visa}</span>
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
          )}
        </div>

        {/* Slide-out detail */}
        <SlideOutPanel isOpen={sel !== null} onClose={() => setSelected(null)}>
          {sel && (
            <>
              <DetailHero color={sel.color} emoji={sel.flag} fontSize={96} gradientEnd="66" onClose={() => setSelected(null)} />

              <div style={{ padding: '18px 24px 0' }}>
                <h2 style={{ fontFamily: "'Inter',sans-serif", fontSize: 24, fontWeight: 700, color: TOKENS.color.textPrimary, margin: '0 0 4px' }}>{sel.city}, {sel.country}</h2>
              </div>

              <div style={{ padding: '14px 24px' }}>
                <DetailStatsGrid stats={[
                  { label: 'WI-FI', val: sel.wifi, color: TOKENS.color.accent },
                  { label: 'COST', val: sel.cost, color: TOKENS.color.warn },
                  { label: 'VISA', val: sel.visa, color: TOKENS.color.info },
                  { label: 'SAFETY', val: sel.safety.split(' ')[0], color: sel.safety.includes('Very') ? TOKENS.color.accent : sel.safety === 'Safe' ? TOKENS.color.warn : TOKENS.color.error },
                ]} />
              </div>

              <DetailTabs tabs={['Map', 'Details', 'Cities', 'Accom', 'Workspaces', 'Flights']} active={tab} onChange={setTab} />

              <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
                {tab === 'Map' && (
                  <div style={{ height: 360, background: 'linear-gradient(160deg,#0D1117 0%,#111827 60%,#0A0F1A 100%)', borderRadius: 12, position: 'relative', overflow: 'hidden', border: '1px solid #26262E' }}>
                    <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.08 }}>
                      <defs><pattern id="loc-grid" width="40" height="40" patternUnits="userSpaceOnUse"><path d="M 40 0 L 0 0 0 40" fill="none" stroke="#F5F5F7" strokeWidth="0.5"/></pattern></defs>
                      <rect width="100%" height="100%" fill="url(#loc-grid)"/>
                    </svg>
                    <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', fontSize: 56 }}>{sel.flag}</div>
                    <div style={{ position: 'absolute', bottom: 12, right: 12, background: 'rgba(10,10,11,0.8)', borderRadius: 8, padding: '6px 12px', fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>
                      {sel.country}
                    </div>
                  </div>
                )}

                {tab === 'Details' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
                    <div>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 8 }}>ABOUT</div>
                      <p style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, color: TOKENS.color.textSecondary, lineHeight: 1.65, margin: 0 }}>{sel.desc}</p>
                    </div>
                    <div>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 8 }}>IMAGES</div>
                      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
                        {[0, 1, 2, 3, 4, 5].map(n => (
                          <div key={n} style={{ aspectRatio: '4 / 3', background: `linear-gradient(${135 + n * 30}deg, ${sel.color}22, ${sel.color}55)`, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 28 }}>
                            {sel.flag}
                          </div>
                        ))}
                      </div>
                    </div>
                    <Card style={{ padding: '14px 16px' }}>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 10, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em', marginBottom: 6 }}>MONTHLY COST OF LIVING</div>
                      <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 22, fontWeight: 600, color: TOKENS.color.warn }}>${sel.costNum.toLocaleString()}</div>
                      <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary, marginTop: 4 }}>Apartment + food + co-working + transport</div>
                    </Card>
                  </div>
                )}

                {tab === 'Cities' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>OTHER CITIES IN {sel.country.toUpperCase()}</div>
                    {[
                      { name: 'Porto', sub: 'Coastal · Smaller scene' },
                      { name: 'Madeira', sub: 'Island · Digital nomad village' },
                      { name: 'Cascais', sub: 'Beachside · 30 min from capital' },
                    ].map(c => (
                      <Card key={c.name} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
                        <div style={{ width: 36, height: 36, borderRadius: 8, background: `${sel.color}22`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>{sel.flag}</div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600, color: TOKENS.color.textPrimary }}>{c.name}</div>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{c.sub}</div>
                        </div>
                        <ChevronRightIcon size={14} />
                      </Card>
                    ))}
                  </div>
                )}

                {tab === 'Accom' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>TOP-RATED IN {sel.city.toUpperCase()}</div>
                    {[
                      { name: 'Selina Chiado', type: 'Coliving', price: '€42/night', icon: '🏢' },
                      { name: 'The Independent Hotel', type: 'Hotel', price: '€89/night', icon: '🏨' },
                      { name: 'NomadX Apartments', type: 'Serviced', price: '€65/night', icon: '🏠' },
                    ].map(a => (
                      <Card key={a.name} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
                        <div style={{ width: 36, height: 36, borderRadius: 8, background: TOKENS.color.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>{a.icon}</div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600, color: TOKENS.color.textPrimary }}>{a.name}</div>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 12, color: TOKENS.color.textSecondary }}>{a.type}</div>
                        </div>
                        <MonoText size={13} weight={600} color="#FFB800">{a.price}</MonoText>
                      </Card>
                    ))}
                  </div>
                )}

                {tab === 'Workspaces' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>BEST WORKSPACES</div>
                    {[
                      { name: 'Hub Lisbon', wifi: '78 Mbps', icon: '💻' },
                      { name: 'Selina CoWork', wifi: '56 Mbps', icon: '💻' },
                      { name: 'Dear Breakfast', wifi: '34 Mbps', icon: '☕' },
                    ].map(w => (
                      <Card key={w.name} style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
                        <div style={{ width: 36, height: 36, borderRadius: 8, background: TOKENS.color.surface2, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>{w.icon}</div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600, color: TOKENS.color.textPrimary }}>{w.name}</div>
                          <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.accent }}>{w.wifi}</div>
                        </div>
                        <ChevronRightIcon size={14} />
                      </Card>
                    ))}
                  </div>
                )}

                {tab === 'Flights' && (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                    <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, fontWeight: 600, color: TOKENS.color.textTertiary, letterSpacing: '0.08em' }}>FLIGHTS TO {sel.city.toUpperCase()}</div>
                    {[
                      { route: `SYD → ${sel.city.slice(0, 3).toUpperCase()}`, code: 'QF1', date: '02 MAY · 06:00 → 22:30', price: '€1,210' },
                      { route: `LHR → ${sel.city.slice(0, 3).toUpperCase()}`, code: 'BA492', date: '04 MAY · 08:15 → 10:45', price: '€86' },
                    ].map(f => (
                      <Card key={f.code} style={{ padding: '14px 16px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                          <PlaneIcon size={18} color="#9999A1" />
                          <div style={{ flex: 1 }}>
                            <div style={{ fontFamily: "'Inter',sans-serif", fontSize: 14, fontWeight: 600, color: TOKENS.color.textPrimary }}>{f.route} · {f.code}</div>
                            <div style={{ fontFamily: "'JetBrains Mono',monospace", fontSize: 11, color: TOKENS.color.textSecondary, marginTop: 2 }}>{f.date}</div>
                          </div>
                          <MonoText size={14} weight={600} color="#FFB800">{f.price}</MonoText>
                        </div>
                      </Card>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}
        </SlideOutPanel>
      </div>
    </div>
  );
}

Object.assign(window, { AccommodationScreen, WhatsOnScreen, RemoteJobsScreen, LocationInfo });
