// contact-sections.jsx — 틴트라이프 · CONTACT page. Uses CONTACT (home-data).
const { useState } = React;

const INQUIRY_TYPES = ["가맹·창업 문의", "원데이클래스 문의", "기타 문의"];
const AGE_RANGES = ["20대 이하", "30대", "40대", "50대", "60대 이상"];
const LICENSE_OPTIONS = ["미보유", "보유", "취득 예정"];

function ContactInfo() {
  return (
    <div className="ct-info">
      <p className="ct-info-kicker">TINTLIFE</p>
      <h2 className="ct-info-title">전화 또는 폼으로<br />편하게 문의하세요.</h2>
      <p className="ct-info-lead">예약·가맹·교육 관련 문의를 남겨주시면 본사에서 순차적으로 유선 연락드립니다. 100% 예약제로 운영됩니다.</p>

      <ul className="ct-info-list">
        <li className="ct-info-item">
          <span className="ct-info-ic" aria-hidden="true">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M4 4h3l1.5 4-2 1.5a11 11 0 005 5l1.5-2 4 1.5v3a1.5 1.5 0 01-1.6 1.5C8.6 18.4 1.6 11.4 2.5 5.6A1.5 1.5 0 014 4z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>
          </span>
          <span className="ct-info-txt">
            <span className="ct-info-label">전화 · {CONTACT.telLabel}</span>
            <a className="ct-info-val ct-info-link" href={`tel:${CONTACT.tel}`}>{CONTACT.tel}</a>
          </span>
        </li>
        <li className="ct-info-item">
          <span className="ct-info-ic" aria-hidden="true">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><rect x="2.5" y="4" width="15" height="12" rx="2" stroke="currentColor" strokeWidth="1.5"/><path d="M3 5.5l7 5 7-5" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>
          </span>
          <span className="ct-info-txt">
            <span className="ct-info-label">이메일</span>
            <a className="ct-info-val ct-info-link" href={`mailto:${CONTACT.email}`}>{CONTACT.email}</a>
          </span>
        </li>
        <li className="ct-info-item">
          <span className="ct-info-ic" aria-hidden="true">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10 2.5c3.3 0 6 2.6 6 5.9 0 4-6 9.1-6 9.1s-6-5.1-6-9.1c0-3.3 2.7-5.9 6-5.9z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/><circle cx="10" cy="8.2" r="2.1" stroke="currentColor" strokeWidth="1.5"/></svg>
          </span>
          <span className="ct-info-txt">
            <span className="ct-info-label">오시는 길</span>
            <span className="ct-info-val">{CONTACT.address}</span>
            <span className="ct-info-sub">{CONTACT.way}</span>
          </span>
        </li>
      </ul>

      <div className="ct-info-maps">
        <a className="ct-map-btn" href={CONTACT.naverMap} target="_blank" rel="noreferrer">네이버 지도</a>
        <a className="ct-map-btn" href={CONTACT.kakaoMap} target="_blank" rel="noreferrer">카카오 지도</a>
      </div>
    </div>
  );
}

function ContactForm() {
  const [f, setF] = useState({ name: "", phone: "", email: "", region: "", license: LICENSE_OPTIONS[0], ageRange: "", type: INQUIRY_TYPES[0], msg: "", agree: false, overseasAgree: false, marketingAgree: false });
  const [sent, setSent] = useState(false);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");

  const set = (k) => (e) => setF((s) => ({ ...s, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value }));
  const setAllAgreements = (e) => {
    const checked = e.target.checked;
    setF((s) => ({ ...s, agree: checked, overseasAgree: checked, marketingAgree: checked }));
  };

  const setPhone = (e) => {
    const digits = e.target.value.replace(/\D/g, "").slice(0, 11);
    let v = digits;
    if (digits.startsWith("02")) {
      if (digits.length > 6) v = digits.slice(0, 2) + "-" + digits.slice(2, 6) + "-" + digits.slice(6);
      else if (digits.length > 2) v = digits.slice(0, 2) + "-" + digits.slice(2);
    } else {
      if (digits.length > 7) v = digits.slice(0, 3) + "-" + digits.slice(3, 7) + "-" + digits.slice(7);
      else if (digits.length > 3) v = digits.slice(0, 3) + "-" + digits.slice(3);
    }
    setF((s) => ({ ...s, phone: v }));
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!f.name.trim() || !f.phone.trim() || !f.email.trim() || !f.region.trim() || !f.msg.trim()) { setErr("이름, 연락처, 이메일, 희망 개설 지역, 문의 내용을 입력해 주세요."); return; }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim())) { setErr("올바른 이메일 주소를 입력해 주세요."); return; }
    const phoneDigits = f.phone.replace(/\D/g, "");
    if (phoneDigits.length < 9 || phoneDigits.length > 11) { setErr("올바른 전화번호를 입력해 주세요. 예: 010-1234-5678"); return; }
    if (!f.agree) { setErr("개인정보 수집·이용에 동의해 주세요."); return; }
    if (!f.overseasAgree) { setErr("국외 처리(이전) 안내에 동의해 주세요."); return; }
    setErr("");
    setLoading(true);
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: f.name, phone: f.phone, email: f.email, region: f.region, license: f.license, ageRange: f.ageRange, type: f.type, msg: f.msg, privacyConsent: f.agree, overseasConsent: f.overseasAgree, marketingConsent: f.marketingAgree, consentAt: new Date().toISOString() }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "서버 오류");
      }
      setSent(true);
    } catch (ex) {
      setErr(ex.message || "전송 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
    } finally {
      setLoading(false);
    }
  };

  if (sent) {
    return (
      <div className="ct-form-card ct-sent">
        <div className="ct-sent-ic" aria-hidden="true">
          <svg width="34" height="34" viewBox="0 0 34 34" fill="none"><circle cx="17" cy="17" r="16" stroke="currentColor" strokeWidth="1.6"/><path d="M10 17.5l4.5 4.5L24 12.5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
        <h3 className="ct-sent-title">문의가 전송되었습니다</h3>
        <p className="ct-sent-sub">담당자가 확인 후 <strong>입력하신 연락처</strong>로 답변드리겠습니다.<br />급하신 분은 전화로 연락 주세요.</p>
        <a className="ct-sent-mail" href={`tel:${CONTACT.tel}`}>{CONTACT.tel}</a>
        <button className="ct-btn ct-btn--ghost" type="button" onClick={() => setSent(false)}>다시 문의하기</button>
      </div>
    );
  }

  return (
    <form className="ct-form-card" onSubmit={submit} noValidate>
      <h3 className="ct-form-title">문의 남기기</h3>

      <div className="ct-field-row">
        <label className="ct-field">
          <span className="ct-label">이름 <em>*</em></span>
          <input className="ct-input" type="text" value={f.name} onChange={set("name")} placeholder="성함을 입력하세요" disabled={loading} />
        </label>
        <label className="ct-field">
          <span className="ct-label">연락처 <em>*</em></span>
          <input className="ct-input" type="tel" inputMode="numeric" value={f.phone} onChange={setPhone} placeholder="010-0000-0000" maxLength={13} disabled={loading} />
        </label>
      </div>

      <label className="ct-field">
        <span className="ct-label">이메일 <em>*</em></span>
        <input className="ct-input" type="email" value={f.email} onChange={set("email")} placeholder="회신받을 이메일을 입력하세요" disabled={loading} />
      </label>

      <div className="ct-field-row">
        <label className="ct-field">
          <span className="ct-label">개설 희망 지역 <em>*</em></span>
          <input className="ct-input" type="text" value={f.region} onChange={set("region")} placeholder="예: 서울 강남구" disabled={loading} />
        </label>
        <label className="ct-field">
          <span className="ct-label">자격증 여부</span>
          <div className="ct-select-wrap">
            <select className="ct-input ct-select" value={f.license} onChange={set("license")} disabled={loading}>
              {LICENSE_OPTIONS.map((v) => <option key={v} value={v}>{v}</option>)}
            </select>
            <svg className="ct-select-caret" width="12" height="8" viewBox="0 0 12 8" fill="none" aria-hidden="true"><path d="M1 1.5L6 6l5-4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
        </label>
      </div>

      <label className="ct-field">
        <span className="ct-label">연령대 <em>(선택)</em></span>
        <div className="ct-select-wrap">
          <select className="ct-input ct-select" value={f.ageRange} onChange={set("ageRange")} disabled={loading}>
            <option value="">선택해 주세요</option>
            {AGE_RANGES.map((v) => <option key={v} value={v}>{v}</option>)}
          </select>
          <svg className="ct-select-caret" width="12" height="8" viewBox="0 0 12 8" fill="none" aria-hidden="true"><path d="M1 1.5L6 6l5-4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
      </label>

      <label className="ct-field">
        <span className="ct-label">문의 유형</span>
        <div className="ct-select-wrap">
          <select className="ct-input ct-select" value={f.type} onChange={set("type")} disabled={loading}>
            {INQUIRY_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
          </select>
          <svg className="ct-select-caret" width="12" height="8" viewBox="0 0 12 8" fill="none" aria-hidden="true"><path d="M1 1.5L6 6l5-4.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </div>
      </label>

      <label className="ct-field">
        <span className="ct-label">문의 내용 <em>*</em></span>
        <textarea className="ct-input ct-textarea" value={f.msg} onChange={set("msg")} rows={5} placeholder="문의하실 내용을 자유롭게 작성해 주세요." disabled={loading} />
      </label>

      <label className="ct-agree ct-agree--all">
        <input type="checkbox" checked={f.agree && f.overseasAgree && f.marketingAgree} onChange={setAllAgreements} disabled={loading} />
        <span><strong>모두 동의하기</strong> <em>(개인정보 수집·이용, 국외 처리 및 마케팅 정보 수신)</em></span>
      </label>
      <label className="ct-agree ct-agree--detail">
        <input type="checkbox" checked={f.agree} onChange={set("agree")} disabled={loading} />
        <span><strong>개인정보 수집·이용</strong>에 동의합니다. (동의를 거부할 수 있으나, 거부 시 문의 접수가 제한됩니다.)</span>
      </label>
      <label className="ct-agree ct-agree--detail">
        <input type="checkbox" checked={f.overseasAgree} onChange={set("overseasAgree")} disabled={loading} />
        <span><strong>개인정보 국외 처리(이전) 안내</strong>에 동의합니다. (Vercel·Gmail의 글로벌 인프라에서 처리될 수 있으며, 거부 시 문의 접수가 제한됩니다.)</span>
      </label>
      <label className="ct-agree ct-agree--detail">
        <input type="checkbox" checked={f.marketingAgree} onChange={set("marketingAgree")} disabled={loading} />
        <span><strong>창업 관련 정보 및 염색방 창업 정보를 카카오톡·문자로 받아보는 것에 동의합니다.</strong> <em>(선택)</em></span>
      </label>
      <p className="ct-form-note" style={{ textAlign: "left", marginTop: 8 }}><a href="privacy.html" target="_blank" rel="noreferrer">개인정보 처리방침 및 동의 내용 보기</a></p>

      {err && <p className="ct-err" role="alert">{err}</p>}

      <button className="ct-btn" type="submit" disabled={loading}>
        {loading ? "전송 중…" : "문의 보내기"}
        {!loading && <svg width="20" height="10" viewBox="0 0 20 10" fill="none" aria-hidden="true"><path d="M0 5h17M17 5l-3.6-4M17 5l-3.6 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
      </button>
      <p className="ct-form-note">작성하신 문의는 틴트라이프 상담 관리 시트에 안전하게 접수됩니다.</p>
    </form>
  );
}

function Contact() {
  return (
    <section className="ct-main" data-screen-label="contact">
      <div className="tl-wrap">
        <header className="ct-head">
          <p className="ct-kicker">CONTACT</p>
          <h1 className="ct-title">문의하기</h1>
          <p className="ct-sub">궁금한 점을 남겨주시면 빠르게 답변드리겠습니다.</p>
        </header>
        <div className="ct-grid">
          <ContactInfo />
          <ContactForm />
        </div>
      </div>
    </section>
  );
}

window.Contact = Contact;
