// 타운카 제휴업체 — 상세 모달 (바텀시트)

function DetailModal({ partner, onClose, onCall, onCopy, onDirections }) {
  const [open, setOpen] = React.useState(false);
  const [closing, setClosing] = React.useState(false);

  React.useEffect(() => {
    if (partner) {
      setClosing(false);
      requestAnimationFrame(() => setOpen(true));
    } else {
      setOpen(false);
    }
  }, [partner?.id]);

  const handleClose = () => {
    setClosing(true);
    setOpen(false);
    setTimeout(() => {
      setClosing(false);
      onClose && onClose();
    }, 240);
  };

  if (!partner && !closing) return null;
  const p = partner;

  // 카테고리/브랜드 라벨
  const cat = window.CATEGORIES.find(c => c.id === p?.category);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      pointerEvents: open || closing ? 'auto' : 'none',
      fontFamily: FF,
      display: 'flex', justifyContent: 'center',
    }}>
      {/* dim — 전체 뷰포트 덮기 */}
      <div onClick={handleClose} style={{
        position: 'fixed', inset: 0,
        background: 'rgba(23,23,25,0.55)',
        opacity: open ? 1 : 0,
        transition: 'opacity 240ms cubic-bezier(0.2,0,0,1)',
      }} />

      {/* sheet — 모바일 컨테이너 너비에 맞춰 가운데 */}
      <div style={{
        position: 'fixed', left: '50%', bottom: 0,
        transform: open ? 'translate(-50%, 0)' : 'translate(-50%, 100%)',
        width: '100%', maxWidth: 480,
        background: '#fff', borderRadius: '24px 24px 0 0',
        boxShadow: '0 -8px 32px rgba(0,0,0,0.18)',
        transition: 'transform 320ms cubic-bezier(0.32,0.72,0,1)',
        maxHeight: '85vh',
        display: 'flex', flexDirection: 'column',
        overflow: 'hidden',
      }}>
        {/* drag handle */}
        <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 8, paddingBottom: 4 }}>
          <div style={{ width: 36, height: 4, borderRadius: 999, background: TC.fillStrong }} />
        </div>

        {/* close button */}
        <button onClick={handleClose} style={{
          all: 'unset', cursor: 'pointer',
          position: 'absolute', top: 14, right: 12,
          width: 32, height: 32, borderRadius: 999,
          background: TC.fillSubtle,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          zIndex: 1,
        }}><Icon name="x" size={18} color={TC.text} stroke={2.4} /></button>

        {/* scroll body */}
        <div style={{ flex: 1, overflowY: 'auto', WebkitOverflowScrolling: 'touch' }}>
          {p && (
            <>
              {/* header block */}
              <div style={{ padding: '8px 20px 16px' }}>
                {/* category chip */}
                <div style={{
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  height: 22, padding: '0 8px', borderRadius: 6,
                  background: TC.fillSubtle, color: TC.text,
                  fontSize: 11, fontWeight: 600, letterSpacing: '0.025em',
                  marginBottom: 10,
                }}>
                  {cat && <><Icon name={cat.icon} size={11} color={TC.text} stroke={2.2} />{cat.label}{p.brand ? ` · ${p.brand}` : ''}</>}
                </div>

                <h2 style={{
                  margin: 0, fontSize: 22, fontWeight: 700,
                  letterSpacing: '-0.025em', lineHeight: '28px',
                  color: TC.textStrong, paddingRight: 36,
                }}>{p.name}</h2>

                {/* badges */}
                {(p.official || p.discount || p.flagship || (p.badges && p.badges.length)) && (
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 10 }}>
                    {p.official && <OfficialBadge />}
                    {p.discount && <MiniBadge tone="discount">제휴 할인 운영</MiniBadge>}
                    {p.flagship && <MiniBadge tone="yellow">플래그십 스토어</MiniBadge>}
                    {p.badges && p.badges.map((b, i) => <MiniBadge key={i} tone="info">{b}</MiniBadge>)}
                  </div>
                )}

                {p.discount && (
                  <div style={{
                    marginTop: 12, padding: 12, borderRadius: 12,
                    background: 'linear-gradient(135deg,#FFF7F2,#FFEEE5)',
                    border: '1px solid rgba(228,31,16,0.12)',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                      <div style={{
                        flexShrink: 0, width: 28, height: 28, borderRadius: 999,
                        background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        boxShadow: '0 1px 2px rgba(228,31,16,0.12)',
                      }}>
                        <Icon name="tag" size={14} color="#B81000" stroke={2.2} />
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 12, fontWeight: 700, color: '#B81000', letterSpacing: '0.02em', marginBottom: 2 }}>
                          타운카 회원 전용 혜택
                        </div>
                        <div style={{ fontSize: 13, color: TC.text, lineHeight: '18px', letterSpacing: '0.015em' }}>
                          {p.discount}
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* divider */}
              <div style={{ height: 8, background: TC.fillSubtle }} />

              {(() => {
                const hasContact = p.address || p.phone || p.manager;
                return (
                  <>
                    {/* 정보가 없는 매장: 깔끔한 빈 상태 */}
                    {!hasContact && (
                      <div style={{
                        padding: '24px 20px 20px',
                        display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
                      }}>
                        <div style={{
                          width: 48, height: 48, borderRadius: 999,
                          background: TC.fillSubtle,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          marginBottom: 12,
                        }}>
                          <Icon name="store" size={22} color={TC.textNeutral} stroke={1.8} />
                        </div>
                        <div style={{
                          fontSize: 15, fontWeight: 700, color: TC.textStrong,
                          letterSpacing: '-0.010em', marginBottom: 6,
                        }}>지점 안내 정보가 준비 중이에요</div>
                        <div style={{
                          fontSize: 13, color: TC.textNeutral, letterSpacing: '0.015em',
                          lineHeight: '19px', wordBreak: 'keep-all', maxWidth: 280,
                        }}>지점에 방문하시거나 타운카 고객센터로 문의하시면<br />상담받으실 수 있어요.</div>
                      </div>
                    )}

                    {/* info rows */}
                    {(hasContact || p.note || p.website) && (
                      <div style={{
                        padding: hasContact ? '16px 20px' : '4px 20px 16px',
                        display: 'flex', flexDirection: 'column', gap: 16,
                      }}>
                        {/* address */}
                        {p.address && (
                          <InfoRow icon="map-pin" label="주소"
                            value={p.address}
                            trailing={
                              <button onClick={() => onCopy && onCopy(p.address)} style={{
                                all: 'unset', cursor: 'pointer',
                                height: 28, padding: '0 10px', borderRadius: 8,
                                background: TC.fillSubtle, color: TC.text,
                                fontSize: 12, fontWeight: 600, letterSpacing: '0.015em',
                                display: 'inline-flex', alignItems: 'center', gap: 3,
                              }}>
                                <Icon name="copy" size={12} color={TC.text} stroke={2.2} />복사
                              </button>
                            }
                          />
                        )}

                        {/* phone or manager */}
                        {(p.phone || p.manager) && (
                          <InfoRow icon="phone" label={p.manager ? '담당자' : '연락처'}
                            value={
                              <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                                {p.manager && <div style={{ fontSize: 15, fontWeight: 600, color: TC.textStrong, letterSpacing: '-0.010em' }}>{p.manager}</div>}
                                {p.phone && (
                                  <div style={{ fontSize: 14, color: TC.text, letterSpacing: '0.015em', fontVariantNumeric: 'tabular-nums' }}>
                                    {p.phone}
                                  </div>
                                )}
                              </div>
                            }
                            trailing={p.phone && (
                              <a href={telUrl(p.phone)} onClick={() => onCall && onCall(p)} style={{
                                cursor: 'pointer', textDecoration: 'none',
                                height: 28, padding: '0 10px', borderRadius: 8,
                                background: TC.primarySubtle, color: TC.primaryPressed,
                                fontSize: 12, fontWeight: 700, letterSpacing: '0.015em',
                                display: 'inline-flex', alignItems: 'center', gap: 3,
                                boxSizing: 'border-box',
                              }}>
                                <Icon name="phone" size={12} color={TC.primaryPressed} stroke={2.4} />전화
                              </a>
                            )}
                          />
                        )}

                        {p.note && (
                          <InfoRow icon="alert-circle" label="안내사항"
                            value={<span style={{ fontSize: 13, color: TC.textNeutral, lineHeight: '18px' }}>{p.note}</span>}
                          />
                        )}

                        {/* 홈페이지 */}
                        {p.website && (
                          <InfoRow icon="globe" label="홈페이지"
                            value={
                              <a href={p.website} target="_blank" rel="noopener noreferrer" style={{
                                fontSize: 13.5, color: TC.text, letterSpacing: '0.015em',
                                textDecoration: 'none', wordBreak: 'break-all',
                                display: 'inline-flex', alignItems: 'center', gap: 4,
                              }}>
                                {p.website.replace(/^https?:\/\//, '').replace(/\/$/, '')}
                                <Icon name="external-link" size={12} color={TC.textNeutral} stroke={2} />
                              </a>
                            }
                            trailing={
                              <a href={p.website} target="_blank" rel="noopener noreferrer" style={{
                                height: 28, padding: '0 10px', borderRadius: 8,
                                background: TC.fillSubtle, color: TC.text,
                                fontSize: 12, fontWeight: 600, letterSpacing: '0.015em',
                                display: 'inline-flex', alignItems: 'center', gap: 3,
                                textDecoration: 'none',
                              }}>
                                <Icon name="arrow-up-right" size={12} color={TC.text} stroke={2.2} />이동
                              </a>
                            }
                          />
                        )}
                      </div>
                    )}
                  </>
                );
              })()}

              {/* tips */}
              <div style={{
                margin: '0 16px 16px', padding: 14, borderRadius: 12,
                background: TC.fillSubtle,
                display: 'flex', alignItems: 'flex-start', gap: 10,
              }}>
                <Icon name="info" size={16} color={TC.textNeutral} stroke={2} style={{ marginTop: 1 }} />
                <div style={{ flex: 1, fontSize: 12, color: TC.textNeutral, lineHeight: '17px', letterSpacing: '0.015em' }}>
                  방문 전 <strong style={{ color: TC.text, fontWeight: 600 }}>"타운카 회원"</strong>임을 알려주시면 제휴 혜택 안내를 받으실 수 있어요.
                </div>
              </div>

              <div style={{ height: 92 }} />
            </>
          )}
        </div>

        {/* sticky bottom CTA */}
        {p && (() => {
          const hasContact = p.address || p.phone || p.manager;
          if (!hasContact) {
            // 정보 없는 매장: 단일 닫기 버튼
            return (
              <div style={{
                padding: '12px 16px calc(12px + env(safe-area-inset-bottom, 0px))',
                background: '#fff',
                borderTop: '0.5px solid ' + TC.line,
              }}>
                <button onClick={handleClose} style={{
                  all: 'unset', cursor: 'pointer', width: '100%',
                  height: 48, borderRadius: 12, background: TC.textStrong,
                  color: '#fff',
                  fontSize: 15, fontWeight: 700, letterSpacing: '0.010em',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  boxSizing: 'border-box',
                }}>
                  확인
                </button>
              </div>
            );
          }
          return (
            <div style={{
              padding: '12px 16px calc(12px + env(safe-area-inset-bottom, 0px))',
              background: '#fff',
              borderTop: '0.5px solid ' + TC.line,
              display: 'flex', gap: 8,
            }}>
              <a href={naverMapUrl(p)} target="_blank" rel="noopener noreferrer"
                 onClick={() => onDirections && onDirections(p)} style={{
                flex: 1, textDecoration: 'none',
                height: 48, borderRadius: 12, background: '#fff',
                border: '1px solid ' + TC.line,
                color: TC.textStrong,
                fontSize: 15, fontWeight: 600, letterSpacing: '0.010em',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
                boxSizing: 'border-box',
              }}>
                <Icon name="map" size={17} color={TC.textStrong} stroke={2} />
                네이버 지도
              </a>
              {p.phone ? (
                <a href={telUrl(p.phone)}
                   onClick={() => onCall && onCall(p)} style={{
                  flex: 1.4, textDecoration: 'none',
                  height: 48, borderRadius: 12, background: TC.primary,
                  color: '#fff',
                  fontSize: 15, fontWeight: 700, letterSpacing: '0.010em',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  boxSizing: 'border-box',
                }}>
                  <Icon name="phone" size={17} color="#fff" stroke={2.2} />
                  전화 걸기
                </a>
              ) : (
                <button onClick={handleClose} style={{
                  all: 'unset', cursor: 'pointer', flex: 1.4,
                  height: 48, borderRadius: 12, background: TC.primary,
                  color: '#fff',
                  fontSize: 15, fontWeight: 700, letterSpacing: '0.010em',
                  display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  boxSizing: 'border-box',
                }}>
                  <Icon name="check" size={17} color="#fff" stroke={2.2} />
                  확인
                </button>
              )}
            </div>
          );
        })()}
      </div>
    </div>
  );
}

function InfoRow({ icon, label, value, trailing }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
      <div style={{
        flexShrink: 0, width: 32, height: 32, borderRadius: 10,
        background: TC.fillSubtle, display: 'flex',
        alignItems: 'center', justifyContent: 'center',
      }}>
        <Icon name={icon} size={16} color={TC.text} stroke={2} />
      </div>
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ fontSize: 11, fontWeight: 600, color: TC.textNeutral, letterSpacing: '0.030em' }}>{label}</div>
        <div style={{ fontSize: 14, color: TC.textStrong, lineHeight: '20px', letterSpacing: '0.015em', wordBreak: 'keep-all' }}>{value}</div>
      </div>
      {trailing && <div style={{ flexShrink: 0 }}>{trailing}</div>}
    </div>
  );
}

Object.assign(window, { DetailModal, InfoRow });
