const { color: EC, font: EF, r: ER, shadow: ES, type: ETY } = window.RAYA;
const { LISTINGS: EL, CATEGORIES: ECAT } = window.RAYA_DATA;
const ECFG = window.RAYA_CONFIG;
const ECOORDS = window.RAYA_COORDS;

const CATEGORY_OF = {};
Object.keys(EL).forEach(k => EL[k].forEach(it => { CATEGORY_OF[it.id] = k; }));

function MapView({ filtered, currency, lang, openListing }) {
  const isAr = lang === 'ar';
  const { bounds, tileUrl } = ECFG.map;
  const [selected, setSelected] = React.useState(null);
  const [peek, setPeek]         = React.useState(null);

  const project = (coord) => ({
    x: ((coord[1] - bounds.west)  / (bounds.east  - bounds.west))  * 100,
    y: ((bounds.north - coord[0]) / (bounds.north - bounds.south)) * 100,
  });

  const pins = filtered
    .map(it => ({ it, coord: ECOORDS[it.id] }))
    .filter(p => p.coord);

  const peekItem = peek ? pins.find(p => p.it.id === peek)?.it : null;

  return (
    <div style={{ padding: '0 20px' }}>
      <div style={{
        height: 420, borderRadius: ER.lg, overflow: 'hidden', position: 'relative',
        background: '#CFE3FA', border: `1px solid ${EC.ink10}`,
      }}>
        {tileUrl ? (
          <div style={{
            position: 'absolute', inset: 0,
            background: `url("${tileUrl.replace('{z}', String(ECFG.map.zoom)).replace('{x}', '297').replace('{y}', '205').replace('{s}', 'a')}") center/cover`,
          }}/>
        ) : (
          <svg viewBox="0 0 400 420" width="100%" height="100%" preserveAspectRatio="xMidYMid slice"
            style={{ position: 'absolute', inset: 0 }}>
            <defs>
              <linearGradient id="sea" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%"  stopColor="#B8D8F5"/>
                <stop offset="100%" stopColor="#CFE3FA"/>
              </linearGradient>
              <linearGradient id="land" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%"  stopColor={EC.cream}/>
                <stop offset="100%" stopColor="#F1E6D2"/>
              </linearGradient>
            </defs>
            <rect x="0" y="0" width="400" height="140" fill="url(#sea)"/>
            <path d="M0 140 Q40 132 80 138 T160 142 T240 140 T320 136 T400 140 L400 420 L0 420 Z"
              fill="url(#land)" stroke={EC.ink20} strokeWidth="1"/>
            <circle cx="70"  cy="80" r="3"  fill="#fff" opacity="0.7"/>
            <circle cx="200" cy="60" r="2"  fill="#fff" opacity="0.5"/>
            <circle cx="310" cy="90" r="2.5" fill="#fff" opacity="0.6"/>
            <path d="M0 230 Q130 218 260 228 T400 222" fill="none" stroke={EC.ink20} strokeWidth="1"/>
            <path d="M0 320 Q150 310 300 320 T400 315" fill="none" stroke={EC.ink20} strokeWidth="1" strokeDasharray="4 4"/>
            <text x="40"  y="170" fontSize="9" fill={EC.ink60} fontFamily="system-ui">Mediterranean</text>
            <text x="250" y="255" fontSize="9" fill={EC.ink60} fontFamily="system-ui">Marsa Matrouh</text>
            <text x="80"  y="300" fontSize="9" fill={EC.ink60} fontFamily="system-ui">Ras El Hikma</text>
            <text x="160" y="360" fontSize="9" fill={EC.ink60} fontFamily="system-ui">Marassi</text>
            <text x="260" y="385" fontSize="9" fill={EC.ink60} fontFamily="system-ui">New Alamein</text>
          </svg>
        )}

        {pins.map(({ it, coord }) => {
          const { x, y } = project(coord);
          const isSel = selected === it.id || peek === it.id;
          return (
            <button key={it.id}
              onMouseEnter={() => setSelected(it.id)}
              onMouseLeave={() => setSelected(null)}
              onClick={(e) => { e.stopPropagation(); setPeek(it.id); }}
              className="raya-btn"
              style={{
                position: 'absolute', left: x + '%', top: y + '%',
                transform: `translate(-50%, -100%) ${isSel ? 'scale(1.08)' : 'scale(1)'}`,
                padding: '6px 12px', borderRadius: ER.pill, border: 'none',
                background: isSel ? EC.ink : EC.paper,
                color: isSel ? EC.paper : EC.ink,
                cursor: 'pointer', whiteSpace: 'nowrap',
                fontFamily: EF.bodyEn, fontSize: 12, fontWeight: 700, letterSpacing: -0.2,
                boxShadow: isSel ? ES.pinActive : ES.pin,
                zIndex: isSel ? 3 : 1,
                transition: 'transform .14s ease, background .14s ease, color .14s ease, box-shadow .14s ease',
              }}>
              {window.RAYA_CURRENCY.formatPrice(it.price, currency)}
            </button>
          );
        })}

        <div style={{
          position: 'absolute', top: 12, [isAr ? 'left' : 'right']: 12,
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          {['plus', 'minus'].map(n => (
            <button key={n} className="raya-btn" style={{
              width: 36, height: 36, borderRadius: 10, border: 'none',
              background: 'rgba(255,255,255,0.96)', cursor: 'pointer',
              display: 'grid', placeItems: 'center',
              boxShadow: '0 1px 2px rgba(10,22,40,0.06), 0 6px 16px rgba(10,22,40,0.1)',
            }}><RIcon name={n} size={14} color={EC.ink} sw={2}/></button>
          ))}
        </div>

        {peekItem ? (
          <div style={{
            position: 'absolute', bottom: 12, left: 12, right: 12, zIndex: 4,
            borderRadius: ER.md, background: EC.paper, padding: 10,
            display: 'flex', gap: 12, alignItems: 'center',
            flexDirection: isAr ? 'row-reverse' : 'row',
            boxShadow: ES.float, cursor: 'pointer',
            fontFamily: isAr ? EF.bodyAr : EF.bodyEn,
          }} onClick={() => openListing(peekItem)}>
            <div style={{
              width: 64, height: 64, borderRadius: ER.sm, flexShrink: 0,
              background: peekItem.images?.[0]
                ? `url(${peekItem.images[0]}) center/cover`
                : `linear-gradient(135deg, ${EC.cream}, ${EC.sand})`,
            }}/>
            <div style={{ flex: 1, minWidth: 0, textAlign: isAr ? 'right' : 'left' }}>
              <div style={{
                fontSize: 13, fontWeight: 600, color: EC.ink,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                lineHeight: isAr ? ETY.arLine : ETY.enLine,
              }}>{isAr ? peekItem.title_ar : peekItem.title_en}</div>
              <div style={{
                fontSize: 11, color: EC.ink60,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                lineHeight: isAr ? ETY.arLine : ETY.enLine,
              }}>{isAr ? peekItem.location_ar : peekItem.location_en}</div>
              <div style={{ fontSize: 13, fontWeight: 700, color: EC.brand, marginTop: 2 }}>
                {window.RAYA_CURRENCY.formatPrice(peekItem.price, currency)}
                <span style={{ fontWeight: 400, fontSize: 11, color: EC.ink60, marginInlineStart: 4 }}>
                  {isAr ? peekItem.unit_ar : peekItem.unit_en}
                </span>
              </div>
            </div>
            <button onClick={(e) => { e.stopPropagation(); setPeek(null); }}
              style={{
                width: 26, height: 26, borderRadius: ER.pill, border: 'none',
                background: EC.ink05, color: EC.ink60, cursor: 'pointer',
                fontSize: 14, display: 'grid', placeItems: 'center', flexShrink: 0,
              }}>✕</button>
          </div>
        ) : (
          <div style={{
            position: 'absolute', bottom: 12, left: 12, right: 12,
            display: 'flex', justifyContent: 'center', pointerEvents: 'none',
          }}>
            <div style={{
              padding: '6px 14px', borderRadius: ER.pill,
              background: 'rgba(255,255,255,0.96)', boxShadow: '0 4px 12px rgba(10,22,40,0.1)',
              fontFamily: isAr ? EF.bodyAr : EF.bodyEn, fontSize: 12, fontWeight: 500, color: EC.ink,
            }}>
              {isAr
                ? `${String(pins.length).replace(/\d/g, d => '٠١٢٣٤٥٦٧٨٩'[+d])} مكان على الخريطة`
                : `${pins.length} ${pins.length === 1 ? 'place' : 'places'} on map`}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function FilterChip({ active, children, onClick, lang }) {
  return (
    <button onClick={onClick} className="raya-btn" style={{
      padding: '8px 16px', borderRadius: ER.pill,
      background: active ? EC.ink : EC.white,
      border: `1px solid ${active ? EC.ink : EC.ink10}`,
      color: active ? EC.paper : EC.ink,
      fontFamily: lang === 'ar' ? EF.bodyAr : EF.bodyEn,
      fontSize: 13, fontWeight: active ? 600 : 500, cursor: 'pointer', whiteSpace: 'nowrap',
      boxShadow: active ? '0 4px 14px rgba(10,22,40,0.18)' : 'none',
      letterSpacing: lang === 'ar' ? 0 : -0.1,
    }}>{children}</button>
  );
}

function ExploreScreen({ lang, currency = 'EGP', favs, toggleFav, openListing, onBack, initialCategory = 'all' }) {
  const isAr = lang === 'ar';
  const [q, setQ] = React.useState('');
  const [cat, setCat] = React.useState(initialCategory || 'all');
  const [view, setView] = React.useState('list');

  React.useEffect(() => { setCat(initialCategory || 'all'); }, [initialCategory]);

  const all = [
    ...EL.stays, ...EL.beaches, ...EL.trips, ...EL.activities,
  ];
  const filtered = all.filter(it => {
    if (cat !== 'all' && CATEGORY_OF[it.id] !== cat) return false;
    if (q) {
      const title = (isAr ? it.title_ar : it.title_en).toLowerCase();
      const loc   = (isAr ? it.location_ar : it.location_en).toLowerCase();
      const needle = q.trim().toLowerCase();
      if (!title.includes(needle) && !loc.includes(needle)) return false;
    }
    return true;
  });

  return (
    <div style={{ background: EC.paper, minHeight: '100%', paddingBottom: 120, direction: isAr ? 'rtl' : 'ltr' }}>
      <div style={{ padding: '62px 20px 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
          <button onClick={onBack} className="raya-btn" style={{
            width: 40, height: 40, borderRadius: ER.pill, border: `1px solid ${EC.ink10}`,
            background: EC.white, display: 'grid', placeItems: 'center', cursor: 'pointer',
          }}>
            <RIcon name={isAr ? 'chevronRight' : 'chevronLeft'} size={18} color={EC.ink}/>
          </button>
          <div style={{
            flex: 1, padding: '11px 16px', borderRadius: ER.pill,
            background: EC.white, border: `1px solid ${EC.ink10}`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <RIcon name="search" size={16} color={EC.ink60}/>
            <input
              value={q} onChange={e => setQ(e.target.value)}
              placeholder={isAr ? 'ابحث عن وجهة، شاطئ، رحلة...' : 'Search destinations, stays, trips...'}
              style={{
                flex: 1, border: 'none', outline: 'none', background: 'transparent',
                fontFamily: isAr ? EF.bodyAr : EF.bodyEn,
                fontSize: 14, color: EC.ink,
                textAlign: isAr ? 'right' : 'left',
              }}
            />
          </div>
        </div>

        <h1 style={{
          margin: '6px 0 14px',
          fontFamily: isAr ? EF.displayAr : EF.displayEn,
          fontSize: 32, fontWeight: 400, color: EC.ink,
          letterSpacing: isAr ? 0 : -0.6,
          fontStyle: isAr ? 'normal' : 'italic',
          lineHeight: isAr ? ETY.arLine : ETY.enLine,
        }}>{isAr ? 'استكشف' : 'Explore'}</h1>
      </div>

      <div className="raya-scroll" style={{
        display: 'flex', gap: 8, padding: '0 20px 14px', overflowX: 'auto',
      }}>
        <FilterChip active={cat === 'all'} onClick={() => setCat('all')} lang={lang}>
          {isAr ? 'الكل' : 'All'}
        </FilterChip>
        {ECAT.map(c => (
          <FilterChip key={c.id} active={cat === c.id} onClick={() => setCat(c.id)} lang={lang}>
            {isAr ? c.ar : c.en}
          </FilterChip>
        ))}
      </div>

      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        padding: '0 20px 16px',
        flexDirection: isAr ? 'row-reverse' : 'row',
      }}>
        <span style={{
          fontFamily: isAr ? EF.bodyAr : EF.bodyEn,
          fontSize: 13, color: EC.ink60,
        }}>
          <strong style={{ color: EC.ink }}>{filtered.length}</strong> {isAr ? 'نتيجة' : 'results'}
        </span>
        <div style={{ display: 'flex', gap: 2, padding: 3, background: EC.ink05, borderRadius: ER.pill }}>
          {['list', 'map'].map(v => (
            <button key={v} onClick={() => setView(v)} className="raya-btn" style={{
              padding: '6px 14px', borderRadius: ER.pill, border: 'none',
              background: view === v ? EC.white : 'transparent',
              boxShadow: view === v ? '0 1px 3px rgba(10,22,40,0.08)' : 'none',
              fontFamily: isAr ? EF.bodyAr : EF.bodyEn,
              fontSize: 12, fontWeight: 500, color: EC.ink, cursor: 'pointer',
              display: 'inline-flex', alignItems: 'center', gap: 4,
            }}>
              <RIcon name={v === 'list' ? 'list' : 'map'} size={13} color={EC.ink}/>
              {isAr ? (v === 'list' ? 'قائمة' : 'خريطة') : (v === 'list' ? 'List' : 'Map')}
            </button>
          ))}
        </div>
      </div>

      {view === 'list' ? (
        filtered.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px 32px' }}>
            <div style={{
              width: 84, height: 84, borderRadius: ER.pill, margin: '0 auto 18px',
              background: EC.cream, display: 'grid', placeItems: 'center',
            }}>
              <RIcon name="search" size={34} color={EC.brand} sw={1.4}/>
            </div>
            <div style={{
              fontFamily: isAr ? EF.displayAr : EF.displayEn,
              fontSize: 18, fontWeight: 500, color: EC.ink, marginBottom: 6,
            }}>{isAr ? 'مفيش نتائج' : 'No matches'}</div>
            <div style={{
              fontFamily: isAr ? EF.bodyAr : EF.bodyEn,
              fontSize: 13, color: EC.ink60, lineHeight: isAr ? ETY.arLine : ETY.enLine,
            }}>{isAr ? 'جرّب تغيّر التصنيف أو كلمة البحث' : 'Try a different category or search term.'}</div>
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 16, padding: '0 20px', gridTemplateColumns: '1fr 1fr' }}>
            {filtered.map(it => (
              <ListingCard key={it.id} item={it} lang={lang} compact
                fav={favs.has(it.id)}
                onFav={() => toggleFav(it.id)}
                onOpen={() => openListing(it)}
              />
            ))}
          </div>
        )
      ) : (
        <MapView filtered={filtered} currency={currency} lang={lang} openListing={openListing}/>
      )}
    </div>
  );
}

window.ExploreScreen = ExploreScreen;
