// ── Property detail page ─────────────────────────────────────────
const { Icon, Photo, HeartBtn, DealTag, Badge, Stats, fmtPrice } = window;

function Gallery({ l, onOpenReel }) {
  const [idx, setIdx] = React.useState(0);
  const ref = React.useRef(null);
  const n = 4;
  const onScroll = () => {
    const el = ref.current; if (!el) return;
    setIdx(Math.round(el.scrollLeft / el.clientWidth));
  };
  return (
    <div style={{ position: 'relative', height: 380 }}>
      <div ref={ref} onScroll={onScroll} className="no-scrollbar" style={{ display: 'flex', height: '100%',
        overflowX: 'auto', scrollSnapType: 'x mandatory', WebkitOverflowScrolling: 'touch' }}>
        {Array.from({ length: n }).map((_, i) => (
          <div key={i} style={{ flex: '0 0 100%', scrollSnapAlign: 'start' }}>
            <Photo hue={l.hue} i={i} kind={['exterior', 'living', 'kitchen', 'bedroom'][i]} />
          </div>
        ))}
      </div>
      {/* dots */}
      <div style={{ position: 'absolute', bottom: 16, left: 0, right: 0, display: 'flex', justifyContent: 'center',
        gap: 6 }}>
        {Array.from({ length: n }).map((_, i) => (
          <span key={i} style={{ width: i === idx ? 18 : 6, height: 6, borderRadius: 9,
            background: i === idx ? '#fff' : 'rgba(255,255,255,0.6)', transition: 'all .2s' }} />
        ))}
      </div>
      {l.video && (
        <button onClick={() => onOpenReel(l.id)} style={{ position: 'absolute', bottom: 14, right: 16,
          display: 'inline-flex', alignItems: 'center', gap: 8, height: 40, padding: '0 16px 0 14px',
          borderRadius: 999, border: 'none', cursor: 'pointer', background: 'rgba(20,20,18,0.6)',
          backdropFilter: 'blur(10px)', color: '#fff', fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 600 }}>
          <Icon name="play" size={15} s="#fff" fill="#fff" /> Watch reel</button>
      )}
    </div>
  );
}

function FactGrid({ l }) {
  const monthly = l.deal === 'buy'
    ? Math.round((l.price * 0.8 * 0.0065 * Math.pow(1.0065, 360)) / (Math.pow(1.0065, 360) - 1))
    : null;
  const facts = [
    ['Type', l.type], ['Year built', l.built],
    ['Days on market', l.days + (l.days === 1 ? ' day' : ' days')],
    l.lot ? ['Lot size', l.lot] : (l.hoa ? ['HOA', '$' + l.hoa + '/mo'] : ['Price / sqft', '$' + Math.round(l.price / l.sqft / (l.deal === 'rent' ? 1 : 1)).toLocaleString()]),
  ];
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, borderRadius: 16, overflow: 'hidden',
        border: '1px solid var(--line)', background: 'var(--line)' }}>
        {facts.map(([k, v]) => (
          <div key={k} style={{ background: 'var(--surface)', padding: '14px 16px' }}>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: 0.5, textTransform: 'uppercase',
              color: 'var(--muted)' }}>{k}</div>
            <div style={{ marginTop: 4, fontFamily: 'var(--sans)', fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>{v}</div>
          </div>
        ))}
      </div>
      {monthly && (
        <div style={{ marginTop: 10, display: 'flex', alignItems: 'center', gap: 8, padding: '12px 16px',
          borderRadius: 12, background: 'var(--accent-soft)' }}>
          <Icon name="dot" size={10} s="var(--accent)" />
          <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, color: 'var(--ink)' }}>
            Est. <strong>${monthly.toLocaleString()}/mo</strong> · 20% down, 6.5% APR, 30-yr</span>
        </div>
      )}
    </div>
  );
}

function Detail({ l, saved, onBack, onToggleSave, onOpenReel }) {
  if (!l) return null;
  return (
    <div style={{ position: 'absolute', inset: 0, background: 'var(--bg)', display: 'flex',
      flexDirection: 'column', animation: 'slideIn .26s cubic-bezier(.2,.8,.2,1)', zIndex: 42 }}>
      <div className="no-scrollbar" style={{ flex: 1, overflowY: 'auto' }}>
        <Gallery l={l} onOpenReel={onOpenReel} />

        <div style={{ padding: '20px 18px 0' }}>
          {/* badges */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <DealTag deal={l.deal} />
            {l.badge && <Badge>{l.badge}</Badge>}
            {l.open && <span style={{ fontFamily: 'var(--sans)', fontSize: 12.5, fontWeight: 600, color: 'var(--accent)' }}>
              Open {l.open}</span>}
          </div>

          <div style={{ fontFamily: 'var(--sans)', fontSize: 30, fontWeight: 700, letterSpacing: -0.8,
            color: 'var(--ink)' }}>{fmtPrice(l)}</div>
          <div style={{ marginTop: 6, fontFamily: 'var(--sans)', fontSize: 17, fontWeight: 600, color: 'var(--ink)' }}>
            {l.address}</div>
          <div style={{ marginTop: 2, fontFamily: 'var(--sans)', fontSize: 14.5, color: 'var(--muted)' }}>
            {l.hood} · {l.city}</div>

          <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--line)' }}>
            <Stats l={l} size={20} gap={22} />
          </div>

          <p style={{ marginTop: 18, fontFamily: 'var(--sans)', fontSize: 15.5, lineHeight: 1.6, color: 'var(--ink)',
            textWrap: 'pretty' }}>{l.blurb}</p>

          {/* facts */}
          <div style={{ marginTop: 22, fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 700, letterSpacing: -0.3,
            color: 'var(--ink)', marginBottom: 12 }}>Home facts</div>
          <FactGrid l={l} />

          {/* features */}
          <div style={{ marginTop: 26, fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 700, letterSpacing: -0.3,
            color: 'var(--ink)', marginBottom: 12 }}>What's special</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
            {l.features.map(f => (
              <span key={f} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 38,
                padding: '0 14px', borderRadius: 999, border: '1px solid var(--line)', background: 'var(--surface)',
                fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 500, color: 'var(--ink)' }}>
                <Icon name="check" size={14} s="var(--accent)" sw={2.4} />{f}</span>
            ))}
          </div>

          {/* location */}
          <div style={{ marginTop: 26, fontFamily: 'var(--sans)', fontSize: 18, fontWeight: 700, letterSpacing: -0.3,
            color: 'var(--ink)', marginBottom: 12 }}>Location</div>
          <div style={{ position: 'relative', height: 150, borderRadius: 16, overflow: 'hidden',
            background: 'oklch(0.95 0.012 150)' }}>
            <div style={{ position: 'absolute', left: '12%', top: '20%', width: '36%', height: '34%',
              borderRadius: 16, background: 'oklch(0.91 0.04 150)' }} />
            {[30, 64].map((t, i) => (<div key={i} style={{ position: 'absolute', left: 0, right: 0, top: t + '%',
              height: 7, background: 'var(--surface)' }} />))}
            {[35, 70].map((lf, i) => (<div key={i} style={{ position: 'absolute', top: 0, bottom: 0, left: lf + '%',
              width: 7, background: 'var(--surface)' }} />))}
            <div style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-100%)' }}>
              <Icon name="pin" size={38} s="var(--accent)" fill="var(--accent)" sw={1.5} />
            </div>
          </div>

          {/* agent */}
          <div style={{ marginTop: 22, marginBottom: 22, display: 'flex', alignItems: 'center', gap: 13,
            padding: '14px 16px', borderRadius: 16, border: '1px solid var(--line)', background: 'var(--surface)' }}>
            <div style={{ width: 48, height: 48, borderRadius: 999, flexShrink: 0, overflow: 'hidden' }}>
              <Photo hue={l.agent.hue} label={false} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 15.5, fontWeight: 600, color: 'var(--ink)' }}>
                {l.agent.name}</div>
              <div style={{ fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--muted)' }}>{l.agent.firm}</div>
            </div>
            <button style={{ width: 42, height: 42, borderRadius: 999, border: '1px solid var(--line)',
              background: 'var(--surface)', cursor: 'pointer', display: 'flex', alignItems: 'center',
              justifyContent: 'center' }}><Icon name="msg" size={20} s="var(--ink)" /></button>
            <button style={{ width: 42, height: 42, borderRadius: 999, border: '1px solid var(--line)',
              background: 'var(--surface)', cursor: 'pointer', display: 'flex', alignItems: 'center',
              justifyContent: 'center' }}><Icon name="phone" size={19} s="var(--ink)" /></button>
          </div>
          <div style={{ height: 90 }} />
        </div>
      </div>

      {/* floating top bar */}
      <div style={{ position: 'absolute', top: 56, left: 16, right: 16, display: 'flex',
        justifyContent: 'space-between', zIndex: 5 }}>
        <button data-tour="re-back" onClick={onBack} style={{ width: 42, height: 42, borderRadius: 999, border: 'none', cursor: 'pointer',
          background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)', boxShadow: '0 2px 8px rgba(0,0,0,0.18)',
          display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon name="chevL" size={22} s="var(--ink)" /></button>
        <div style={{ display: 'flex', gap: 10 }}>
          <button style={{ width: 42, height: 42, borderRadius: 999, border: 'none', cursor: 'pointer',
            background: 'rgba(255,255,255,0.92)', backdropFilter: 'blur(8px)', boxShadow: '0 2px 8px rgba(0,0,0,0.18)',
            display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="share" size={19} s="var(--ink)" /></button>
          <HeartBtn active={saved} onClick={() => onToggleSave(l.id)} size={42} light />
        </div>
      </div>

      {/* sticky footer */}
      <div style={{ display: 'flex', gap: 10, padding: '12px 18px calc(14px + env(safe-area-inset-bottom))',
        borderTop: '1px solid var(--line)', background: 'var(--bg)' }}>
        <button style={{ flex: 1, height: 52, borderRadius: 14, border: '1.5px solid var(--ink)', cursor: 'pointer',
          background: 'var(--surface)', fontFamily: 'var(--sans)', fontSize: 15.5, fontWeight: 600,
          color: 'var(--ink)' }}>{l.deal === 'rent' ? 'Ask a question' : 'Request tour'}</button>
        <button style={{ flex: 1, height: 52, borderRadius: 14, border: 'none', cursor: 'pointer',
          background: 'var(--ink)', color: 'var(--bg)', fontFamily: 'var(--sans)', fontSize: 15.5, fontWeight: 600 }}>
          Contact agent</button>
      </div>
    </div>
  );
}

window.Detail = Detail;
