const { color: DC, font: DF, r: DR, shadow: DSH } = window.RAYA;
const {
  AMENITIES: DA, HOUSE_RULES: DHR,
  TRIP_INCLUDES: DTI, ACTIVITY_INCLUDES: DAI, BEACH_FACILITIES: DBF,
} = window.RAYA_DATA;
const DCFG = window.RAYA_CONFIG;
const DCOORDS = window.RAYA_COORDS;

function Gallery({ item, lang, onBack, onFav, fav, onShare }) {
  const [idx, setIdx] = React.useState(0);
  const isAr = lang === 'ar';
  const images = (item.images && item.images.length) ? item.images : [null];
  const tones  = (item.tones  && item.tones.length)  ? item.tones  : [item.tone];
  const total  = images.length;
  const go = (dir) => setIdx((idx + dir + total) % total);

  return (
    <div style={{ position: 'relative', height: 380, overflow: 'hidden' }}>
      <RImage
        tone={tones[idx % tones.length] || item.tone}
        image={images[idx]}
        rounded={0}
        style={{ position: 'absolute', inset: 0 }}
      />

      <div style={{
        position: 'absolute', top: 62, left: 0, right: 0, padding: '0 20px',
        display: 'flex', justifyContent: 'space-between',
        flexDirection: isAr ? 'row-reverse' : 'row',
      }}>
        <button onClick={onBack} className="raya-btn" aria-label="back" style={{
          width: 40, height: 40, borderRadius: DR.pill,
          background: 'rgba(255,255,255,0.95)', border: 'none', cursor: 'pointer',
          display: 'grid', placeItems: 'center',
        }}>
          <RIcon name={isAr ? 'chevronRight' : 'chevronLeft'} size={18} color={DC.ink}/>
        </button>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={onShare} className="raya-btn" aria-label="share" style={{
            width: 40, height: 40, borderRadius: DR.pill,
            background: 'rgba(255,255,255,0.95)', border: 'none', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            <RIcon name="share" size={16} color={DC.ink}/>
          </button>
          <HeartBtn active={fav} onClick={onFav} light size={40}/>
        </div>
      </div>

      {total > 1 && (
        <>
          <button onClick={() => go(-1)} aria-label="previous" className="raya-btn" style={{
            position: 'absolute', top: '50%', [isAr ? 'right' : 'left']: 12,
            transform: 'translateY(-50%)',
            width: 36, height: 36, borderRadius: DR.pill, border: 'none',
            background: 'rgba(255,255,255,0.9)', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            <RIcon name={isAr ? 'chevronRight' : 'chevronLeft'} size={16} color={DC.ink}/>
          </button>
          <button onClick={() => go(1)} aria-label="next" className="raya-btn" style={{
            position: 'absolute', top: '50%', [isAr ? 'left' : 'right']: 12,
            transform: 'translateY(-50%)',
            width: 36, height: 36, borderRadius: DR.pill, border: 'none',
            background: 'rgba(255,255,255,0.9)', cursor: 'pointer',
            display: 'grid', placeItems: 'center',
          }}>
            <RIcon name={isAr ? 'chevronLeft' : 'chevronRight'} size={16} color={DC.ink}/>
          </button>
        </>
      )}

      <div style={{
        position: 'absolute', bottom: 20, left: '50%', transform: 'translateX(-50%)',
        display: 'flex', gap: 4, padding: '5px 10px', borderRadius: DR.pill,
        background: 'rgba(10,22,40,0.5)', backdropFilter: 'blur(8px)',
      }}>
        {images.map((_, i) => (
          <button key={i} onClick={() => setIdx(i)} aria-label={`image ${i + 1}`} style={{
            width: i === idx ? 18 : 6, height: 6, borderRadius: DR.pill,
            background: i === idx ? DC.white : 'rgba(255,255,255,0.5)',
            border: 'none', cursor: 'pointer', padding: 0, transition: 'width 0.2s',
          }}/>
        ))}
      </div>

      <div style={{
        position: 'absolute', bottom: 20,
        right: isAr ? undefined : 20, left: isAr ? 20 : undefined,
        padding: '4px 10px', borderRadius: DR.pill,
        background: 'rgba(10,22,40,0.5)', backdropFilter: 'blur(8px)',
        fontFamily: DF.bodyEn, fontSize: 11, fontWeight: 500, color: DC.white,
        direction: 'ltr',
      }}>{idx + 1} / {total}</div>
    </div>
  );
}

function StatCard({ icon, value, label, lang }) {
  const isAr = lang === 'ar';
  return (
    <div style={{
      padding: 14, borderRadius: DR.md,
      background: DC.white, border: `1px solid ${DC.ink10}`,
      textAlign: 'center',
    }}>
      <RIcon name={icon} size={20} color={DC.brand} sw={1.6}/>
      <div style={{
        fontFamily: DF.displayEn, fontSize: 18, fontWeight: 500,
        color: DC.ink, marginTop: 6,
      }}>{value}</div>
      <div style={{
        fontFamily: isAr ? DF.bodyAr : DF.bodyEn,
        fontSize: 11, color: DC.ink60,
      }}>{label}</div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <h3 style={{
        margin: '0 0 12px', fontSize: 18, fontWeight: 500, color: DC.ink,
      }}>{title}</h3>
      {children}
    </div>
  );
}

function MapPreview({ item, lang }) {
  const isAr = lang === 'ar';
  const coord = DCOORDS[item.id];
  const { bounds } = DCFG.map;
  const pos = coord ? {
    x: ((coord[1] - bounds.west)  / (bounds.east  - bounds.west))  * 100,
    y: ((bounds.north - coord[0]) / (bounds.north - bounds.south)) * 100,
  } : { x: 50, y: 50 };

  return (
    <div style={{
      height: 170, borderRadius: DR.md, overflow: 'hidden',
      background: `linear-gradient(180deg, ${DC.cream} 0%, #E0ECFF 100%)`,
      position: 'relative', border: `1px solid ${DC.ink10}`,
    }}>
      <svg viewBox="0 0 400 170" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
        style={{ position: 'absolute', inset: 0 }}>
        {/* Mediterranean sea stripe */}
        <rect x="0" y="0" width="400" height="55" fill="#CFE3FA"/>
        {/* coastline */}
        <path d="M0 55 Q60 62 120 58 T240 62 T360 58 T400 55 L400 170 L0 170 Z"
          fill={DC.cream} stroke={DC.ink20} strokeWidth="1"/>
        {/* roads */}
        <path d="M0 95 Q100 90 200 95 T400 92" fill="none" stroke={DC.ink20} strokeWidth="1"/>
        <path d="M0 130 Q150 122 300 128 T400 125" fill="none" stroke={DC.ink20} strokeWidth="1" strokeDasharray="4 4"/>
      </svg>
      {/* pin */}
      <div style={{
        position: 'absolute', left: pos.x + '%', top: pos.y + '%',
        transform: 'translate(-50%, -100%)',
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
      }}>
        <div style={{
          padding: '4px 10px', borderRadius: DR.pill,
          background: DC.white, boxShadow: DSH.card,
          fontFamily: isAr ? DF.bodyAr : DF.bodyEn,
          fontSize: 11, fontWeight: 500, color: DC.ink, whiteSpace: 'nowrap',
        }}>{isAr ? item.location_ar : item.location_en}</div>
        <div style={{
          width: 34, height: 34, borderRadius: DR.pill,
          background: DC.brand, display: 'grid', placeItems: 'center',
          boxShadow: '0 6px 16px rgba(0,104,255,0.35)',
        }}>
          <RIcon name="pin" size={16} color={DC.white} sw={2}/>
        </div>
      </div>
    </div>
  );
}

function DetailsScreen({ item, lang, currency = 'EGP', onBack, favs, toggleFav, onBook }) {
  const isAr = lang === 'ar';
  const fav = favs.has(item.id);

  const title    = isAr ? item.title_ar    : item.title_en;
  const location = isAr ? item.location_ar : item.location_en;
  const descText = isAr ? item.description_ar : item.description_en;
  const host     = isAr ? item.host_ar : item.host_en;
  const badge    = item.badges_ar && item.badges_en && (isAr ? item.badges_ar[0] : item.badges_en[0]);

  const category = item.category
    || (item.beds != null ? 'stays'
        : item.duration_en && item.meeting_point_en ? 'trips'
        : item.duration_en ? 'activities'
        : 'beaches');
  const isStay     = category === 'stays';
  const isTrip     = category === 'trips';
  const isActivity = category === 'activities';
  const isBeach    = category === 'beaches';

  const stats = [];
  if (isStay) {
    if (item.guests != null) stats.push({ icon: 'user',  v: item.guests,     l: isAr ? 'ضيوف'    : 'Guests' });
    if (item.beds   != null) stats.push({ icon: 'bed',   v: item.beds,       l: isAr ? 'غرف نوم' : 'Bedrooms' });
    if (item.baths  != null) stats.push({ icon: 'bath',  v: item.baths,      l: isAr ? 'حمامات'  : 'Baths' });
    if (item.sqm    != null) stats.push({ icon: 'ruler', v: item.sqm + 'm²', l: isAr ? 'المساحة' : 'Area' });
  } else if (isTrip) {
    if (item.duration_en)   stats.push({ icon: 'calendar', v: isAr ? item.duration_ar   : item.duration_en,   l: isAr ? 'المدة'        : 'Duration' });
    if (item.group_size_en) stats.push({ icon: 'user',     v: isAr ? item.group_size_ar : item.group_size_en, l: isAr ? 'حجم المجموعة' : 'Group size' });
  } else if (isActivity) {
    if (item.duration_en) stats.push({ icon: 'calendar', v: isAr ? item.duration_ar : item.duration_en, l: isAr ? 'المدة'   : 'Duration' });
    if (item.level_en)    stats.push({ icon: 'activity', v: isAr ? item.level_ar    : item.level_en,    l: isAr ? 'المستوى' : 'Level' });
    if (item.age_en)      stats.push({ icon: 'user',     v: isAr ? item.age_ar      : item.age_en,      l: isAr ? 'العمر'   : 'Ages' });
  } else if (isBeach) {
    if (item.best_time_en) stats.push({ icon: 'sun',  v: isAr ? item.best_time_ar : item.best_time_en, l: isAr ? 'أفضل وقت' : 'Best time' });
    if (item.sand_en)      stats.push({ icon: 'palm', v: isAr ? item.sand_ar      : item.sand_en,      l: isAr ? 'النوع'   : 'Type' });
  }

  const roomRows = isStay ? [
    { icon: 'bed',   l_ar: 'غرف النوم',       l_en: 'Bedrooms',       v: item.beds, suf_ar: item.beds === 1 ? 'غرفة' : item.beds === 2 ? 'غرفتين' : 'غرف' },
    { icon: 'user',  l_ar: 'تستوعب',           l_en: 'Sleeps up to',   v: item.guests, suf_ar: item.guests === 1 ? 'ضيف' : item.guests === 2 ? 'ضيفين' : 'ضيوف' },
    { icon: 'bath',  l_ar: 'حمامات',           l_en: 'Bathrooms',      v: item.baths, suf_ar: item.baths === 1 ? 'حمام' : item.baths === 2 ? 'حمامين' : 'حمامات' },
    { icon: 'ruler', l_ar: 'المساحة الإجمالية', l_en: 'Total area',     v: item.sqm ? item.sqm + ' m²' : null, suf_ar: '' },
  ].filter(r => r.v != null) : [];

  const inclusionItems = isTrip ? DTI : isActivity ? DAI : null;
  const inclusionTitle = isAr ? 'المشمول في السعر' : "What's included";
  const facilityItems  = isBeach ? DBF : null;
  const facilityTitle  = isAr ? 'خدمات ومرافق الشاطئ' : 'Beach facilities';

  const amenityItems = isStay ? DA : null;
  const amenityTitle = isAr ? 'المميزات' : "What's included";
  const showHouseRules = isStay;

  return (
    <div style={{
      background: DC.paper, minHeight: '100%', paddingBottom: 120,
      direction: isAr ? 'rtl' : 'ltr',
      textAlign: isAr ? 'right' : 'left',
    }}>
      <Gallery item={item} lang={lang} onBack={onBack} onFav={() => toggleFav(item.id)} fav={fav}/>

      <div style={{
        padding: '22px 20px',
        fontFamily: isAr ? DF.bodyAr : DF.bodyEn,
      }}>
        {badge && (
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            padding: '4px 10px', borderRadius: DR.pill,
            background: DC.brandSoft, marginBottom: 12,
            fontSize: 11, fontWeight: 600, color: DC.brand,
            letterSpacing: isAr ? 0 : 0.5, textTransform: isAr ? 'none' : 'uppercase',
          }}>
            <RIcon name="flame" size={11} color={DC.brand} sw={2}/>
            {badge}
          </div>
        )}

        <h1 style={{
          margin: '0 0 8px',
          fontFamily: isAr ? DF.displayAr : DF.displayEn,
          fontSize: 26, fontWeight: 500, color: DC.ink,
          letterSpacing: isAr ? 0 : -0.5, lineHeight: 1.2,
        }}>{title}</h1>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20,
          flexDirection: isAr ? 'row-reverse' : 'row', flexWrap: 'wrap',
          justifyContent: isAr ? 'flex-end' : 'flex-start',
        }}>
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            fontSize: 13, color: DC.ink60,
          }}>
            <RIcon name="pin" size={13} color={DC.ink60} sw={1.8}/>
            {location}
          </span>
          <span style={{ width: 3, height: 3, borderRadius: DR.pill, background: DC.ink20 }}/>
          <RatingChip rating={item.rating} reviews={item.reviews} lang={lang}/>
        </div>

        {stats.length > 0 && (
          <div style={{
            display: 'grid',
            gridTemplateColumns: `repeat(${Math.min(stats.length, 4)}, 1fr)`,
            gap: 10, marginBottom: 24,
          }}>
            {stats.slice(0, 4).map((s, i) => (
              <StatCard key={i} icon={s.icon} value={s.v} label={s.l} lang={lang}/>
            ))}
          </div>
        )}

        {roomRows.length > 0 && (
          <Section title={isAr ? 'تفاصيل الوحدة' : 'Unit details'}>
            <div style={{
              background: DC.white, border: `1px solid ${DC.ink10}`,
              borderRadius: DR.md, overflow: 'hidden',
            }}>
              {roomRows.map((r, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '13px 14px',
                  borderBottom: i < roomRows.length - 1 ? `1px solid ${DC.ink10}` : 'none',
                  flexDirection: isAr ? 'row-reverse' : 'row',
                }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: DR.sm,
                    background: DC.brandSoft, display: 'grid', placeItems: 'center', flexShrink: 0,
                  }}>
                    <RIcon name={r.icon} size={16} color={DC.brand} sw={1.7}/>
                  </div>
                  <div style={{ flex: 1, fontSize: 13, color: DC.ink60 }}>
                    {isAr ? r.l_ar : r.l_en}
                  </div>
                  <div style={{
                    fontFamily: DF.displayEn, fontSize: 15, fontWeight: 600, color: DC.ink,
                  }}>
                    {typeof r.v === 'number' ? (isAr ? `${r.v} ${r.suf_ar}` : r.v) : r.v}
                  </div>
                </div>
              ))}
            </div>
          </Section>
        )}

        {isTrip && item.meeting_point_en && (
          <Section title={isAr ? 'نقطة الانطلاق' : 'Meeting point'}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '14px 16px', borderRadius: DR.md,
              background: DC.white, border: `1px solid ${DC.ink10}`,
              flexDirection: isAr ? 'row-reverse' : 'row',
            }}>
              <div style={{
                width: 38, height: 38, borderRadius: DR.pill,
                background: DC.brandSoft, display: 'grid', placeItems: 'center', flexShrink: 0,
              }}>
                <RIcon name="pin" size={17} color={DC.brand} sw={1.8}/>
              </div>
              <div style={{ flex: 1, fontSize: 14, color: DC.ink, lineHeight: 1.5 }}>
                {isAr ? item.meeting_point_ar : item.meeting_point_en}
              </div>
            </div>
          </Section>
        )}

        {host && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: 14, borderRadius: DR.md,
            background: DC.white, border: `1px solid ${DC.ink10}`,
            marginBottom: 24,
            flexDirection: isAr ? 'row-reverse' : 'row',
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: DR.pill,
              background: `linear-gradient(135deg, ${DC.brand}, oklch(0.55 0.18 260))`,
              color: DC.white, display: 'grid', placeItems: 'center',
              fontFamily: DF.displayEn, fontSize: 17, fontWeight: 500, flexShrink: 0,
            }}>{host.trim().charAt(0)}</div>
            <div style={{ flex: 1, textAlign: isAr ? 'right' : 'left' }}>
              <div style={{ fontSize: 11, color: DC.ink60 }}>{isAr ? 'يستضيفك' : 'Hosted by'}</div>
              <div style={{ fontSize: 15, fontWeight: 600, color: DC.ink, marginTop: 2 }}>{host}</div>
            </div>
            <div style={{
              padding: '4px 10px', borderRadius: DR.pill,
              background: DC.brandSoft,
              fontSize: 11, fontWeight: 600, color: DC.brand,
            }}>{isAr ? 'مضيف موثّق' : 'Verified host'}</div>
          </div>
        )}

        {descText && (
          <Section title={isAr ? 'عن المكان' : 'About this place'}>
            <p style={{
              margin: 0, fontSize: 14, lineHeight: 1.7, color: DC.ink80,
              whiteSpace: 'pre-line',
            }}>{descText}</p>
          </Section>
        )}

        {amenityItems && (
          <Section title={amenityTitle}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {amenityItems.map((a, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 12px', borderRadius: DR.sm,
                  background: DC.white, border: `1px solid ${DC.ink10}`,
                  flexDirection: isAr ? 'row-reverse' : 'row',
                }}>
                  <RIcon name={a.icon} size={18} color={DC.ink80} sw={1.6}/>
                  <span style={{ fontSize: 13, color: DC.ink }}>{isAr ? a.ar : a.en}</span>
                </div>
              ))}
            </div>
          </Section>
        )}

        {inclusionItems && (
          <Section title={inclusionTitle}>
            <div style={{
              background: DC.white, border: `1px solid ${DC.ink10}`,
              borderRadius: DR.md, overflow: 'hidden',
            }}>
              {inclusionItems.map((a, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 14px',
                  borderBottom: i < inclusionItems.length - 1 ? `1px solid ${DC.ink10}` : 'none',
                  flexDirection: isAr ? 'row-reverse' : 'row',
                }}>
                  <div style={{
                    width: 30, height: 30, borderRadius: DR.pill,
                    background: 'oklch(0.95 0.08 145)', display: 'grid', placeItems: 'center', flexShrink: 0,
                  }}>
                    <RIcon name="check" size={14} color="oklch(0.5 0.15 145)" sw={2.4}/>
                  </div>
                  <span style={{ flex: 1, fontSize: 13, color: DC.ink }}>{isAr ? a.ar : a.en}</span>
                </div>
              ))}
            </div>
          </Section>
        )}

        {facilityItems && (
          <Section title={facilityTitle}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {facilityItems.map((a, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 12px', borderRadius: DR.sm,
                  background: DC.white, border: `1px solid ${DC.ink10}`,
                  flexDirection: isAr ? 'row-reverse' : 'row',
                }}>
                  <RIcon name={a.icon} size={18} color={DC.ink80} sw={1.6}/>
                  <span style={{ fontSize: 13, color: DC.ink }}>{isAr ? a.ar : a.en}</span>
                </div>
              ))}
            </div>
          </Section>
        )}

        {showHouseRules && (
          <Section title={isAr ? 'قواعد المكان' : 'House rules'}>
            <div style={{
              background: DC.white, border: `1px solid ${DC.ink10}`,
              borderRadius: DR.md, overflow: 'hidden',
            }}>
              {DHR.map((r, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 14px',
                  borderBottom: i < DHR.length - 1 ? `1px solid ${DC.ink10}` : 'none',
                  flexDirection: isAr ? 'row-reverse' : 'row',
                }}>
                  <RIcon name={r.icon} size={17} color={DC.brand} sw={1.7}/>
                  <span style={{ fontSize: 13, color: DC.ink }}>{isAr ? r.ar : r.en}</span>
                </div>
              ))}
            </div>
          </Section>
        )}

        <Section title={isAr ? 'الموقع' : 'Location'}>
          <MapPreview item={item} lang={lang}/>
        </Section>
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 20px 28px', background: 'rgba(255,255,255,0.92)',
        backdropFilter: 'blur(14px)', borderTop: `1px solid ${DC.ink10}`,
        display: 'flex', gap: 12, alignItems: 'center',
        flexDirection: isAr ? 'row-reverse' : 'row',
      }}>
        <div style={{ flex: 1 }}>
          <div style={{
            fontFamily: DF.displayEn, fontSize: 22, fontWeight: 500,
            color: DC.ink, letterSpacing: -0.3,
          }}>
            {window.RAYA_CURRENCY.formatPrice(item.price, currency || 'EGP')}
            <span style={{
              fontFamily: isAr ? DF.bodyAr : DF.bodyEn,
              fontSize: 12, fontWeight: 400, color: DC.ink60,
              marginLeft: isAr ? 0 : 4, marginRight: isAr ? 4 : 0,
            }}>{isAr ? (item.unit_ar || '/الليلة') : (item.unit_en || '/night')}</span>
          </div>
          <div style={{
            fontFamily: isAr ? DF.bodyAr : DF.bodyEn,
            fontSize: 11, color: DC.ink60,
          }}>{isAr ? 'السعر النهائي شامل كل الرسوم' : 'Final price, all fees included'}</div>
        </div>
        <RButton variant="brand" size="lg" lang={lang} onClick={onBook}
          icon={<RIcon name="calendar" size={16} color={DC.white} sw={2}/>}>
          {isAr ? 'احجز دلوقتي' : 'Reserve now'}
        </RButton>
      </div>
    </div>
  );
}

window.DetailsScreen = DetailsScreen;
