// Lifestyle section – "Life in your new home" with live sunrise/sunset.
// Replaces the rejected daily-routine concept. No ambient audio, no schedule –
// just atmosphere + facts + placeholders for real photography.

const LIFESTYLE_PLACES = [
  {
    id: 'sao-tome',
    label: { ru: 'Флорианополис', en: 'Florianópolis' },
    region: { ru: 'Бразилия · IT-столица ЛатАм', en: 'Brazil · LatAm IT capital' },
    tz: 'America/Sao_Paulo',
    lat: -27.6, lon: -48.5,
    tempC: 24,
    rainyDays: 9,
    palette: ['#1a3a52', '#3a7e9d', '#f5d585'],
    photo: 'https://images.unsplash.com/photo-1544550285-f813152fb2fd?w=1400&q=80&auto=format&fit=crop',
    cost: { rent: '$1.4k/мес', school: '$11k/год', insurance: '$1.4k/год', currency: 'USD' },
    facts: {
      ru: ['Здесь живёт команда Migronis с 2025', '6000+ IT-компаний – «Бразильская Кремниевая долина»', 'Океан, сёрфинг, безопасность семьи', 'Аренда + 20–30% перепродажа жилья'],
      en: ['Where the Migronis team has lived since 2025', '6,000+ IT companies – "LatAm Silicon Valley"', 'Ocean, surfing, family safety', 'Rental + 20–30% real-estate appreciation']
    },
  },
  {
    id: 'portugal-golden',
    label: { ru: 'Лиссабон', en: 'Lisbon' },
    region: { ru: 'Португалия', en: 'Portugal' },
    tz: 'Europe/Lisbon',
    lat: 38.7, lon: -9.1,
    tempC: 19,
    rainyDays: 11,
    palette: ['#1a3a5c', '#e8a868', '#fff0d9'],
    photo: 'https://images.unsplash.com/photo-1555881400-74d7acaacd8b?w=1400&q=80&auto=format&fit=crop',
    cost: { rent: '€1.8k/мес', school: '€15k/год', insurance: '€1.2k/год', currency: 'EUR' },
    facts: {
      ru: ['7 холмов, 28 трамвай', 'Атлантический океан + Серра-да-Эштрела', 'Самая безопасная страна Западной Европы', '300 солнечных дней в году'],
      en: ['7 hills, the 28 tram', 'Atlantic ocean + Serra da Estrela', 'Safest country in Western Europe', '300 sunny days per year']
    },
  },
  {
    id: 'turkey',
    label: { ru: 'Стамбул', en: 'Istanbul' },
    region: { ru: 'Türkiye', en: 'Türkiye' },
    tz: 'Europe/Istanbul',
    lat: 41.0, lon: 28.9,
    tempC: 17,
    rainyDays: 9,
    palette: ['#3e2752', '#c54545', '#f0c862'],
    photo: 'https://images.unsplash.com/photo-1524231757912-21f4fe3a7200?w=1400&q=80&auto=format&fit=crop',
    cost: { rent: '$0.9k/мес', school: '$12k/год', insurance: '$0.9k/год', currency: 'USD' },
    facts: {
      ru: ['Босфор – мост между двух континентов', 'Гражданство уже через 6–8 мес.', 'Развитый рынок недвижимости и здравоохранения', 'Безвиз в 118 стран'],
      en: ['Bosphorus bridges two continents', 'Citizenship in 6–8 months', 'Strong property and healthcare market', '118 visa-free destinations']
    },
  },
  {
    id: 'cyprus',
    label: { ru: 'Лимасол', en: 'Limassol' },
    region: { ru: 'Кипр', en: 'Cyprus' },
    tz: 'Asia/Nicosia',
    lat: 34.7, lon: 33.0,
    tempC: 22,
    rainyDays: 5,
    palette: ['#0b5d8a', '#d4a45a', '#f4e3b8'],
    photo: 'https://images.unsplash.com/photo-1601581874993-b69d846e4c97?w=1400&q=80&auto=format&fit=crop',
    cost: { rent: '€1.5k/мес', school: '€13k/год', insurance: '€1.0k/год', currency: 'EUR' },
    facts: {
      ru: ['340 солнечных дней в году', '60-day tax rule – оптимизация налогов', 'Английский – деловой язык', 'EU + Средиземное море'],
      en: ['340 sunny days per year', '60-day tax rule – tax optimisation', 'English is the business language', 'EU + Mediterranean']
    },
  },
];

// SunCalc-style approximation. Returns hours-as-float in local timezone.
function sunTimes(lat, lon, tz, date) {
  const rad = Math.PI / 180;
  const start = new Date(date.getFullYear(), 0, 0);
  const dayOfYear = Math.floor((date - start) / 86400000);
  const decl = -23.45 * rad * Math.cos((360 / 365) * (dayOfYear + 10) * rad);
  const cosH = -Math.tan(lat * rad) * Math.tan(decl);
  if (cosH < -1 || cosH > 1) return null; // polar day/night
  const H = Math.acos(cosH) / rad;
  const noonUTC = 12 - lon / 15;
  const sunriseUTC = noonUTC - H / 15;
  const sunsetUTC = noonUTC + H / 15;

  const tzOffset = (() => {
    const now = date;
    const tzDate = new Date(now.toLocaleString('en-US', { timeZone: tz }));
    const utcDate = new Date(now.toLocaleString('en-US', { timeZone: 'UTC' }));
    return (tzDate - utcDate) / 3600000;
  })();

  const fmt = (h) => {
    const local = (h + tzOffset + 24) % 24;
    const hh = Math.floor(local);
    const mm = Math.round((local - hh) * 60);
    return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
  };
  return { sunrise: fmt(sunriseUTC), sunset: fmt(sunsetUTC), tzOffset };
}

function nowInTz(tz) {
  try {
    return new Intl.DateTimeFormat('en-GB', {
      timeZone: tz, hour: '2-digit', minute: '2-digit', hour12: false,
    }).format(new Date());
  } catch (e) {
    return '–';
  }
}

// Compute "daylight progress" 0..1 for sky gradient.
function skyMix(sunrise, sunset, tz) {
  const now = new Date().toLocaleString('en-GB', { timeZone: tz, hour: '2-digit', minute: '2-digit', hour12: false });
  const [h, m] = now.split(':').map(Number);
  const cur = h + m / 60;
  const [srH, srM] = sunrise.split(':').map(Number);
  const [ssH, ssM] = sunset.split(':').map(Number);
  const sr = srH + srM / 60;
  const ss = ssH + ssM / 60;
  if (cur < sr - 1) return 0; // deep night
  if (cur < sr) return 0.15;  // pre-dawn
  if (cur < sr + 1) return 0.4; // dawn
  if (cur < ss - 1) return 0.85; // day
  if (cur < ss) return 0.55; // golden hour
  if (cur < ss + 1) return 0.3; // dusk
  return 0.1; // night
}

function skyGradient(mix, palette) {
  const [night, golden, day] = palette;
  // Build a vertical gradient that morphs with daylight progress
  if (mix < 0.3) {
    return `linear-gradient(180deg, ${night} 0%, ${night} 50%, ${golden}88 100%)`;
  } else if (mix < 0.6) {
    return `linear-gradient(180deg, ${night}88 0%, ${golden} 50%, ${day} 100%)`;
  }
  return `linear-gradient(180deg, ${day}cc 0%, ${day} 50%, ${golden}66 100%)`;
}

function PlaceCard({ place, lang, setRoute }) {
  const [time, setTime] = React.useState(nowInTz(place.tz));
  const [tick, setTick] = React.useState(0);

  React.useEffect(() => {
    const id = setInterval(() => {
      setTime(nowInTz(place.tz));
      setTick((t) => t + 1);
    }, 30000);
    return () => clearInterval(id);
  }, [place.tz]);

  const sun = sunTimes(place.lat, place.lon, place.tz, new Date());
  const mix = sun ? skyMix(sun.sunrise, sun.sunset, place.tz) : 0.5;
  const sky = sun ? skyGradient(mix, place.palette) : `linear-gradient(180deg, ${place.palette[0]}, ${place.palette[2]})`;

  const phase = mix < 0.2 ? (lang === 'ru' ? 'ночь' : 'night')
              : mix < 0.5 ? (lang === 'ru' ? 'рассвет' : 'sunrise')
              : mix < 0.75 ? (lang === 'ru' ? 'день' : 'day')
              : mix < 0.6 ? (lang === 'ru' ? 'золотой час' : 'golden hour')
              : (lang === 'ru' ? 'день' : 'day');

  return (
    <div className="lift" style={{
      background: 'var(--bg-elev-2)', border: '1px solid var(--border)',
      borderRadius: 'var(--r-lg)', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Sky strip – animates with real daylight */}
      <div style={{
        height: 80, position: 'relative', overflow: 'hidden',
        background: sky, transition: 'background 1.5s ease',
      }}>
        {/* Sun position – soft radial glow, not a hard disk */}
        {sun && (() => {
          const coreColor = mix > 0.7 ? '#FFF4C2' : mix > 0.3 ? '#FFC880' : '#FFD9A0';
          const haloColor = mix > 0.7 ? '#FFE08A' : mix > 0.3 ? '#FF9148' : '#FFAA66';
          return (
            <div style={{
              position: 'absolute',
              bottom: `${Math.max(-30, mix * 90 - 30)}%`,
              left: `${15 + mix * 60}%`,
              width: 220, height: 220,
              transform: 'translate(-50%, 50%)',
              borderRadius: '50%',
              background: `radial-gradient(circle at center,
                ${coreColor} 0%,
                ${coreColor}f0 8%,
                ${haloColor}aa 22%,
                ${haloColor}55 42%,
                ${haloColor}22 62%,
                transparent 78%)`,
              filter: 'blur(6px)',
              opacity: mix < 0.1 ? 0 : 0.95,
              transition: 'all 2s ease',
              pointerEvents: 'none',
            }} />
          );
        })()}
        {/* Stars in night */}
        {mix < 0.25 && (
          <div style={{ position: 'absolute', inset: 0 }}>
            {Array.from({ length: 18 }).map((_, i) => (
              <span key={i} style={{
                position: 'absolute',
                left: `${(i * 17.3) % 100}%`,
                top: `${(i * 13.7) % 60}%`,
                width: 1.5, height: 1.5, borderRadius: 999,
                background: '#fff', opacity: 0.5 + ((i % 3) * 0.15),
              }} />
            ))}
          </div>
        )}
        {/* Location chip */}
        <div style={{
          position: 'absolute', left: 14, top: 12, fontSize: 11,
          padding: '4px 10px', borderRadius: 999,
          background: 'rgba(0,0,0,0.4)', color: '#fff',
          backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
          letterSpacing: '0.04em',
        }}>{place.region[lang]}</div>
      </div>

      {/* Image – real city photography */}
      {place.photo ? (
        <div style={{ aspectRatio: '16/9', position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--border)', background: '#191C1F' }}>
          <img src={place.photo} alt={place.label[lang]} loading="lazy"
               onError={(e) => { e.currentTarget.src = `https://picsum.photos/seed/migronis-${place.id}/1200/700`; }}
               style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
        </div>
      ) : (
        <div className="img-ph" data-label={lang === 'ru' ? `Фото · ${place.label.ru}` : `Photo · ${place.label.en}`}
             style={{ aspectRatio: '16/9', borderRadius: 0, border: 'none', borderBottom: '1px solid var(--border)' }} />
      )}

      <div style={{ padding: 22, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <h3 className="display" style={{ fontSize: 26, margin: 0 }}>{place.label[lang]}</h3>

        {/* Now bar */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 0,
          marginTop: 16, padding: '12px 0', borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
        }}>
          <div>
            <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>{lang === 'ru' ? 'сейчас' : 'now'}</div>
            <div className="mono" style={{ fontSize: 14, color: 'var(--accent)' }}>{time}</div>
          </div>
          {sun && (
            <>
              <div>
                <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>↑ {lang === 'ru' ? 'рассвет' : 'sunrise'}</div>
                <div className="mono" style={{ fontSize: 14 }}>{sun.sunrise}</div>
              </div>
              <div>
                <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>↓ {lang === 'ru' ? 'закат' : 'sunset'}</div>
                <div className="mono" style={{ fontSize: 14 }}>{sun.sunset}</div>
              </div>
            </>
          )}
          <div>
            <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>{lang === 'ru' ? 'сред. t°' : 'avg t°'}</div>
            <div className="mono" style={{ fontSize: 14 }}>+{place.tempC}°</div>
          </div>
        </div>

        {/* Atmospheric facts */}
        <ul style={{ listStyle: 'none', padding: 0, margin: '16px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {place.facts[lang].map((f, i) => (
            <li key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, color: 'var(--fg-muted)' }}>
              <span style={{
                flexShrink: 0, marginTop: 6,
                width: 4, height: 4, borderRadius: 999, background: 'var(--accent)',
              }} />
              <span>{f}</span>
            </li>
          ))}
        </ul>

        {/* Cost of living – indicative monthly/yearly markers for a family */}
        {place.cost && (
          <div style={{
            marginTop: 18, padding: '14px 0',
            borderTop: '1px solid var(--border)',
          }}>
            <div className="eyebrow" style={{ fontSize: 10, marginBottom: 10 }}>
              {lang === 'ru' ? 'Стоимость жизни семьи · от' : 'Family cost of living · from'}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {[
                { l: lang === 'ru' ? 'аренда' : 'rent',     v: place.cost.rent },
                { l: lang === 'ru' ? 'школа' : 'school',     v: place.cost.school },
                { l: lang === 'ru' ? 'страховка' : 'insurance', v: place.cost.insurance },
              ].map((m, i) => (
                <div key={i}>
                  <div style={{ fontSize: 10, color: 'var(--fg-dim)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 4 }}>{m.l}</div>
                  <div className="mono" style={{ fontSize: 12 }}>{m.v}</div>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ marginTop: 'auto', paddingTop: 18 }}>
          <button className="btn btn-line btn-sm" style={{ width: '100%' }}
                  onClick={() => setRoute({ name: 'program', id: place.id })}>
            {lang === 'ru' ? 'Программа для этой страны' : 'See the program for this country'} →
          </button>
        </div>
      </div>
    </div>
  );
}

function LifestyleSection({ lang, setRoute }) {
  return (
    <section className="section" style={{ paddingTop: 64 }}>
      <div className="container-wide">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 36, flexWrap: 'wrap', gap: 20 }}>
          <div style={{ maxWidth: 720 }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>
              {lang === 'ru' ? '– Не паспорт-острова. А места куда едут жить.' : '– Real places. Not passport islands.'}
            </div>
            <h2 className="display h-2" style={{ margin: 0 }}>
              {lang === 'ru'
                ? <>Сколько на самом деле <em>стоит</em><br/>жить в этих городах</>
                : <>What it <em>actually</em> costs<br/>to live in these places</>}
            </h2>
            <p style={{ color: 'var(--fg-muted)', fontSize: 16, marginTop: 18, maxWidth: 560, lineHeight: 1.55 }}>
              {lang === 'ru'
                ? 'Флорианополис, Лиссабон, Стамбул, Лимасол – реально livable юрисдикции с нашими RBI-программами. Местное время, климат и стоимость жизни семьи: аренда, школа, страховка.'
                : 'Florianópolis, Lisbon, Istanbul, Limassol – actually livable jurisdictions with our RBI programs. Local time, climate and family cost-of-living: rent, school, insurance.'}
            </p>
          </div>
          <div style={{
            padding: '10px 16px', background: 'var(--surface)',
            border: '1px solid var(--border)', borderRadius: 999,
            fontSize: 12, color: 'var(--fg-muted)',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--accent)', boxShadow: '0 0 8px var(--accent)' }} />
            {lang === 'ru' ? 'обновляется каждые 30 сек' : 'live · updates every 30 s'}
          </div>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16,
        }}>
          {LIFESTYLE_PLACES.map((p) => (
            <PlaceCard key={p.id} place={p} lang={lang} setRoute={setRoute} />
          ))}
        </div>
      </div>
    </section>
  );
}

window.LifestyleSection = LifestyleSection;
