/* ============================================================
   WorkStay — Explore / Search (editorial, not marketplace grid)
   exports: ExplorePage
   ============================================================ */
const { useState: useStateEx, useMemo } = React;

function PropertyRow({ p, go, wished, toggleWish, i }) {
  const [hov, setHov] = useStateEx(false);
  const flip = i % 2 === 1;
  return (
    <div onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ display: 'grid', gridTemplateColumns: flip ? '1fr 1.15fr' : '1.15fr 1fr', gap: 'clamp(28px,4vw,64px)',
        alignItems: 'center', paddingBlock: 'clamp(40px,5vw,72px)', borderTop: '1px solid var(--line)' }} className="ws-prow">
      {/* visual */}
      <button onClick={() => go('property', { id: p.id })} style={{ order: flip ? 2 : 1, position: 'relative', border: 'none', padding: 0, borderRadius: 'var(--r-lg)', overflow: 'hidden',
        height: 420, background: 'none', cursor: 'pointer' }} className="ws-prow-vis">
        <Scene variant={p.scene} style={{ position: 'absolute', inset: 0, transform: hov ? 'scale(1.05)' : 'scale(1)', transition: 'transform 1.1s cubic-bezier(.16,1,.3,1)' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(0deg, rgba(10,10,12,0.55), transparent 50%)' }} />
        <div className="glass" style={{ position: 'absolute', left: 18, top: 18, padding: '8px 13px', borderRadius: 999, display: 'flex', alignItems: 'center', gap: 8, fontSize: 12.5 }}>
          <Icon name="wifi" size={13} style={{ color: 'var(--good)' }} /> {p.speed} Mbps verified
        </div>
        <div style={{ position: 'absolute', right: 18, bottom: 18 }}><WorkScore value={p.workScore} size={88} stroke={6} label="Work" /></div>
      </button>
      {/* copy */}
      <div style={{ order: flip ? 1 : 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
          <span style={{ fontSize: 12.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--violet-soft)' }}>{p.collection}</span>
          <button onClick={() => toggleWish(p.id)} aria-label="Save" style={{ marginLeft: 'auto', background: 'none', border: 'none', color: wished ? 'var(--violet)' : 'var(--text-faint)', display: 'flex', padding: 4 }}>
            <Icon name="heart" size={19} style={{ fill: wished ? 'var(--violet)' : 'none' }} />
          </button>
        </div>
        <button onClick={() => go('property', { id: p.id })} style={{ background: 'none', border: 'none', padding: 0, textAlign: 'left' }}>
          <h3 className="serif" style={{ fontSize: 'clamp(30px,3.4vw,46px)', lineHeight: 1.04, margin: 0,
            color: hov ? 'var(--text)' : 'var(--text)', transition: 'color .3s' }}>{p.name}</h3>
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, color: 'var(--text-dim)', fontSize: 14.5 }}>
          <Icon name="pin" size={15} /> {p.city}, {p.country}
        </div>
        <p style={{ marginTop: 18, fontSize: 16.5, lineHeight: 1.55, color: 'var(--text-dim)', maxWidth: 440 }}>{p.tagline}</p>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 22 }}>
          {p.amenities.slice(0, 4).map(a => (
            <span key={a} style={{ fontSize: 12.5, padding: '6px 12px', borderRadius: 999, border: '1px solid var(--line)', color: 'var(--text-dim)' }}>{a}</span>
          ))}
        </div>
        <div className="ws-prow-price" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 30, paddingTop: 22, borderTop: '1px solid var(--line)' }}>
          <div><span style={{ fontFamily: 'var(--serif)', fontSize: 30 }}>${p.price.toLocaleString()}</span><span style={{ fontSize: 14, color: 'var(--text-faint)' }}> / {p.period}</span></div>
          <Btn variant="line" icon="arrow" onClick={() => go('property', { id: p.id })}>View work profile</Btn>
        </div>
      </div>
    </div>
  );
}

function ExplorePage({ go, params = {}, wish = [], toggleWish }) {
  const { PROPERTIES, COLLECTIONS } = window.WS_DATA;
  const [filter, setFilter] = useStateEx(params.collection || 'All');
  const [sort, setSort] = useStateEx('work');
  const wishOnly = params.wishOnly;

  const filters = ['All', ...COLLECTIONS.map(c => c.title)];

  const list = useMemo(() => {
    let r = PROPERTIES.slice();
    if (wishOnly) r = r.filter(p => wish.includes(p.id));
    else if (filter !== 'All') r = r.filter(p => p.collection === filter);
    if (sort === 'work') r.sort((a, b) => b.workScore - a.workScore);
    if (sort === 'price') r.sort((a, b) => a.price - b.price);
    if (sort === 'speed') r.sort((a, b) => b.speed - a.speed);
    return r;
  }, [filter, sort, wishOnly, wish]);

  return (
    <main style={{ paddingTop: 110 }}>
      {/* header */}
      <section style={{ position: 'relative', paddingBlock: '40px 30px', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', top: -80, right: -40, width: 380, height: 380, borderRadius: '50%', background: 'radial-gradient(circle, var(--violet-glow), transparent 70%)', filter: 'blur(40px)', opacity: 0.5 }} />
        <div className="wrap" style={{ position: 'relative' }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>{wishOnly ? 'Your wishlist' : 'Explore work-ready stays'}</div>
          <h1 className="d2" style={{ margin: 0, maxWidth: 760 }}>
            {wishOnly ? <>Spaces you’re <span className="italic" style={{ color: 'var(--beige)' }}>keeping</span> in mind.</>
              : <>Find the room that <span className="italic" style={{ color: 'var(--beige)' }}>makes</span> the work happen.</>}
          </h1>
          <div style={{ marginTop: 30, maxWidth: 880 }}><FloatSearch go={go} compact /></div>
        </div>
      </section>

      {/* filter rail */}
      {!wishOnly && (
        <section style={{ position: 'sticky', top: 64, zIndex: 40, background: 'rgba(10,10,12,0.78)', backdropFilter: 'blur(18px)', borderBlock: '1px solid var(--line)' }}>
          <div className="wrap ws-filterbar" style={{ display: 'flex', alignItems: 'center', gap: 14, paddingBlock: 14, overflowX: 'auto' }}>
            <div style={{ display: 'flex', gap: 8, flex: 1 }}>
              {filters.map(f => <Pill key={f} active={filter === f} onClick={() => setFilter(f)}>{f}</Pill>)}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, borderLeft: '1px solid var(--line)', paddingLeft: 14 }}>
              <span style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>Sort</span>
              {[['work', 'Work Score'], ['price', 'Price'], ['speed', 'Speed']].map(([k, l]) =>
                <Pill key={k} active={sort === k} onClick={() => setSort(k)}>{l}</Pill>)}
            </div>
          </div>
        </section>
      )}

      {/* results */}
      <section style={{ paddingBottom: 90 }}>
        <div className="wrap">
          <div style={{ paddingBlock: 22, fontSize: 13.5, color: 'var(--text-faint)' }}>{list.length} {list.length === 1 ? 'space' : 'spaces'} · verified this month</div>
          {list.length === 0 && (
            <div style={{ textAlign: 'center', paddingBlock: 100, color: 'var(--text-dim)' }}>
              <Icon name="heart" size={32} style={{ color: 'var(--text-faint)' }} />
              <p style={{ marginTop: 16, fontSize: 17 }}>Nothing saved yet — tap the heart on any space.</p>
              <div style={{ marginTop: 20, display: 'flex', justifyContent: 'center' }}><Btn onClick={() => go('explore')}>Browse stays</Btn></div>
            </div>
          )}
          {list.map((p, i) => <PropertyRow key={p.id} p={p} i={i} go={go} wished={wish.includes(p.id)} toggleWish={toggleWish} />)}
        </div>
      </section>

      {/* nearby / map band */}
      {!wishOnly && <MapBand />}
    </main>
  );
}

/* dark interactive-feeling city map with best-work-zones heatmap */
function MapBand() {
  const { NEARBY } = window.WS_DATA;
  const iconFor = { Coworking: 'desk', Cafe: 'coffee', Metro: 'train', Gym: 'dumbbell', Grocery: 'cart' };
  const [active, setActive] = useStateEx(null);
  return (
    <section className="section" style={{ background: 'var(--bg-2)', borderTop: '1px solid var(--line)' }}>
      <div className="wrap" style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 'clamp(32px,5vw,70px)', alignItems: 'center' }} className="ws-intel">
        <div>
          <div className="eyebrow" style={{ marginBottom: 16 }}>Location intelligence</div>
          <h2 className="d3" style={{ margin: 0 }}>The best remote-work zones, mapped.</h2>
          <p style={{ marginTop: 18, fontSize: 16, lineHeight: 1.6, color: 'var(--text-dim)' }}>A heatmap of where focus actually happens — coworking, fast cafés, transit, and the quiet pockets in between.</p>
          <div style={{ marginTop: 26, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {NEARBY.map((n, i) => (
              <button key={i} onMouseEnter={() => setActive(i)} onMouseLeave={() => setActive(null)}
                style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 14px', borderRadius: 'var(--r-sm)', background: active === i ? 'var(--surface-2)' : 'transparent',
                  border: '1px solid', borderColor: active === i ? 'var(--line-2)' : 'transparent', transition: 'all .25s', textAlign: 'left' }}>
                <span style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--surface-3)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--violet-soft)' }}><Icon name={iconFor[n.type]} size={17} /></span>
                <div style={{ flex: 1 }}><div style={{ fontSize: 14.5 }}>{n.name}</div><div style={{ fontSize: 12.5, color: 'var(--text-faint)' }}>{n.type}</div></div>
                <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>{n.dist}</span>
              </button>
            ))}
          </div>
        </div>
        <div className="ws-map-canvas" style={{ position: 'relative', height: 460, borderRadius: 'var(--r-xl)', overflow: 'hidden', border: '1px solid var(--line-2)', background: 'var(--surface)' }}>
          {/* map grid */}
          <div style={{ position: 'absolute', inset: 0, backgroundImage: 'linear-gradient(var(--line) 1px, transparent 1px), linear-gradient(90deg, var(--line) 1px, transparent 1px)', backgroundSize: '46px 46px', opacity: 0.6 }} />
          {/* roads */}
          <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
            <path d="M0 60 Q40 40 100 55" stroke="var(--line-2)" strokeWidth="0.6" fill="none" />
            <path d="M30 0 Q45 50 35 100" stroke="var(--line-2)" strokeWidth="0.6" fill="none" />
            <path d="M70 0 L65 100" stroke="var(--line-2)" strokeWidth="0.4" fill="none" />
          </svg>
          {/* heat zones */}
          <div style={{ position: 'absolute', left: '38%', top: '30%', width: 220, height: 220, transform: 'translate(-50%,-50%)', background: 'radial-gradient(circle, var(--violet-glow), transparent 65%)', filter: 'blur(14px)' }} />
          <div style={{ position: 'absolute', left: '62%', top: '50%', width: 170, height: 170, transform: 'translate(-50%,-50%)', background: 'radial-gradient(circle, var(--amber-glow), transparent 65%)', filter: 'blur(14px)' }} />
          {/* pins */}
          {NEARBY.map((n, i) => (
            <div key={i} style={{ position: 'absolute', left: `${n.x}%`, top: `${n.y}%`, transform: 'translate(-50%,-50%)', transition: 'all .3s' }}>
              <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: active === i ? 40 : 32, height: active === i ? 40 : 32, borderRadius: 999,
                background: active === i ? 'var(--violet)' : 'var(--surface-2)', border: '1px solid var(--line-2)', color: active === i ? '#fff' : 'var(--violet-soft)',
                boxShadow: active === i ? '0 0 24px -4px var(--violet-glow)' : 'none', transition: 'all .3s' }}>
                <Icon name={iconFor[n.type]} size={15} />
              </span>
            </div>
          ))}
          {/* home marker */}
          <div style={{ position: 'absolute', left: '46%', top: '40%', transform: 'translate(-50%,-50%)' }}>
            <span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 46, height: 46, borderRadius: 14, background: 'linear-gradient(135deg, var(--violet), var(--violet-deep))', boxShadow: '0 0 30px -4px var(--violet-glow)' }}><Logo size={24} /></span>
          </div>
          <div className="glass" style={{ position: 'absolute', left: 18, bottom: 18, padding: '10px 14px', borderRadius: 999, fontSize: 12.5, display: 'flex', alignItems: 'center', gap: 9 }}>
            <span style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--violet)' }} /> Best remote-work zones
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ExplorePage, MapBand });
