// GS Car — Map, Merchant Detail, Booking, AI Agent, Inbox

const ScreenMap = ({ onOpenMerchant }) => {
  const [activeFilter, setActiveFilter] = React.useState('全部');
  const filters = ['全部', '氛圍燈', '改裝', 'Detailing', '隔熱紙', '輪圈', '保養'];
  const [selected, setSelected] = React.useState(null);
  const [transform, setTransform] = React.useState({ x: 0, y: 0, scale: 1 });
  const dragRef = React.useRef(null);
  const mapRef = React.useRef(null);

  const PAN_LIMIT = 600;
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
  const onPointerDown = (e) => {
    if (e.target.closest('button')) return;
    dragRef.current = { x: e.clientX, y: e.clientY, tx: transform.x, ty: transform.y };
    try { e.currentTarget.setPointerCapture?.(e.pointerId); } catch (_) { /* iOS Safari can throw InvalidStateError */ }
  };
  const onPointerMove = (e) => {
    if (!dragRef.current) return;
    const dx = e.clientX - dragRef.current.x;
    const dy = e.clientY - dragRef.current.y;
    setTransform(t => ({
      ...t,
      x: clamp(dragRef.current.tx + dx, -PAN_LIMIT, PAN_LIMIT),
      y: clamp(dragRef.current.ty + dy, -PAN_LIMIT, PAN_LIMIT),
    }));
  };
  const onPointerUp = () => { dragRef.current = null; };
  const zoom = (delta) => setTransform(t => ({ ...t, scale: Math.max(0.8, Math.min(1.8, t.scale + delta)) }));
  const reset = () => setTransform({ x: 0, y: 0, scale: 1 });

  return (
    <div className="screen screen-enter">
      {/* Pan/zoom layer (background + pins + user dot) */}
      <div
        ref={mapRef}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={onPointerUp}
        onPointerCancel={onPointerUp}
        style={{
          position: 'absolute', inset: 0,
          touchAction: 'none', cursor: dragRef.current ? 'grabbing' : 'grab',
          overflow: 'hidden',
          background: `
            repeating-linear-gradient(0deg, transparent 0, transparent 59px, rgba(255,255,255,0.04) 59px, rgba(255,255,255,0.04) 60px),
            repeating-linear-gradient(90deg, transparent 0, transparent 59px, rgba(255,255,255,0.04) 59px, rgba(255,255,255,0.04) 60px),
            radial-gradient(ellipse 70% 50% at 30% 25%, rgba(74, 158, 255, 0.08), transparent),
            radial-gradient(ellipse 60% 50% at 70% 75%, rgba(45, 187, 110, 0.06), transparent),
            linear-gradient(135deg, #0a0e15 0%, #08080a 100%)`,
        }}
      >
        <div style={{
          position: 'absolute', inset: 0,
          transform: `translate(${transform.x}px, ${transform.y}px) scale(${transform.scale})`,
          transformOrigin: 'center center',
          transition: dragRef.current ? 'none' : 'transform 0.18s ease-out',
        }}>
          {/* District labels (positioned relative to viewport, pan with user) */}
          <div style={{ position: 'absolute', top: '24%', left: '20%', fontSize: 9, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>長沙灣</div>
          <div style={{ position: 'absolute', top: '38%', left: '58%', fontSize: 9, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>觀塘</div>
          <div style={{ position: 'absolute', top: '68%', left: '36%', fontSize: 9, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>黃竹坑</div>
          <div style={{ position: 'absolute', top: '76%', left: '78%', fontSize: 9, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.1em' }}>柴灣</div>

          {/* User location */}
          <div style={{ position: 'absolute', top: '50%', left: '50%' }}>
            <div style={{
              width: 16, height: 16, borderRadius: '50%',
              background: 'var(--blue)', border: '3px solid #fff',
              boxShadow: '0 0 0 2px var(--blue)', position: 'relative',
              transform: 'translate(-50%, -50%)',
            }}>
              <div style={{
                position: 'absolute', inset: -8,
                border: '1.5px solid var(--blue)',
                borderRadius: '50%', opacity: 0.4,
                animation: 'pulse 2s infinite',
              }} />
              <style>{`@keyframes pulse { 0%,100% { transform: scale(1); opacity: 0.4; } 50% { transform: scale(1.5); opacity: 0; } }`}</style>
            </div>
          </div>

          {/* Pins */}
          {DATA.merchants.map(m => (
            <button key={m.id} onClick={(e) => { e.stopPropagation(); setSelected(m); }} style={{
              position: 'absolute',
              left: `${m.coords.x}%`, top: `${m.coords.y}%`,
              transform: 'translate(-50%, -100%)',
              zIndex: selected?.id === m.id ? 10 : 5,
            }}>
              <div style={{
                background: m.featured ? 'var(--accent)' : 'var(--bg-2)',
                border: `1.5px solid ${m.featured ? '#fff' : 'var(--line)'}`,
                color: m.featured ? '#fff' : 'var(--ink-0)',
                padding: '7px 11px', borderRadius: 14,
                fontSize: 11, fontWeight: 700,
                boxShadow: '0 8px 24px rgba(0,0,0,0.55)',
                display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 2,
                whiteSpace: 'nowrap',
                transform: selected?.id === m.id ? 'scale(1.08)' : 'scale(1)',
                transition: 'transform 0.2s',
                minWidth: 0,
              }}>
                <span style={{
                  fontSize: 8, fontFamily: 'var(--font-mono)',
                  letterSpacing: '0.08em',
                  opacity: m.featured ? 0.85 : 0.55,
                  textTransform: 'uppercase',
                }}>{m.tagZh || m.tag}</span>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                  <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '-0.01em' }}>
                    {m.shortName || m.name}
                  </span>
                  {m.verified && (
                    <svg width="11" height="11" viewBox="0 0 24 24" fill={m.featured ? '#fff' : '#4aa8ff'} style={{ flexShrink: 0 }}>
                      <path d="M12 2l2.4 1.8 3 .2.5 3 2.1 2.2-1.4 2.7.4 3-2.8 1.2-1.6 2.5L12 18l-2.6.6-1.6-2.5-2.8-1.2.4-3L4 9.7l2.1-2.2.5-3 3-.2L12 2z"/>
                      <path d="M8.5 12l2.5 2.5 4.5-5" stroke={m.featured ? 'var(--accent)' : 'var(--bg-0)'} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  )}
                  <span style={{ display: 'flex', alignItems: 'center', gap: 2, marginLeft: 2, opacity: 0.9 }}>
                    <Icons.Star size={9} />
                    <span style={{ fontSize: 10 }}>{m.rating}</span>
                  </span>
                </div>
              </div>
              <div style={{
                width: 0, height: 0, margin: '0 auto',
                borderLeft: '6px solid transparent',
                borderRight: '6px solid transparent',
                borderTop: `8px solid ${m.featured ? 'var(--accent)' : 'var(--bg-2)'}`,
                filter: 'drop-shadow(0 4px 6px rgba(0,0,0,0.5))',
              }} />
            </button>
          ))}
        </div>
      </div>

      {/* Top overlay (fixed, above pan layer) */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 15, pointerEvents: 'none' }}>
        <div style={{ pointerEvents: 'auto' }}>
          <StatusBar dark />
          <div style={{ padding: '8px 16px' }}>
            <div style={{
              background: 'rgba(15,15,20,0.85)', backdropFilter: 'blur(20px)',
              borderRadius: 14, border: '1px solid var(--line)',
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '12px 14px',
            }}>
              <Icons.Search size={16} />
              <div style={{ flex: 1, fontSize: 13, color: 'var(--ink-2)' }}>搜尋商戶 / 服務 / 地區</div>
              <button className="icon-btn" style={{ width: 28, height: 28, background: 'var(--bg-3)' }}><Icons.Filter size={14} /></button>
            </div>
          </div>
          <div style={{ padding: '0 16px 8px', display: 'flex', gap: 6 }} className="hscroll">
            {filters.map(f => (
              <button key={f} onClick={() => setActiveFilter(f)}
                className={`chip ${activeFilter === f ? 'active' : ''}`}
                style={{ background: activeFilter === f ? 'var(--accent)' : 'rgba(15,15,20,0.85)', backdropFilter: 'blur(20px)' }}>
                {f}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Zoom controls (right side) */}
      <div style={{
        position: 'absolute', right: 14, bottom: selected ? 280 : 120, zIndex: 12,
        display: 'flex', flexDirection: 'column', gap: 1,
        background: 'rgba(15,15,20,0.9)', backdropFilter: 'blur(20px)',
        borderRadius: 12, border: '1px solid var(--line)', overflow: 'hidden',
        transition: 'bottom 0.25s',
      }}>
        <button onClick={() => zoom(0.25)} style={{
          width: 36, height: 36, color: 'var(--ink-0)',
          display: 'grid', placeItems: 'center',
          borderBottom: '0.5px solid var(--line)',
        }}><Icons.Plus size={16} /></button>
        <button onClick={() => zoom(-0.25)} style={{
          width: 36, height: 36, color: 'var(--ink-0)',
          display: 'grid', placeItems: 'center',
          borderBottom: '0.5px solid var(--line)',
        }}><Icons.Minus size={16} /></button>
        <button onClick={reset} title="Recenter" style={{
          width: 36, height: 36, color: 'var(--accent)',
          display: 'grid', placeItems: 'center',
          fontSize: 10, fontFamily: 'var(--font-mono)', fontWeight: 700,
        }}>◎</button>
      </div>

      {/* Pan hint */}
      <div style={{
        position: 'absolute', left: '50%', bottom: selected ? 280 : 120, zIndex: 12,
        transform: 'translateX(-50%)',
        background: 'rgba(15,15,20,0.85)', backdropFilter: 'blur(20px)',
        border: '1px solid var(--line)', borderRadius: 100,
        padding: '6px 12px', fontSize: 10, color: 'var(--ink-2)',
        fontFamily: 'var(--font-mono)', letterSpacing: '0.1em',
        pointerEvents: 'none', whiteSpace: 'nowrap',
        transition: 'bottom 0.25s, opacity 0.2s',
        opacity: transform.x === 0 && transform.y === 0 && transform.scale === 1 ? 0.7 : 0,
      }}>← 拖拉移動 · 縮放 ↑↓</div>

      {/* Bottom sheet for selected */}
      {selected && (
        <div style={{
          position: 'absolute', bottom: 100, left: 16, right: 16, zIndex: 20,
          background: 'rgba(15,15,20,0.95)', backdropFilter: 'blur(30px)',
          borderRadius: 18, border: '1px solid var(--line)',
          padding: 16,
          animation: 'slideUp 0.25s ease-out',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                <span className="meta" style={{ color: 'var(--accent)' }}>{selected.tagZh || selected.tag}</span>
                {selected.premium && <span className="badge badge-gold">PREMIUM</span>}
              </div>
              <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em', lineHeight: 1.2 }}>{selected.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-2)', marginTop: 4 }}>{selected.type}</div>
              <div style={{ display: 'flex', gap: 10, fontSize: 11, color: 'var(--ink-2)', marginTop: 6 }}>
                <Stars rating={selected.rating} size={11} />
                <span>· {selected.reviewCount} reviews</span>
                <span>· {selected.distance}</span>
              </div>
            </div>
            <button onClick={() => setSelected(null)} style={{ color: 'var(--ink-3)' }}><Icons.Close size={16} /></button>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            <button onClick={() => onOpenMerchant(selected)} className="btn-primary" style={{ flex: 1, padding: '11px', fontSize: 13 }}>
              查看詳情
            </button>
            <button className="btn-secondary" style={{ flex: 0, padding: '11px 14px' }}>
              <Icons.Direction size={14} />
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

const ScreenMerchantDetail = ({ merchant, onBack, onBook, onContact }) => (
  <div className="screen screen-enter">
    <StatusBar dark />
    <div style={{
      position: 'absolute', top: 50, left: 0, right: 0, zIndex: 10,
      display: 'flex', justifyContent: 'space-between', padding: '8px 20px',
    }}>
      <button className="icon-btn" onClick={onBack} style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(20px)' }}>
        <Icons.Back size={20} />
      </button>
      <button className="icon-btn" style={{ background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(20px)' }}><Icons.Share size={16} /></button>
    </div>

    <div className="scroll">
      <div style={{
        height: 220, position: 'relative',
        background: merchant.featured
          ? 'radial-gradient(ellipse at 50% 60%, rgba(225,10,23,0.4), #08080a 75%)'
          : 'radial-gradient(ellipse at 50% 60%, #2a2a35, #08080a 75%)',
      }}>
        {/* Light bars / ambient effect */}
        <div style={{
          position: 'absolute', inset: 0,
          background: merchant.featured
            ? `repeating-linear-gradient(90deg,
                transparent 0, transparent 20px,
                rgba(225,10,23,0.15) 20px, rgba(225,10,23,0.15) 22px,
                transparent 22px, transparent 60px,
                rgba(255,46,75,0.2) 60px, rgba(255,46,75,0.2) 62px)`
            : 'none',
        }} />
        <div style={{
          position: 'absolute', bottom: 16, left: 20,
          fontFamily: 'var(--font-mono)', fontSize: 9,
          color: 'var(--ink-3)', textTransform: 'uppercase', letterSpacing: '0.15em',
        }}>storefront placeholder</div>
        <div style={{ position: 'absolute', top: 100, right: 20, display: 'flex', gap: 4 }}>
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: i === 0 ? 'var(--ink-0)' : 'rgba(255,255,255,0.3)' }} />
          ))}
        </div>
      </div>

      <div style={{ padding: '20px 20px 100px' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
          <span className="badge badge-verified">已驗證</span>
          {merchant.premium && <span className="badge badge-gold">PREMIUM</span>}
          <span className="badge" style={{ background: 'var(--bg-3)', color: 'var(--ink-1)' }}>{merchant.tagZh || merchant.tag}</span>
        </div>
        <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.15 }}>{merchant.name}</div>
        <div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 4 }}>{merchant.type}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10, paddingBottom: 14, borderBottom: '0.5px solid var(--line)' }}>
          <Stars rating={merchant.rating} size={13} />
          <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>{merchant.reviewCount} 則評價</span>
          <span style={{ color: 'var(--ink-4)' }}>·</span>
          <span style={{ fontSize: 12, color: 'var(--ink-2)' }}>{merchant.distance}</span>
        </div>

        {merchant.ownerNote && (
          <div style={{
            marginTop: 14, padding: 12,
            background: 'var(--gold-soft)', border: '1px solid rgba(201,169,106,0.25)',
            borderRadius: 10, fontSize: 11, color: 'var(--gold)', lineHeight: 1.5,
            display: 'flex', gap: 8,
          }}>
            <Icons.Sparkle size={14} />
            <span>{merchant.ownerNote}</span>
          </div>
        )}

        <div style={{ marginTop: 18 }}>
          <div className="meta" style={{ marginBottom: 10 }}>服務 / 價錢</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {merchant.services.map((s, i) => (
              <div key={i} style={{
                padding: '11px 14px', background: 'var(--bg-2)', borderRadius: 10,
                border: '1px solid var(--line-soft)',
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              }}>
                <span style={{ fontSize: 13, color: 'var(--ink-1)' }}>{s}</span>
                <Icons.Plus size={14} />
              </div>
            ))}
          </div>
          <div style={{
            marginTop: 8, fontSize: 11, color: 'var(--ink-3)',
            display: 'flex', justifyContent: 'space-between',
          }}>
            <span>價錢範圍</span>
            <span style={{ color: 'var(--ink-1)', fontWeight: 600 }}>{merchant.priceRange}</span>
          </div>
        </div>

        <div style={{ marginTop: 18 }}>
          <div className="meta" style={{ marginBottom: 10 }}>聯絡 / 位置</div>
          <div style={{ background: 'var(--bg-2)', borderRadius: 12, border: '1px solid var(--line-soft)', overflow: 'hidden' }}>
            <Row icon={<Icons.Pin size={14} />} text={merchant.address} />
            <Row icon={<Icons.Phone size={14} />} text={merchant.phone} />
            <Row icon={<Icons.Bell size={14} />} text={`營業時間 · ${merchant.hours}`} last />
          </div>
        </div>
      </div>
    </div>

    <div style={{
      position: 'absolute', bottom: 0, left: 0, right: 0,
      padding: '14px 20px 32px',
      background: 'rgba(8,8,10,0.95)', backdropFilter: 'blur(20px)',
      borderTop: '0.5px solid var(--line)',
      display: 'flex', gap: 10,
    }}>
      <button onClick={onContact} className="btn-secondary" style={{ flex: 0, padding: '14px 18px' }}>
        <Icons.Chat size={16} />
      </button>
      <button onClick={onBook} className="btn-primary" style={{ flex: 1 }}>
        即刻預約
      </button>
    </div>
  </div>
);

const Row = ({ icon, text, last }) => (
  <div style={{
    padding: '12px 14px',
    display: 'flex', gap: 10, alignItems: 'center',
    borderBottom: last ? 'none' : '0.5px solid var(--line)',
  }}>
    <span style={{ color: 'var(--ink-3)' }}>{icon}</span>
    <span style={{ fontSize: 12, color: 'var(--ink-1)' }}>{text}</span>
  </div>
);

window.ScreenMap = ScreenMap;
window.ScreenMerchantDetail = ScreenMerchantDetail;
