// 예약 문의 모달 - 간소화 2단계: 디자이너 선택 → 네이버/인스타 링크 이동
const { useState, useEffect } = React;

function BookingModal({ isOpen, onClose, lang, t, initialDesigner }) {
  const [step, setStep] = useState(1);
  const [selectedDesigner, setSelectedDesignerLocal] = useState(null);

  const allDesigners = [...window.designers, window.chiefDesigner];

  useEffect(() => {
    if (isOpen) {
      // 모달이 새로 열릴 때 초기화
      if (initialDesigner) {
        setSelectedDesignerLocal(initialDesigner);
        setStep(2);
      } else {
        setSelectedDesignerLocal(null);
        setStep(1);
      }
    }
  }, [isOpen, initialDesigner]);

  if (!isOpen) return null;

  const handleNext = () => {
    if (step < 2) setStep(step + 1);
  };

  const handleBack = () => {
    if (step > 1) setStep(step - 1);
  };

  const openLink = (url) => {
    if (url) {
      window.open(url, '_blank', 'noopener');
      onClose();
    }
  };

  const canProceed = () => {
    if (step === 1) return selectedDesigner !== null;
    return true;
  };

  const stepLabels = lang === 'ko'
    ? ['디자이너 선택', '예약 문의 방법']
    : ['Select Stylist', 'Contact Method'];

  return (
    <div className="fixed inset-0 z-[70] flex items-end md:items-center justify-center bg-black/60 backdrop-blur-sm fade-in sm:p-4">
      <div className="bg-white w-full max-w-[480px] md:rounded-3xl rounded-t-3xl shadow-2xl flex flex-col overflow-hidden relative max-h-[92vh] animate-slide-up">
        
        {/* 헤더 */}
        <div className="flex-shrink-0 px-6 pt-6 pb-4 border-b border-stone-100">
          <div className="flex items-center justify-between mb-5">
            <div>
              <p className="text-[10px] font-bold tracking-[0.2em] text-stone-400 uppercase">
                {t('예약 문의', 'Booking Inquiry')}
              </p>
              <h3 className="text-lg font-bold text-stone-900 mt-0.5">
                {stepLabels[step - 1]}
              </h3>
            </div>
            <button 
              onClick={onClose} 
              className="w-9 h-9 bg-stone-100 hover:bg-stone-200 rounded-full flex items-center justify-center text-stone-600 transition-colors"
              aria-label="Close"
            >
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
          </div>

          {/* Step Progress */}
          <div className="flex items-center gap-1.5">
            {[1, 2].map((s) => (
              <div 
                key={s}
                className={`flex-1 h-1 rounded-full transition-all duration-300 ${
                  s <= step ? 'bg-stone-900' : 'bg-stone-200'
                }`}
              />
            ))}
          </div>
          <div className="flex items-center justify-between mt-2">
            <span className="text-[10px] text-stone-400 font-medium">
              {t(`${step} / 2 단계`, `Step ${step} of 2`)}
            </span>
          </div>
        </div>

        {/* 본문 스크롤 영역 */}
        <div className="flex-1 overflow-y-auto px-6 py-6">
          
          {/* STEP 1: 디자이너 선택 */}
          {step === 1 && (
            <div>
              <p className="text-sm text-stone-500 mb-5 break-keep">
                {t('상담 받고 싶으신 디자이너를 선택해주세요.', 'Please select the stylist you\'d like to consult with.')}
              </p>
              <div className="grid grid-cols-3 gap-3">
                {allDesigners.map((d, idx) => {
                  const isSelected = selectedDesigner && selectedDesigner.name === d.name;
                  return (
                    <button
                      key={idx}
                      onClick={() => setSelectedDesignerLocal(d)}
                      className={`flex flex-col items-center text-center p-2 rounded-xl transition-all ${
                        isSelected ? 'bg-stone-900 text-white' : 'bg-stone-50 hover:bg-stone-100 text-stone-900'
                      }`}
                    >
                      <div className={`w-16 h-16 rounded-full overflow-hidden mb-2 border-2 ${
                        isSelected ? 'border-white' : 'border-transparent'
                      }`}>
                        <img src={d.img} alt={d.name} className="w-full h-full object-cover" />
                      </div>
                      <span className="text-xs font-bold leading-tight">{t(d.name, d.nameEn)}</span>
                      <span className={`text-[10px] mt-0.5 ${isSelected ? 'text-stone-300' : 'text-stone-400'}`}>
                        {t(d.title, d.titleEn)}
                      </span>
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* STEP 2: 네이버 / 인스타 링크 선택 */}
          {step === 2 && selectedDesigner && (
            <div>
              {/* 선택한 디자이너 요약 */}
              <div className="flex items-center gap-4 bg-stone-50 rounded-2xl p-4 mb-6">
                <img 
                  src={selectedDesigner.img} 
                  alt={selectedDesigner.name} 
                  className="w-14 h-14 rounded-full object-cover flex-shrink-0" 
                />
                <div className="min-w-0 flex-1">
                  <p className="text-[10px] font-bold tracking-[0.15em] text-stone-400 uppercase">
                    {t('선택한 디자이너', 'Selected Stylist')}
                  </p>
                  <p className="font-bold text-stone-900 text-base truncate">
                    {t(selectedDesigner.name, selectedDesigner.nameEn)}
                  </p>
                  <p className="text-xs text-stone-500">
                    {t(selectedDesigner.title, selectedDesigner.titleEn)}
                  </p>
                </div>
              </div>

              <p className="text-sm text-stone-500 mb-5 break-keep">
                {t('원하시는 방법으로 문의해주세요. 선택 시 해당 채널로 바로 이동합니다.', 'Please choose your preferred inquiry method. You\'ll be redirected to the selected channel.')}
              </p>

              <div className="space-y-3">
                {/* 네이버 예약 */}
                {selectedDesigner.bookUrl ? (
                  <button
                    onClick={() => openLink(selectedDesigner.bookUrl)}
                    className="w-full group flex items-center gap-4 p-4 rounded-2xl bg-white border-2 border-stone-100 hover:border-[#03c75a] hover:shadow-md transition-all text-left"
                  >
                    <div className="w-12 h-12 rounded-xl bg-[#03c75a] flex items-center justify-center flex-shrink-0 text-white font-black text-xl tracking-tight">
                      N
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-stone-900 text-base">
                        {t('네이버 예약', 'Naver Booking')}
                      </p>
                      <p className="text-xs text-stone-500 mt-0.5 break-keep">
                        {t('날짜·시간·메뉴를 직접 선택하고 예약하세요', 'Book directly with your preferred date, time & menu')}
                      </p>
                    </div>
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-stone-300 group-hover:text-[#03c75a] group-hover:translate-x-1 transition-all flex-shrink-0">
                      <line x1="5" y1="12" x2="19" y2="12"></line>
                      <polyline points="12 5 19 12 12 19"></polyline>
                    </svg>
                  </button>
                ) : (
                  <div className="w-full flex items-center gap-4 p-4 rounded-2xl bg-stone-50 border-2 border-stone-100 opacity-50 cursor-not-allowed">
                    <div className="w-12 h-12 rounded-xl bg-stone-200 flex items-center justify-center flex-shrink-0 text-stone-400 font-black text-xl">
                      N
                    </div>
                    <div className="flex-1">
                      <p className="font-bold text-stone-400 text-base">
                        {t('네이버 예약', 'Naver Booking')}
                      </p>
                      <p className="text-xs text-stone-400 mt-0.5">
                        {t('현재 이용 불가', 'Currently unavailable')}
                      </p>
                    </div>
                  </div>
                )}

                {/* 인스타그램 DM */}
                {selectedDesigner.ig ? (
                  <button
                    onClick={() => openLink(selectedDesigner.ig)}
                    className="w-full group flex items-center gap-4 p-4 rounded-2xl bg-white border-2 border-stone-100 hover:border-[#fd1d1d] hover:shadow-md transition-all text-left"
                  >
                    <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[#833ab4] via-[#fd1d1d] to-[#fcb045] flex items-center justify-center flex-shrink-0 text-white">
                      <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
                        <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
                        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
                      </svg>
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-bold text-stone-900 text-base">
                        {t('인스타그램 DM 문의', 'Instagram DM')}
                      </p>
                      <p className="text-xs text-stone-500 mt-0.5 break-keep">
                        {t('포트폴리오를 먼저 보고 편하게 문의하세요', 'Browse portfolio and send a DM directly')}
                      </p>
                    </div>
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-stone-300 group-hover:text-[#fd1d1d] group-hover:translate-x-1 transition-all flex-shrink-0">
                      <line x1="5" y1="12" x2="19" y2="12"></line>
                      <polyline points="12 5 19 12 12 19"></polyline>
                    </svg>
                  </button>
                ) : (
                  <div className="w-full flex items-center gap-4 p-4 rounded-2xl bg-stone-50 border-2 border-stone-100 opacity-50 cursor-not-allowed">
                    <div className="w-12 h-12 rounded-xl bg-stone-200 flex items-center justify-center flex-shrink-0 text-stone-400">
                      <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
                        <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
                        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
                      </svg>
                    </div>
                    <div className="flex-1">
                      <p className="font-bold text-stone-400 text-base">
                        {t('인스타그램 DM 문의', 'Instagram DM')}
                      </p>
                      <p className="text-xs text-stone-400 mt-0.5">
                        {t('현재 이용 불가', 'Currently unavailable')}
                      </p>
                    </div>
                  </div>
                )}

                {/* 매장 전화 */}
                <a
                  href="tel:0507-1488-3141"
                  className="w-full group flex items-center gap-4 p-4 rounded-2xl bg-white border-2 border-stone-100 hover:border-stone-900 hover:shadow-md transition-all text-left"
                >
                  <div className="w-12 h-12 rounded-xl bg-stone-900 flex items-center justify-center flex-shrink-0 text-white">
                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                    </svg>
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="font-bold text-stone-900 text-base">
                      {t('매장 전화 문의', 'Call the Salon')}
                    </p>
                    <p className="text-xs text-stone-500 mt-0.5">
                      0507-1488-3141
                    </p>
                  </div>
                  <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="text-stone-300 group-hover:text-stone-900 group-hover:translate-x-1 transition-all flex-shrink-0">
                    <line x1="5" y1="12" x2="19" y2="12"></line>
                    <polyline points="12 5 19 12 12 19"></polyline>
                  </svg>
                </a>
              </div>

              <div className="bg-stone-50 border border-stone-100 rounded-xl p-3 mt-5 flex gap-2.5">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#78716c" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="flex-shrink-0 mt-0.5">
                  <circle cx="12" cy="12" r="10"></circle>
                  <line x1="12" y1="16" x2="12" y2="12"></line>
                  <line x1="12" y1="8" x2="12.01" y2="8"></line>
                </svg>
                <p className="text-[11px] text-stone-600 leading-relaxed break-keep">
                  {t(
                    '네이버 예약 페이지에서 날짜·시간·메뉴를 직접 선택하실 수 있습니다.',
                    'You can select your date, time, and menu directly on the Naver Booking page.'
                  )}
                </p>
              </div>
            </div>
          )}
        </div>

        {/* 푸터 버튼 */}
        <div className="flex-shrink-0 px-6 py-4 border-t border-stone-100 bg-white flex gap-2.5">
          {step > 1 && (
            <button
              onClick={handleBack}
              className="px-5 py-3.5 rounded-xl bg-stone-100 text-stone-700 font-bold text-sm hover:bg-stone-200 transition-colors"
            >
              {t('이전', 'Back')}
            </button>
          )}
          {step < 2 ? (
            <button
              onClick={handleNext}
              disabled={!canProceed()}
              className={`flex-1 py-3.5 rounded-xl font-bold text-sm transition-colors ${
                canProceed()
                  ? 'bg-stone-900 text-white hover:bg-stone-800'
                  : 'bg-stone-100 text-stone-300 cursor-not-allowed'
              }`}
            >
              {t('다음', 'Next')}
            </button>
          ) : (
            <button
              onClick={onClose}
              className="flex-1 py-3.5 rounded-xl bg-stone-100 text-stone-700 font-bold text-sm hover:bg-stone-200 transition-colors"
            >
              {t('닫기', 'Close')}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
