// ===================== MENTORING APPLICATION MODAL =====================

const GOOGLE_FORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSfanp_5BedH6Cc-GDh07eXlz4XjBry5X7xCGzTE4H7aRPoyZg/formResponse";
const FIELD_MAP = {
  name: "entry.1873564836",
  phone: "entry.1893427209",
  email: "entry.2013491279",
  preferredContact: "entry.2025993176",
  currentSituation: "entry.1885713176",
  mentoringAreas: "entry.1136456752",
  goal: "entry.331709428",
  challenge: "entry.150080928",
};

function formatPhone(value) {
  const digits = value.replace(/\D/g, "").slice(0, 11);
  if (digits.length <= 3) return digits;
  if (digits.length <= 7) return digits.slice(0, 3) + "-" + digits.slice(3);
  return digits.slice(0, 3) + "-" + digits.slice(3, 7) + "-" + digits.slice(7);
}

function validateForm(s) {
  const e = {};
  if (!s.name.trim() || s.name.trim().length < 2) e.name = "이름을 입력해 주세요";
  if (!/^01[0-9]\d{7,8}$/.test(s.phone.replace(/-/g, ""))) e.phone = "올바른 전화번호를 입력해 주세요";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email)) e.email = "올바른 이메일을 입력해 주세요";
  if (!s.preferredContact) e.preferredContact = "선호 연락 방법을 선택해 주세요";
  if (!s.currentSituation) e.currentSituation = "현재 상황을 선택해 주세요";
  if (s.currentSituation === "기타" && !s.situationOther.trim()) e.situationOther = "현재 상황을 입력해 주세요";
  if (s.mentoringAreas.length === 0) e.mentoringAreas = "관심 영역을 1개 이상 선택해 주세요";
  return e;
}

const initForm = {
  name: "", phone: "", email: "",
  preferredContact: "", currentSituation: "", situationOther: "",
  mentoringAreas: [], goal: "", challenge: "",
  submitStatus: "idle", errors: {},
};

function formReducer(state, action) {
  switch (action.type) {
    case "SET_FIELD":
      return { ...state, [action.field]: action.value, errors: { ...state.errors, [action.field]: "" } };
    case "TOGGLE_AREA": {
      const has = state.mentoringAreas.includes(action.value);
      const areas = has
        ? state.mentoringAreas.filter(a => a !== action.value)
        : state.mentoringAreas.length < 3
          ? [...state.mentoringAreas, action.value]
          : state.mentoringAreas;
      return { ...state, mentoringAreas: areas, errors: { ...state.errors, mentoringAreas: "" } };
    }
    case "SET_ERRORS": return { ...state, errors: action.errors };
    case "SET_STATUS": return { ...state, submitStatus: action.status };
    case "RESET": return { ...initForm };
    default: return state;
  }
}

// ---------- Sub-components ----------

function ChoiceButton({ label, selected, onClick, gold }) {
  return (
    <button
      type="button"
      className={`choice-btn${selected ? " selected" : ""}${selected && gold ? " gold" : ""}`}
      onClick={onClick}
    >{label}</button>
  );
}

function FormField({ label, required, error, hint, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <label style={{ display: "block", fontSize: 14, fontWeight: 600, color: "var(--text-0)", marginBottom: 10 }}>
        {label}{required && <span style={{ color: "#EF4444", marginLeft: 4 }}>*</span>}
        {hint && <span style={{ color: "var(--text-3)", fontWeight: 400, fontSize: 13, marginLeft: 8 }}>{hint}</span>}
      </label>
      {children}
      {error && <p className="form-error-text">{error}</p>}
    </div>
  );
}

function InfoBanner() {
  return (
    <div className="info-banner">
      <p>
        <strong style={{ color: "var(--emerald)" }}>문기준 멘토</strong>가 직접 검토 후<br />
        선호하신 연락 방법으로 회신드립니다.
      </p>
      <p style={{ marginTop: 12 }}>
        <span style={{ color: "var(--emerald)", fontWeight: 600 }}>첫 온보딩 상담 (10~20분) 무료</span><br />
        온보딩에서는 현재 상황을 파악하고,<br />
        맞춤 멘토링 방향과 계획을 함께 세웁니다.
      </p>
      <p style={{ marginTop: 12 }}>
        이후 본 멘토링은 <strong style={{ color: "var(--text-0)" }}>유료</strong>로 진행되지만,<br />
        <span style={{ color: "var(--text-1)" }}>유료 진행 여부는 상담 후 편하게 결정하시면 됩니다.</span>
      </p>
    </div>
  );
}

function SuccessView({ onClose }) {
  return (
    <div style={{ padding: "60px 28px", textAlign: "center" }}>
      <div style={{
        width: 64, height: 64, borderRadius: "50%",
        background: "rgba(16,185,129,0.15)", margin: "0 auto 24px",
        display: "flex", alignItems: "center", justifyContent: "center",
      }}>
        <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--emerald)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 6L9 17l-5-5" />
        </svg>
      </div>
      <h3 style={{ fontSize: 22, fontWeight: 700, color: "var(--text-0)", marginBottom: 12 }}>
        신청이 완료되었습니다!
      </h3>
      <p style={{ fontSize: 15, color: "var(--text-1)", lineHeight: 1.7, marginBottom: 32 }}>
        선호하신 연락 방법으로<br />빠르게 회신드리겠습니다.
      </p>
      <button className="modal-submit-btn" onClick={onClose} style={{ maxWidth: 200, margin: "0 auto" }}>
        닫기
      </button>
    </div>
  );
}

// ---------- Main Modal ----------

function MentoringModal({ isOpen, onClose }) {
  const [state, dispatch] = React.useReducer(formReducer, initForm);
  const containerRef = React.useRef(null);

  // ESC close + body scroll lock
  React.useEffect(() => {
    if (!isOpen) return;
    const handleEsc = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", handleEsc);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", handleEsc);
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  // Reset form after close animation
  React.useEffect(() => {
    if (!isOpen) {
      const t = setTimeout(() => dispatch({ type: "RESET" }), 300);
      return () => clearTimeout(t);
    }
  }, [isOpen]);

  async function handleSubmit() {
    const errors = validateForm(state);
    if (Object.keys(errors).length > 0) {
      dispatch({ type: "SET_ERRORS", errors });
      // Scroll to first error
      if (containerRef.current) {
        const firstErr = containerRef.current.querySelector(".form-error-text");
        if (firstErr) firstErr.scrollIntoView({ behavior: "smooth", block: "center" });
      }
      return;
    }
    dispatch({ type: "SET_STATUS", status: "submitting" });

    try {
      if (GOOGLE_FORM_URL) {
        const params = new URLSearchParams();
        const situation = state.currentSituation === "기타"
          ? "기타: " + state.situationOther : state.currentSituation;
        Object.entries(FIELD_MAP).forEach(([key, entryId]) => {
          let val = "";
          if (key === "name") val = state.name;
          else if (key === "phone") val = state.phone;
          else if (key === "email") val = state.email;
          else if (key === "preferredContact") val = state.preferredContact;
          else if (key === "currentSituation") val = situation;
          else if (key === "mentoringAreas") val = state.mentoringAreas.join(", ");
          else if (key === "goal") val = state.goal;
          else if (key === "challenge") val = state.challenge;
          params.append(entryId, val);
        });
        await fetch(GOOGLE_FORM_URL, {
          method: "POST", mode: "no-cors",
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
          body: params.toString(),
        });
      }
      dispatch({ type: "SET_STATUS", status: "success" });
    } catch {
      dispatch({ type: "SET_STATUS", status: "error" });
      setTimeout(() => dispatch({ type: "SET_STATUS", status: "idle" }), 3000);
    }
  }

  const CONTACT_OPTIONS = ["전화", "카카오톡", "이메일", "문자(SMS)"];
  const SITUATION_OPTIONS = ["대학생 (재학)", "대학원생", "취업 준비생", "현직자 (이직 준비)", "비전공자 (타 분야)", "기타"];
  const AREA_OPTIONS = [
    "AI/ML 직무 탐색", "포트폴리오 & 이력서", "코딩테스트 & 기술면접",
    "대학원 진학 상담", "외국계 취업 전략", "세일즈 오피스 직무", "AI 프로젝트 코칭",
  ];

  return (
    <div className={"modal-overlay" + (isOpen ? " active" : "")} onClick={onClose}>
      <div className="modal-container" ref={containerRef} role="dialog" aria-modal="true" aria-labelledby="modal-title" onClick={e => e.stopPropagation()}>

        {state.submitStatus === "success" ? (
          <SuccessView onClose={onClose} />
        ) : (
          <>
            {/* Header */}
            <div className="modal-header">
              <div>
                <h2 id="modal-title" style={{ fontSize: 20, fontWeight: 700, color: "var(--text-0)", margin: 0 }}>
                  멘토링 신청
                </h2>
                <p style={{ fontSize: 14, color: "var(--text-2)", marginTop: 6, marginBottom: 0 }}>
                  간단한 정보를 남겨주시면, 멘토가 직접 검토 후 연락드립니다.
                </p>
              </div>
              <button className="modal-close-btn" onClick={onClose} aria-label="닫기">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            </div>

            {/* Body */}
            <div className="modal-body">

              {state.submitStatus === "error" && (
                <div style={{ background: "rgba(239,68,68,0.1)", border: "1px solid rgba(239,68,68,0.3)", borderRadius: 12, padding: "12px 16px", marginBottom: 20, fontSize: 14, color: "#F87171" }}>
                  전송에 실패했습니다. 잠시 후 다시 시도해 주세요.
                </div>
              )}

              {/* 기본 정보 */}
              <FormField label="이름" required error={state.errors.name}>
                <input className={"form-input" + (state.errors.name ? " error" : "")}
                  type="text" placeholder="홍길동" value={state.name}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "name", value: e.target.value })} />
              </FormField>

              <FormField label="전화번호" required error={state.errors.phone}>
                <input className={"form-input" + (state.errors.phone ? " error" : "")}
                  type="tel" placeholder="010-1234-5678" value={state.phone}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "phone", value: formatPhone(e.target.value) })} />
              </FormField>

              <FormField label="이메일" required error={state.errors.email}>
                <input className={"form-input" + (state.errors.email ? " error" : "")}
                  type="email" placeholder="example@email.com" value={state.email}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "email", value: e.target.value })} />
              </FormField>

              {/* 구분선 */}
              <div style={{ height: 1, background: "var(--line)", margin: "8px 0 28px" }} />

              {/* 선호 연락 방법 */}
              <FormField label="선호 연락 방법" required error={state.errors.preferredContact}>
                <div className="choice-group">
                  {CONTACT_OPTIONS.map(opt => (
                    <ChoiceButton key={opt} label={opt}
                      selected={state.preferredContact === opt}
                      onClick={() => dispatch({ type: "SET_FIELD", field: "preferredContact", value: opt })} />
                  ))}
                </div>
              </FormField>

              {/* 현재 상황 */}
              <FormField label="현재 상황" required error={state.errors.currentSituation}>
                <div className="choice-group">
                  {SITUATION_OPTIONS.map(opt => (
                    <ChoiceButton key={opt} label={opt}
                      selected={state.currentSituation === opt}
                      onClick={() => dispatch({ type: "SET_FIELD", field: "currentSituation", value: opt })} />
                  ))}
                </div>
              </FormField>

              {state.currentSituation === "기타" && (
                <div style={{ marginTop: -16, marginBottom: 24 }}>
                  <input className={"form-input" + (state.errors.situationOther ? " error" : "")}
                    type="text" placeholder="현재 상황을 알려주세요"
                    value={state.situationOther}
                    onChange={e => dispatch({ type: "SET_FIELD", field: "situationOther", value: e.target.value })} />
                  {state.errors.situationOther && <p className="form-error-text">{state.errors.situationOther}</p>}
                </div>
              )}

              {/* 관심 멘토링 영역 */}
              <FormField label="관심 멘토링 영역" required hint="(최대 3개 선택)" error={state.errors.mentoringAreas}>
                <div className="choice-group">
                  {AREA_OPTIONS.map(opt => (
                    <ChoiceButton key={opt} label={opt}
                      selected={state.mentoringAreas.includes(opt)}
                      gold={opt === "세일즈 오피스 직무"}
                      onClick={() => dispatch({ type: "TOGGLE_AREA", value: opt })} />
                  ))}
                </div>
              </FormField>

              {/* 구분선 */}
              <div style={{ height: 1, background: "var(--line)", margin: "8px 0 28px" }} />

              {/* 주관식 질문 */}
              <FormField label="멘토링을 통해 이루고 싶은 목표가 있다면?" hint="(선택)">
                <textarea className="form-input" rows={3}
                  placeholder="예: 6개월 내 외국계 IT 기업 이직, AI 분야 포트폴리오 완성 등"
                  value={state.goal} style={{ resize: "vertical", minHeight: 80 }}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "goal", value: e.target.value })} />
              </FormField>

              <FormField label="현재 가장 고민되는 점은 무엇인가요?" hint="(선택)">
                <textarea className="form-input" rows={3}
                  placeholder="예: 비전공자라 어디서부터 시작해야 할지 모르겠어요, 이력서 피드백을 받고 싶어요 등"
                  value={state.challenge} style={{ resize: "vertical", minHeight: 80 }}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "challenge", value: e.target.value })} />
              </FormField>

              {/* 안내 배너 */}
              <InfoBanner />

              {/* 제출 */}
              <button
                className="modal-submit-btn"
                disabled={state.submitStatus === "submitting"}
                onClick={handleSubmit}
              >
                {state.submitStatus === "submitting" ? (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                    <svg className="spinner" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                      <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" />
                    </svg>
                    신청 중...
                  </span>
                ) : "멘토링 신청하기"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ===================== EBOOK PRE-ORDER MODAL =====================

const EBOOK_FORM_URL = "https://docs.google.com/forms/d/e/1FAIpQLSduQ0wBd27pXdmJsBI3e5-B4Qc2O2M9P08VB2lnBiobaL8Uwg/formResponse";
const EBOOK_FIELD_MAP = {
  name: "entry.105215705",
  email: "entry.772154716",
  phone: "entry.1008215388",
  preferredContact: "entry.822545060",
};

const initEbook = {
  name: "", email: "", phone: "", preferredContact: "",
  submitStatus: "idle", errors: {},
};

function ebookReducer(state, action) {
  switch (action.type) {
    case "SET_FIELD":
      return { ...state, [action.field]: action.value, errors: { ...state.errors, [action.field]: "" } };
    case "SET_ERRORS": return { ...state, errors: action.errors };
    case "SET_STATUS": return { ...state, submitStatus: action.status };
    case "RESET": return { ...initEbook };
    default: return state;
  }
}

function EbookModal({ isOpen, onClose }) {
  const [state, dispatch] = React.useReducer(ebookReducer, initEbook);

  React.useEffect(() => {
    if (!isOpen) return;
    const handleEsc = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", handleEsc);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", handleEsc);
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  React.useEffect(() => {
    if (!isOpen) {
      const t = setTimeout(() => dispatch({ type: "RESET" }), 300);
      return () => clearTimeout(t);
    }
  }, [isOpen]);

  async function handleSubmit() {
    const errors = {};
    if (!state.name.trim() || state.name.trim().length < 2) errors.name = "이름을 입력해 주세요";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(state.email)) errors.email = "올바른 이메일을 입력해 주세요";
    if (!/^01[0-9]\d{7,8}$/.test(state.phone.replace(/-/g, ""))) errors.phone = "올바른 전화번호를 입력해 주세요";
    if (!state.preferredContact) errors.preferredContact = "선호 연락 방법을 선택해 주세요";

    if (Object.keys(errors).length > 0) {
      dispatch({ type: "SET_ERRORS", errors });
      return;
    }
    dispatch({ type: "SET_STATUS", status: "submitting" });

    try {
      const params = new URLSearchParams();
      params.append(EBOOK_FIELD_MAP.name, state.name);
      params.append(EBOOK_FIELD_MAP.email, state.email);
      params.append(EBOOK_FIELD_MAP.phone, state.phone);
      params.append(EBOOK_FIELD_MAP.preferredContact, state.preferredContact);
      await fetch(EBOOK_FORM_URL, {
        method: "POST", mode: "no-cors",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: params.toString(),
      });
      dispatch({ type: "SET_STATUS", status: "success" });
    } catch {
      dispatch({ type: "SET_STATUS", status: "error" });
      setTimeout(() => dispatch({ type: "SET_STATUS", status: "idle" }), 3000);
    }
  }

  const CONTACT_OPTIONS = ["전화", "카카오톡", "이메일", "문자(SMS)"];

  return (
    <div className={"modal-overlay" + (isOpen ? " active" : "")} onClick={onClose}>
      <div className="modal-container" role="dialog" aria-modal="true" onClick={e => e.stopPropagation()}>

        {state.submitStatus === "success" ? (
          <div style={{ padding: "60px 28px", textAlign: "center" }}>
            <div style={{
              width: 64, height: 64, borderRadius: "50%",
              background: "rgba(245,158,11,0.15)", margin: "0 auto 24px",
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="var(--gold)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M20 6L9 17l-5-5" />
              </svg>
            </div>
            <h3 style={{ fontSize: 22, fontWeight: 700, color: "var(--text-0)", marginBottom: 12 }}>
              사전 신청이 완료되었습니다!
            </h3>
            <p style={{ fontSize: 15, color: "var(--text-1)", lineHeight: 1.7, marginBottom: 32 }}>
              전자책 런칭과 동시에<br />선호하신 연락 방법으로 알림을 드리겠습니다.
            </p>
            <button className="modal-submit-btn" onClick={onClose} style={{
              maxWidth: 200, margin: "0 auto",
              background: "var(--grad-gold)",
            }}>닫기</button>
          </div>
        ) : (
          <>
            <div className="modal-header">
              <div>
                <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 8 }}>
                  <h2 style={{ fontSize: 20, fontWeight: 700, color: "var(--text-0)", margin: 0 }}>
                    전자책 사전 신청
                  </h2>
                  <span className="badge badge-gold" style={{ fontSize: 11 }}>COMING SOON</span>
                </div>
                <p style={{ fontSize: 14, color: "var(--text-2)", marginTop: 0, marginBottom: 0, lineHeight: 1.6 }}>
                  관심을 가져주셔서 감사합니다!<br />
                  6월 중 런칭 예정이며, 출시와 동시에<br />
                  선호하시는 연락 방법으로 알림을 드리겠습니다.
                </p>
              </div>
              <button className="modal-close-btn" onClick={onClose} aria-label="닫기">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                  <path d="M18 6L6 18M6 6l12 12" />
                </svg>
              </button>
            </div>

            <div className="modal-body">
              {state.submitStatus === "error" && (
                <div style={{ background: "rgba(239,68,68,0.1)", border: "1px solid rgba(239,68,68,0.3)", borderRadius: 12, padding: "12px 16px", marginBottom: 20, fontSize: 14, color: "#F87171" }}>
                  전송에 실패했습니다. 잠시 후 다시 시도해 주세요.
                </div>
              )}

              <FormField label="이름" required error={state.errors.name}>
                <input className={"form-input" + (state.errors.name ? " error" : "")}
                  type="text" placeholder="홍길동" value={state.name}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "name", value: e.target.value })} />
              </FormField>

              <FormField label="이메일" required error={state.errors.email}>
                <input className={"form-input" + (state.errors.email ? " error" : "")}
                  type="email" placeholder="example@email.com" value={state.email}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "email", value: e.target.value })} />
              </FormField>

              <FormField label="전화번호" required error={state.errors.phone}>
                <input className={"form-input" + (state.errors.phone ? " error" : "")}
                  type="tel" placeholder="010-1234-5678" value={state.phone}
                  onChange={e => dispatch({ type: "SET_FIELD", field: "phone", value: formatPhone(e.target.value) })} />
              </FormField>

              <FormField label="선호 연락 방법" required error={state.errors.preferredContact}>
                <div className="choice-group">
                  {CONTACT_OPTIONS.map(opt => (
                    <ChoiceButton key={opt} label={opt}
                      selected={state.preferredContact === opt}
                      onClick={() => dispatch({ type: "SET_FIELD", field: "preferredContact", value: opt })} />
                  ))}
                </div>
              </FormField>

              <div className="info-banner" style={{ borderLeftColor: "var(--gold)", background: "rgba(245,158,11,0.06)" }}>
                <p>
                  사전 신청하시면 <strong style={{ color: "var(--gold)" }}>출시 알림</strong>과<br />
                  <strong style={{ color: "var(--gold)" }}>얼리버드 할인 혜택</strong>을 드립니다.
                </p>
              </div>

              <button
                className="modal-submit-btn"
                style={{ background: "var(--grad-gold)", color: "#1A1A1A" }}
                disabled={state.submitStatus === "submitting"}
                onClick={handleSubmit}
              >
                {state.submitStatus === "submitting" ? (
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                    <svg className="spinner" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                      <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83" />
                    </svg>
                    신청 중...
                  </span>
                ) : "사전 신청하기"}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { MentoringModal, EbookModal });
