// Real Estate Gallery + ROI – properties in CBI/RBI destinations
// Indicative offerings with rental yield, capital appreciation, exit terms.
// Real listings to be supplied by client; placeholders from picsum.photos.

const REAL_ESTATE = [
  {
    id: 're-grenada-anse',
    country: 'Grenada', flag: '🇬🇩',
    program: 'grenada',
    region: { ru: 'Карибы', en: 'Caribbean' },
    locality: 'Grand Anse Beach',
    type: { ru: 'Бранд-отель, апартаменты', en: 'Branded resort, apartments' },
    img: 'https://picsum.photos/seed/migronis-re-grenada/1200/900',
    price: 350000, currency: 'USD',
    bedrooms: 2, area: 92,
    yieldGross: 6.8, appreciation: 5.4, exit: 5,
    eligible: { ru: 'Гражданство Гренады', en: 'Grenada citizenship' },
    badges: ['Government-approved', 'Rental managed'],
  },
  {
    id: 're-skn-marriott',
    country: 'Saint Kitts & Nevis', flag: '🇰🇳',
    program: 'saint-kitts',
    region: { ru: 'Карибы', en: 'Caribbean' },
    locality: 'Park Hyatt resort fractions',
    type: { ru: 'Доли в брендовом курорте', en: 'Branded-resort shares' },
    img: 'https://picsum.photos/seed/migronis-re-skn/1200/900',
    price: 400000, currency: 'USD',
    bedrooms: 1, area: 68,
    yieldGross: 5.5, appreciation: 4.2, exit: 7,
    eligible: { ru: 'Гражданство Saint Kitts', en: 'St Kitts citizenship' },
    badges: ['Approved CIU', '7-year exit'],
  },
  {
    id: 're-lisbon-chiado',
    country: 'Portugal', flag: '🇵🇹',
    program: 'portugal-golden',
    region: { ru: 'Европа', en: 'Europe' },
    locality: 'Chiado, Lisbon',
    type: { ru: 'Историческое здание, реконструкция', en: 'Historic building, refurb' },
    img: 'https://picsum.photos/seed/migronis-re-lisbon/1200/900',
    price: 750000, currency: 'EUR',
    bedrooms: 2, area: 110,
    yieldGross: 4.4, appreciation: 7.1, exit: 6,
    eligible: { ru: 'Не Golden Visa (но рентал)', en: 'Not GV-eligible (rental)' },
    badges: ['City centre', 'Heritage'],
  },
  {
    id: 're-istanbul-bebek',
    country: 'Türkiye', flag: '🇹🇷',
    program: 'turkey',
    region: { ru: 'MENA', en: 'MENA' },
    locality: 'Bebek, Istanbul',
    type: { ru: 'Премиум-апартаменты, вид на Босфор', en: 'Premium apartments, Bosphorus view' },
    img: 'https://picsum.photos/seed/migronis-re-istanbul/1200/900',
    price: 450000, currency: 'USD',
    bedrooms: 3, area: 145,
    yieldGross: 5.9, appreciation: 8.4, exit: 3,
    eligible: { ru: 'Гражданство Türkiye', en: 'Türkiye citizenship' },
    badges: ['Bosphorus view', '3-year exit'],
  },
  {
    id: 're-limassol-marina',
    country: 'Cyprus', flag: '🇨🇾',
    program: 'cyprus',
    region: { ru: 'Европа', en: 'Europe' },
    locality: 'Limassol Marina',
    type: { ru: 'Sea-front penthouse', en: 'Sea-front penthouse' },
    img: 'https://picsum.photos/seed/migronis-re-cyprus/1200/900',
    price: 850000, currency: 'EUR',
    bedrooms: 3, area: 180,
    yieldGross: 5.2, appreciation: 6.1, exit: 5,
    eligible: { ru: 'PR Кипра', en: 'Cyprus PR' },
    badges: ['Yacht berth option', 'EU PR'],
  },
  {
    id: 're-athens-glyfada',
    country: 'Greece', flag: '🇬🇷',
    program: 'greece',
    region: { ru: 'Европа', en: 'Europe' },
    locality: 'Glyfada Riviera, Athens',
    type: { ru: 'Newbuild апартаменты у моря', en: 'Newbuild seafront apartments' },
    img: 'https://picsum.photos/seed/migronis-re-greece/1200/900',
    price: 380000, currency: 'EUR',
    bedrooms: 2, area: 95,
    yieldGross: 5.7, appreciation: 6.8, exit: 5,
    eligible: { ru: 'Golden Visa Греции', en: 'Greek Golden Visa' },
    badges: ['Tourist short-let', 'Schengen'],
  },
];

function PropertyCard({ p, lang, setRoute }) {
  const cur = p.currency === 'USD' ? '$' : '€';
  const fmt = (n) => cur + (n >= 1e6 ? (n/1e6).toFixed(2) + 'M' : (n/1000).toFixed(0) + 'k');

  return (
    <div className="lift" style={{
      background: 'var(--bg-elev)', border: '1px solid var(--border)',
      borderRadius: 'var(--r-lg)', overflow: 'hidden',
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Image */}
      <div style={{ position: 'relative', aspectRatio: '4/3', overflow: 'hidden' }}>
        <img src={p.img} alt={p.locality} loading="lazy" draggable="false"
             style={{ width: '100%', height: '100%', objectFit: 'cover', filter: 'saturate(1.05)' }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, transparent 40%, rgba(0,0,0,0.5))',
        }} />
        <div style={{
          position: 'absolute', top: 12, left: 12,
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '6px 12px', borderRadius: 999,
          background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)',
          color: '#fff', fontSize: 12,
        }}>
          <window.FlagIcon emoji={p.flag} size={12} /><span>{p.country}</span>
        </div>
        {/* Yield badge */}
        <div style={{
          position: 'absolute', top: 12, right: 12,
          padding: '8px 12px', borderRadius: 12,
          background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)',
          color: '#fff',
        }}>
          <div style={{ fontSize: 10, opacity: .7, letterSpacing: '0.06em', textTransform: 'uppercase' }}>
            {lang === 'ru' ? 'доходность' : 'gross yield'}
          </div>
          <div className="mono" style={{ fontSize: 18, color: 'var(--accent-strong)', fontWeight: 600 }}>
            {p.yieldGross.toFixed(1)}%
          </div>
        </div>
        <div style={{
          position: 'absolute', bottom: 12, left: 14, right: 14,
          color: '#fff',
        }}>
          <div style={{ fontFamily: 'var(--f-display)', fontSize: 22, lineHeight: 1.1 }}>
            {p.locality}
          </div>
          <div style={{ fontSize: 13, opacity: .85, marginTop: 4 }}>
            {p.type[lang]}
          </div>
        </div>
      </div>

      {/* Body */}
      <div style={{ padding: 18, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 14 }}>
          <div>
            <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>{lang === 'ru' ? 'Цена от' : 'From'}</div>
            <div className="display" style={{ fontSize: 28, color: 'var(--accent)', lineHeight: 1 }}>{fmt(p.price)}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 13 }}>{p.bedrooms} BR · {p.area} m²</div>
          </div>
        </div>

        {/* ROI breakdown */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0,
          padding: '10px 0',
          borderTop: '1px solid var(--border)', borderBottom: '1px solid var(--border)',
          marginBottom: 14,
        }}>
          {[
            { l: lang === 'ru' ? 'Рост, % / год' : 'Growth, % / yr', v: '+' + p.appreciation + '%' },
            { l: lang === 'ru' ? 'Выход' : 'Exit', v: p.exit + (lang === 'ru' ? ' лет' : ' yr') },
            { l: lang === 'ru' ? 'Срок ROI' : 'ROI in', v: Math.round(100 / (p.yieldGross + p.appreciation)) + (lang === 'ru' ? ' лет' : ' yr') },
          ].map((m, i) => (
            <div key={i} style={{ borderLeft: i > 0 ? '1px solid var(--border)' : 'none', paddingLeft: i > 0 ? 12 : 0 }}>
              <div className="eyebrow" style={{ fontSize: 9, marginBottom: 4 }}>{m.l}</div>
              <div className="mono" style={{ fontSize: 13 }}>{m.v}</div>
            </div>
          ))}
        </div>

        {/* Badges */}
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14 }}>
          {p.badges.map((b) => (
            <span key={b} className="chip mono" style={{ fontSize: 10, height: 22, padding: '0 8px' }}>{b}</span>
          ))}
        </div>

        <div style={{ fontSize: 12, color: 'var(--fg-muted)', marginBottom: 14 }}>
          <span style={{ color: 'var(--accent)' }}>✓</span> {lang === 'ru' ? 'Даёт право на' : 'Eligible for'}: {p.eligible[lang]}
        </div>

        <div style={{ flex: 1 }} />

        <button className="btn btn-line btn-sm" onClick={() => setRoute({ name: 'program', id: p.program })}
                style={{ width: '100%' }}>
          {lang === 'ru' ? 'Программа этой страны' : 'See the program'} →
        </button>
      </div>
    </div>
  );
}

function RealEstateSection({ lang, setRoute }) {
  const [filter, setFilter] = React.useState('all');
  const visible = filter === 'all' ? REAL_ESTATE
                : REAL_ESTATE.filter((p) => p.region[lang === 'ru' ? 'ru' : 'en'] === (filter === 'carib' ? (lang === 'ru' ? 'Карибы' : 'Caribbean')
                                                                                       : filter === 'eu' ? (lang === 'ru' ? 'Европа' : 'Europe')
                                                                                       : filter === 'mena' ? 'MENA' : '_'));
  const tabs = [
    { v: 'all',   l: lang === 'ru' ? 'Все' : 'All' },
    { v: 'carib', l: lang === 'ru' ? 'Карибы' : 'Caribbean' },
    { v: 'eu',    l: lang === 'ru' ? 'Европа' : 'Europe' },
    { v: 'mena',  l: 'MENA' },
  ];

  // Aggregate stats
  const avgYield = (REAL_ESTATE.reduce((a, p) => a + p.yieldGross, 0) / REAL_ESTATE.length).toFixed(1);
  const avgApprec = (REAL_ESTATE.reduce((a, p) => a + p.appreciation, 0) / REAL_ESTATE.length).toFixed(1);
  const minTicket = Math.min(...REAL_ESTATE.map((p) => p.price));
  const cur = (n) => n >= 1e6 ? '$' + (n/1e6).toFixed(2) + 'M' : '$' + (n/1000).toFixed(0) + 'k';

  return (
    <section className="section" style={{ paddingTop: 72, paddingBottom: 48 }}>
      <div className="container-wide">
        <div style={{
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
          marginBottom: 36, flexWrap: 'wrap', gap: 24,
        }}>
          <div style={{ maxWidth: 720 }}>
            <div className="eyebrow" style={{ marginBottom: 12 }}>
              {lang === 'ru' ? '– Инвест-направление · Migronis как площадка' : '– Investment vertical · Migronis as platform'}
            </div>
            <h2 className="display h-2" style={{ margin: 0 }}>
              {lang === 'ru'
                ? <>Не просто <em>агенты</em> <span className="ds">–</span><br/>площадка для ваших инвестиций</>
                : <>Not just <em>agents</em> <span className="ds">–</span><br/>a platform for your investments</>}
            </h2>
            <p style={{ color: 'var(--fg-muted)', fontSize: 16, marginTop: 16, maxWidth: 560, lineHeight: 1.55 }}>
              {lang === 'ru'
                ? 'Через Migronis вы оформляете не только документы, но и подключаетесь к двум собственным направлениям: жилая недвижимость во Флорианополисе (Бразилия) и фонд в Португалии под Golden Visa / HQA. Плюс – каталог одобренных объектов под CBI/RBI.'
                : 'Migronis is not only documents. We are the platform behind two in-house verticals – residential real estate in Florianópolis (Brazil) and a Portugal fund eligible for Golden Visa / HQA. Plus a catalog of CBI/RBI-approved properties.'}
            </p>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, auto)', gap: 24 }}>
            {[
              { l: lang === 'ru' ? 'Средняя доходность' : 'Avg gross yield', v: avgYield + '%' },
              { l: lang === 'ru' ? 'Средний рост' : 'Avg appreciation', v: '+' + avgApprec + '%' },
              { l: lang === 'ru' ? 'Вход от' : 'Entry from', v: cur(minTicket) },
            ].map((m, i) => (
              <div key={i}>
                <div className="eyebrow" style={{ fontSize: 10, marginBottom: 6 }}>{m.l}</div>
                <div className="display" style={{ fontSize: 26, color: 'var(--accent)' }}>{m.v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Migronis in-house verticals – replaces external fund-mention block */}
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0,
          marginBottom: 40,
          borderTop: '1px solid var(--border-strong)',
          borderBottom: '1px solid var(--border-strong)',
        }}>
          {[
            {
              flag: '🇧🇷',
              label: lang === 'ru' ? 'Migronis Real Estate · Бразилия' : 'Migronis Real Estate · Brazil',
              location: 'Florianópolis, Santa Catarina',
              status: lang === 'ru' ? 'Активные продажи' : 'Active sales',
              statusKind: lang === 'ru' ? 'escrow-сервис' : 'escrow service',
              entry: '$200k+',
              yield: lang === 'ru' ? '5–6% аренда + 20–30% перепродажа' : '5–6% rental + 20–30% resale',
              bullets: lang === 'ru'
                ? ['Лицензированное агентство во Флорипе', 'Собственный escrow-сервис', 'Команда Migronis живёт на месте', 'Связка с Brazil Investor Visa']
                : ['Licensed agency in Florianópolis', 'Own escrow service', 'Migronis team lives on site', 'Bundles with Brazil Investor Visa'],
              cta: lang === 'ru' ? 'Подробнее' : 'Learn more',
            },
            {
              flag: '🇵🇹',
              label: lang === 'ru' ? 'Migronis Fund · Португалия' : 'Migronis Fund · Portugal',
              location: 'Lisbon · Cascais',
              status: lang === 'ru' ? 'Открыт для подписки' : 'Open for subscription',
              statusKind: 'Golden Visa / HQA',
              entry: '€500k',
              yield: lang === 'ru' ? '4–7% IRR · 8-летний цикл' : '4–7% IRR · 8-year cycle',
              bullets: lang === 'ru'
                ? ['Регулируется CMVM Португалии', 'Eligible под Golden Visa', 'R&D + редевелопмент исторических зданий', 'Распределение через Migronis']
                : ['Regulated by CMVM Portugal', 'Golden Visa eligible', 'R&D + heritage redevelopment', 'Distributed through Migronis'],
              cta: lang === 'ru' ? 'Запросить деки' : 'Request the deck',
            },
          ].map((v, i) => (
            <div key={i} style={{
              padding: '32px 36px',
              borderRight: i === 0 ? '1px solid var(--border)' : '0',
              background: 'var(--bg-elev-2)',
              display: 'flex', flexDirection: 'column', gap: 18,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16 }}>
                <div>
                  <window.FlagIcon emoji={v.flag} size={24} />
                  <h3 className="display" style={{ fontSize: 28, marginTop: 10, fontWeight: 700, lineHeight: 1.05 }}>{v.label}</h3>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', marginTop: 6 }}>
                    {v.location}
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flexShrink: 0 }}>
                  <div className="mono" style={{
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    fontSize: 11, letterSpacing: '0.04em', textTransform: 'uppercase',
                    color: 'var(--accent)',
                  }}>
                    <span style={{ width: 6, height: 6, background: 'var(--accent)', boxShadow: '0 0 8px var(--accent)' }} />
                    {v.status}
                  </div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--fg-dim)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
                    · {v.statusKind}
                  </div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '6px 24px', paddingTop: 16, borderTop: '1px solid var(--border)' }}>
                <div className="eyebrow" style={{ fontSize: 10 }}>{lang === 'ru' ? 'вход' : 'entry'}</div>
                <div className="mono" style={{ fontSize: 14 }}>{v.entry}</div>
                <div className="eyebrow" style={{ fontSize: 10 }}>{lang === 'ru' ? 'доходность' : 'returns'}</div>
                <div className="mono" style={{ fontSize: 14 }}>{v.yield}</div>
              </div>

              <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
                {v.bullets.map((b, j) => (
                  <li key={j} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13, color: 'var(--fg-muted)' }}>
                    <span style={{ flexShrink: 0, marginTop: 7, width: 4, height: 4, background: 'var(--accent)' }} />
                    <span>{b}</span>
                  </li>
                ))}
              </ul>

              <button className="btn btn-line btn-sm" style={{ alignSelf: 'flex-start', marginTop: 'auto' }}>
                {v.cta} →
              </button>
            </div>
          ))}
        </div>

        {/* Sub-heading for approved-properties catalog */}
        <div className="eyebrow" style={{ marginBottom: 16 }}>
          {lang === 'ru' ? '– Каталог одобренных объектов под CBI / RBI' : '– Catalog of CBI / RBI-approved properties'}
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
          {tabs.map((t) => (
            <button key={t.v} onClick={() => setFilter(t.v)}
              style={{
                padding: '8px 16px', borderRadius: 999, fontSize: 13,
                background: filter === t.v ? 'var(--accent)' : 'transparent',
                color: filter === t.v ? '#FFF8E6' : 'var(--fg-muted)',
                border: `1px solid ${filter === t.v ? 'var(--accent)' : 'var(--border)'}`,
                transition: 'all .15s',
              }}>
              {t.l}
            </button>
          ))}
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 20,
        }}>
          {visible.map((p) => (
            <PropertyCard key={p.id} p={p} lang={lang} setRoute={setRoute} />
          ))}
        </div>

        <div style={{
          marginTop: 22, padding: '14px 18px',
          background: 'var(--accent-soft)', border: '1px solid var(--accent)', borderRadius: 'var(--r-md)',
          fontSize: 13, color: 'var(--fg)', display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span style={{ fontSize: 18 }}>ⓘ</span>
          {lang === 'ru'
            ? 'Доходность и сроки – индикативные, на основе исторических данных за 2020–2025. Финальные условия – в предложении. Размер инвестиций для CBI может отличаться от рыночной цены недвижимости.'
            : 'Yields and exit terms are indicative, based on 2020–2025 historic data. Final terms – in the offer. CBI-required investment may differ from the market price of the property.'}
        </div>
      </div>
    </section>
  );
}

window.RealEstateSection = RealEstateSection;
