const { color: HC, font: HF, r: HR, shadow: HSH, type: HTY } = window.RAYA;
const { LISTINGS: HL, CATEGORIES: HCAT, DESTINATIONS: HD } = window.RAYA_DATA;

const coverOf = (item) => (item.images && item.images[0]) || undefined;

function Greeting({ lang }) {
  const isAr = lang === 'ar';
  return (
    <div style={{ padding: '60px 20px 0', direction: isAr ? 'rtl' : 'ltr' }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        marginBottom: 18,
      }}>
        <RayaLogo size={22} color={HC.brand} lang={lang} />
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="raya-btn" style={{
            width: 40, height: 40, borderRadius: HR.pill, border: `1px solid ${HC.ink10}`,
            background: HC.white, display: 'grid', placeItems: 'center', cursor: 'pointer',
          }}>
            <RIcon name="bell" size={18} color={HC.ink} />
          </button>
        </div>
      </div>
      <div style={{
        fontFamily: HF.bodyEn, fontSize: 12, color: HC.ink60,
        letterSpacing: 1.2, textTransform: 'uppercase', marginBottom: 4,
      }}>
        {isAr ? 'أهلاً بيك في راية' : 'Welcome to Raya'}
      </div>
      <h1 style={{
        margin: 0,
        fontFamily: isAr ? HF.displayAr : HF.displayEn,
        fontSize: isAr ? 30 : 34, fontWeight: isAr ? 700 : 400, color: HC.ink,
        lineHeight: isAr ? HTY.arDisplayLine : HTY.enDisplayLine,
        letterSpacing: isAr ? HTY.arDisplayTrack : -1,
        fontStyle: isAr ? 'normal' : 'italic',
      }}>
        {isAr ? 'رحلتك الجاية،' : 'Your next escape,'}
        <br/>
        <span style={{ fontStyle: 'normal', fontWeight: isAr ? 400 : 300, color: HC.ink60 }}>
          {isAr ? 'تبدأ من هنا.' : 'starts here.'}
        </span>
      </h1>
    </div>
  );
}

function SearchBar({ lang, onFocus }) {
  const isAr = lang === 'ar';
  return (
    <div style={{ padding: '20px', direction: isAr ? 'rtl' : 'ltr' }}>
      <button
        onClick={onFocus}
        className="raya-tap"
        style={{
          width: '100%', padding: '14px 18px', borderRadius: HR.pill,
          background: HC.white, border: `1px solid ${HC.ink10}`,
          display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
          boxShadow: '0 1px 3px rgba(10,22,40,0.04)',
        }}
      >
        <RIcon name="search" size={18} color={HC.ink60} />
        <span style={{
          flex: 1, textAlign: isAr ? 'right' : 'left',
          fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
          fontSize: 14, color: HC.ink60,
        }}>
          {isAr ? 'ابحث عن وجهتك القادمة...' : 'Search your next escape...'}
        </span>
        <div style={{
          width: 28, height: 28, borderRadius: HR.pill,
          background: HC.ink, display: 'grid', placeItems: 'center',
        }}>
          <RIcon name="sliders" size={14} color={HC.paper} sw={2} />
        </div>
      </button>
    </div>
  );
}

const DESTINATION_COVERS = {
  d1: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1200&auto=format&fit=crop&q=80',
  d2: 'https://images.unsplash.com/photo-1519046904884-53103b34b206?w=1200&auto=format&fit=crop&q=80',
  d3: 'https://images.unsplash.com/photo-1540541338287-41700207dee6?w=1200&auto=format&fit=crop&q=80',
};

function DestinationHero({ destinations, active, setActive, lang, onOpen }) {
  const isAr = lang === 'ar';
  const d = destinations[active];
  return (
    <div style={{ padding: '0 20px', direction: isAr ? 'rtl' : 'ltr' }}>
      <div style={{
        position: 'relative', height: 260, borderRadius: HR.xl, overflow: 'hidden',
        boxShadow: HSH.card,
      }}>
        <RImage tone={d.tone} image={DESTINATION_COVERS[d.id]} rounded={HR.xl} style={{ position: 'absolute', inset: 0 }} />
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(135deg, rgba(0,0,0,0) 45%, rgba(10,22,40,0.55) 80%, rgba(10,22,40,0.82))',
        }}/>
        <div style={{
          position: 'absolute', top: 16, [isAr ? 'right' : 'left']: 16,
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '5px 10px', borderRadius: HR.pill,
          background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)',
          fontFamily: HF.bodyEn, fontSize: 10, fontWeight: 600, color: HC.ink,
          letterSpacing: 1.2, textTransform: 'uppercase',
        }}>
          <RIcon name="sparkle" size={10} color={HC.brand} sw={2} />
          {isAr ? 'وجهة مميزة' : 'Featured destination'}
        </div>
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0, padding: 20,
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between',
          flexDirection: isAr ? 'row-reverse' : 'row',
        }}>
          <div style={{ textAlign: isAr ? 'right' : 'left' }}>
            <div style={{
              fontFamily: HF.bodyEn, fontSize: 10, color: 'rgba(255,255,255,0.7)',
              letterSpacing: 1.5, textTransform: 'uppercase', marginBottom: 4,
            }}>
              {isAr ? d.tagline_ar : d.tagline_en}
            </div>
            <h2 style={{
              margin: 0,
              fontFamily: isAr ? HF.displayAr : HF.displayEn,
              fontSize: isAr ? 26 : 28, fontWeight: isAr ? 700 : 400, color: HC.white,
              letterSpacing: isAr ? 0 : -0.5,
              lineHeight: isAr ? 1.25 : 1.1,
              fontStyle: isAr ? 'normal' : 'italic',
              textShadow: '0 2px 12px rgba(10,22,40,0.4)',
            }}>
              {isAr ? d.ar : d.en}
            </h2>
            <div style={{
              marginTop: 6,
              fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
              fontSize: 12, color: 'rgba(255,255,255,0.85)',
            }}>
              {d.stays} {isAr ? 'مكان للإقامة' : 'stays available'}
            </div>
          </div>
          <button onClick={onOpen} className="raya-btn" style={{
            width: 48, height: 48, borderRadius: HR.pill,
            background: HC.white, border: 'none', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            <RIcon name={isAr ? 'arrowLeft' : 'arrowRight'} size={18} color={HC.ink} sw={2} />
          </button>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 6, justifyContent: 'center', marginTop: 14 }}>
        {destinations.map((_, i) => (
          <button key={i} onClick={() => setActive(i)} style={{
            width: i === active ? 20 : 6, height: 6, borderRadius: HR.pill,
            background: i === active ? HC.ink : HC.ink20, border: 'none',
            cursor: 'pointer', padding: 0, transition: 'width 0.24s',
          }}/>
        ))}
      </div>
    </div>
  );
}

function CategoryStrip({ cats, active, setActive, lang }) {
  const isAr = lang === 'ar';
  return (
    <div className="raya-scroll" style={{
      display: 'flex', gap: 4, overflowX: 'auto', padding: '20px 16px 12px',
      direction: isAr ? 'rtl' : 'ltr',
    }}>
      {cats.map(c => (
        <CategoryTile key={c.id} cat={c} active={active === c.id}
          onClick={() => setActive(c.id)} lang={lang} />
      ))}
    </div>
  );
}

function FeaturedCard({ item, lang, onOpen, onFav, fav }) {
  const isAr = lang === 'ar';
  return (
    <div
      onClick={onOpen}
      className="raya-card"
      style={{
        margin: '0 20px 16px', borderRadius: HR.lg, overflow: 'hidden',
        background: HC.white, boxShadow: HSH.card, cursor: 'pointer',
        direction: isAr ? 'rtl' : 'ltr',
      }}
    >
      <div style={{ position: 'relative', height: 220 }}>
        <RImage tone={item.tone} image={coverOf(item)} rounded={0} style={{ position: 'absolute', inset: 0 }} />
        <div style={{
          position: 'absolute', top: 14, [isAr ? 'left' : 'right']: 14,
        }}>
          <HeartBtn active={fav} onClick={onFav} light />
        </div>
        {item.badges_en && (
          <div style={{
            position: 'absolute', top: 14, [isAr ? 'right' : 'left']: 14,
            padding: '5px 10px', borderRadius: HR.pill,
            background: HC.gold, fontFamily: HF.bodyEn, fontSize: 10,
            fontWeight: 600, color: HC.ink, letterSpacing: 1,
            textTransform: 'uppercase',
          }}>
            {isAr ? item.badges_ar[0] : item.badges_en[0]}
          </div>
        )}
      </div>
      <div style={{ padding: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
          <h3 style={{
            margin: 0,
            fontFamily: isAr ? HF.displayAr : HF.displayEn,
            fontSize: isAr ? 18 : 20, fontWeight: isAr ? 700 : 500, color: HC.ink,
            letterSpacing: isAr ? 0 : -0.3,
            lineHeight: isAr ? 1.3 : 1.2,
          }}>{isAr ? item.title_ar : item.title_en}</h3>
          <RatingChip rating={item.rating} reviews={item.reviews} lang={lang}/>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 4,
          fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
          fontSize: 13, color: HC.ink60, marginBottom: 14,
        }}>
          <RIcon name="pin" size={12} color={HC.ink40} sw={1.8}/>
          {isAr ? item.location_ar : item.location_en}
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 14,
          padding: '12px 0', borderTop: `1px solid ${HC.ink10}`,
          borderBottom: `1px solid ${HC.ink10}`,
          marginBottom: 14,
        }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: isAr ? HF.bodyAr : HF.bodyEn, fontSize: 12, color: HC.ink60 }}>
            <RIcon name="bed" size={15} color={HC.ink60} sw={1.6}/>
            {item.beds} {isAr ? 'غرف' : 'beds'}
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: isAr ? HF.bodyAr : HF.bodyEn, fontSize: 12, color: HC.ink60 }}>
            <RIcon name="bath" size={15} color={HC.ink60} sw={1.6}/>
            {item.baths} {isAr ? 'حمامات' : 'baths'}
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: isAr ? HF.bodyAr : HF.bodyEn, fontSize: 12, color: HC.ink60 }}>
            <RIcon name="ruler" size={15} color={HC.ink60} sw={1.6}/>
            {item.sqm}m²
          </span>
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div>
            <span style={{
              fontFamily: HF.displayEn, fontSize: 22, fontWeight: 500,
              color: HC.ink, letterSpacing: -0.3,
            }}>{window.RAYA_CURRENCY.formatPrice(item.price, window.__rayaCurrency || 'EGP')}</span>
            <span style={{
              fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
              fontSize: 12, color: HC.ink60, marginLeft: isAr ? 0 : 4, marginRight: isAr ? 4 : 0,
            }}>{isAr ? item.unit_ar : item.unit_en}</span>
          </div>
          <div style={{
            padding: '8px 16px', borderRadius: HR.pill, background: HC.ink,
            color: HC.paper, fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
            fontSize: 12, fontWeight: 600,
          }}>
            {isAr ? 'احجز' : 'Reserve'}
          </div>
        </div>
      </div>
    </div>
  );
}

function ListingCard({ item, lang, compact, onOpen, onFav, fav }) {
  const isAr = lang === 'ar';
  const w = compact ? 170 : 210;
  return (
    <div
      onClick={onOpen}
      className="raya-card"
      style={{
        width: w, flexShrink: 0, cursor: 'pointer',
        direction: isAr ? 'rtl' : 'ltr',
      }}
    >
      <div style={{ position: 'relative', height: compact ? 160 : 200, borderRadius: HR.md, overflow: 'hidden', marginBottom: 10 }}>
        <RImage tone={item.tone} image={coverOf(item)} rounded={0} style={{ position: 'absolute', inset: 0 }} />
        <div style={{ position: 'absolute', top: 10, [isAr ? 'left' : 'right']: 10 }}>
          <HeartBtn active={fav} onClick={onFav} size={30} light />
        </div>
        {item.price && (
          <div style={{
            position: 'absolute', bottom: 10, [isAr ? 'right' : 'left']: 10,
            padding: '5px 10px', borderRadius: HR.sm,
            background: 'rgba(255,255,255,0.95)', backdropFilter: 'blur(8px)',
            fontFamily: HF.bodyEn, fontSize: 12, fontWeight: 600, color: HC.ink,
          }}>
            {window.RAYA_CURRENCY.formatPrice(item.price, window.__rayaCurrency || 'EGP')}
            <span style={{ color: HC.ink60, fontWeight: 400 }}>
              {isAr ? item.unit_ar : item.unit_en}
            </span>
          </div>
        )}
      </div>
      <div style={{ padding: '0 2px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 2 }}>
          <h4 style={{
            margin: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
            fontSize: 14, fontWeight: 600, color: HC.ink,
          }}>{isAr ? item.title_ar : item.title_en}</h4>
          <RatingChip rating={item.rating} compact lang={lang}/>
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 3,
          fontFamily: isAr ? HF.bodyAr : HF.bodyEn,
          fontSize: 12, color: HC.ink60,
        }}>
          <RIcon name="pin" size={10} color={HC.ink40} sw={1.8}/>
          {isAr ? item.location_ar : item.location_en}
        </div>
      </div>
    </div>
  );
}

function ScrollRow({ title, items, lang, favs, onFav, onOpen, compact, onSeeAll }) {
  const isAr = lang === 'ar';
  return (
    <div style={{ marginBottom: 28, direction: isAr ? 'rtl' : 'ltr' }}>
      <SectionHeader title={title} action={isAr ? 'شوف الكل' : 'View all'} lang={lang} onAction={onSeeAll}/>
      <div className="raya-scroll" style={{
        display: 'flex', gap: 14, overflowX: 'auto', padding: '0 20px 4px',
      }}>
        {items.map(it => (
          <ListingCard key={it.id} item={it} lang={lang} compact={compact}
            fav={favs.has(it.id)}
            onFav={() => onFav(it.id)}
            onOpen={() => onOpen(it)}
          />
        ))}
      </div>
    </div>
  );
}

function HomeScreen({ lang, favs, toggleFav, openListing, openSearch }) {
  const [heroIdx, setHeroIdx] = React.useState(0);
  const [cat, setCat] = React.useState('stays');

  return (
    <div style={{ paddingBottom: 120, background: HC.paper, minHeight: '100%' }}>
      <Greeting lang={lang} />
      <SearchBar lang={lang} onFocus={() => openSearch()}/>
      <DestinationHero destinations={HD} active={heroIdx} setActive={setHeroIdx} lang={lang}
        onOpen={() => openSearch()}/>
      <CategoryStrip cats={HCAT} active={cat} setActive={(id) => { setCat(id); openSearch(id); }} lang={lang}/>

      <FeaturedCard item={HL.stays[0]} lang={lang}
        fav={favs.has(HL.stays[0].id)}
        onFav={() => toggleFav(HL.stays[0].id)}
        onOpen={() => openListing(HL.stays[0])}
      />

      <ScrollRow title={lang === 'ar' ? 'شقق وفنادق' : 'Stays to love'}
        items={HL.stays.slice(1)} lang={lang}
        favs={favs} onFav={toggleFav} onOpen={openListing}
        onSeeAll={() => openSearch('stays')}/>

      <ScrollRow title={lang === 'ar' ? 'شواطئ' : 'Beach clubs'}
        items={HL.beaches} lang={lang} compact
        favs={favs} onFav={toggleFav} onOpen={openListing}
        onSeeAll={() => openSearch('beaches')}/>

      <ScrollRow title={lang === 'ar' ? 'رحلات عائلية' : 'Family trips'}
        items={HL.trips} lang={lang} compact
        favs={favs} onFav={toggleFav} onOpen={openListing}
        onSeeAll={() => openSearch('trips')}/>

      <ScrollRow title={lang === 'ar' ? 'أنشطة' : 'Experiences'}
        items={HL.activities} lang={lang} compact
        favs={favs} onFav={toggleFav} onOpen={openListing}
        onSeeAll={() => openSearch('activities')}/>
    </div>
  );
}

window.HomeScreen = HomeScreen;
