// FAQ + Inquiry Form + Footer + KakaoFAB

const FAQS = [
  { q: "제작 기간은 얼마나 걸리나요?",      a: "디자인 분석부터 3D 모델링, 세공, 마감까지 평균 2–3주가 소요됩니다. 디테일 난이도에 따라 추가 기간이 필요할 수 있습니다." },
  { q: "가격은 어떻게 책정되나요?",         a: "소재(18K 골드 / 플래티넘), 스톤 등급, 디테일 난이도에 따라 결정됩니다. 정확한 견적은 제작 문의를 통해 1:1로 안내드립니다." },
  { q: "A/S는 가능한가요?",                 a: "벨로엔에서 제작한 모든 제품은 평생 A/S를 보장합니다. 사이즈 조정·광택·체인 수리 등 일반 보수는 무상으로 진행됩니다." },
  { q: "반품 / 교환이 가능한가요?",         a: "주문 제작 특성상 단순 변심은 어렵습니다. 다만 출고 시점의 결함은 수령 후 7일 내 교환·재제작을 보장합니다." },
  { q: "배송은 어떻게 진행되나요?",         a: "전 제품 보험 등기 또는 안심 퀵으로 발송됩니다. 서울 권역은 직접 수령도 가능합니다." },
];

function FAQ() {
  const [open, setOpen] = React.useState(0);
  return (
    <section className="section-tight" id="faq">
      <div className="container">
        <div className="eyebrow-row">
          <span className="lbl">10 — QUESTIONS</span>
          <span className="rule"></span>
        </div>
        <h2 className="serif" style={{ margin: "0 0 32px", fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: "clamp(36px, 4.4vw, 64px)", letterSpacing: "0.02em", lineHeight: 1.1 }}>
          자주 받는 <em style={{ fontStyle: "italic", color: "var(--gold)" }}>질문.</em>
        </h2>
        <div className="faq">
          {FAQS.map((f, i) => (
            <div className={"faq-item " + (open === i ? "open" : "")} key={i} onClick={() => setOpen(open === i ? -1 : i)}>
              <div className="faq-q">
                <span className="num">{String(i+1).padStart(2,"0")}</span>
                <span className="text">{f.q}</span>
                <span className="toggle">+</span>
              </div>
              <div className="faq-a"><p>{f.a}</p></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function InquiryModal() {
  const [open, setOpen] = React.useState(false);
  const [kakaoUrl, setKakaoUrl] = React.useState("");

  React.useEffect(() => {
    fetch("/api/config")
      .then(r => r.json())
      .then(d => setKakaoUrl(d.kakaoUrl || ""))
      .catch(() => {});

    const onOpen = () => setOpen(true);
    window.addEventListener("open-inquiry", onOpen);
    return () => window.removeEventListener("open-inquiry", onOpen);
  }, []);

  // Lock body scroll when open
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;

  const goKakao = () => {
    if (!kakaoUrl) {
      alert("카카오톡 상담 채널이 아직 연결되지 않았습니다.\n관리자 페이지에서 URL을 설정해주세요.");
      return;
    }
    window.open(kakaoUrl, "_blank", "noopener,noreferrer");
  };

  return (
    <div className="vl-modal-backdrop" onClick={() => setOpen(false)}>
      <div className="vl-modal" onClick={(e) => e.stopPropagation()}>
        <button className="vl-modal-close" aria-label="닫기" onClick={() => setOpen(false)}>×</button>
        <div className="vl-modal-icon">
          <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.5 2 10.8c0 2.7 1.8 5.1 4.5 6.5l-1 3.6 4.2-2.4c.7.1 1.5.2 2.3.2 5.5 0 10-3.5 10-7.9S17.5 3 12 3z"/></svg>
        </div>
        <h3 className="vl-modal-title serif">제작 문의</h3>
        <p className="vl-modal-desc">
          카카오톡으로 1:1 상담을 받으실 수 있습니다.<br/>
          제품 사진, 사이즈, 요청사항을 자유롭게 보내주세요.
        </p>
        <button className="vl-modal-cta" onClick={goKakao}>
          <svg viewBox="0 0 24 24" fill="currentColor" style={{width:20,height:20,marginRight:8}}><path d="M12 3C6.5 3 2 6.5 2 10.8c0 2.7 1.8 5.1 4.5 6.5l-1 3.6 4.2-2.4c.7.1 1.5.2 2.3.2 5.5 0 10-3.5 10-7.9S17.5 3 12 3z"/></svg>
          카카오톡으로 상담하기
        </button>
        <p className="vl-modal-foot">평일 11:00–19:00 · 답변까지 평균 30분 이내</p>
      </div>
    </div>
  );
}

function _DEPRECATED_Inquiry() {
  const [step, setStep] = React.useState(1);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(false);
  const [error, setError] = React.useState("");
  const [form, setForm] = React.useState({
    category: "RING",
    reference: "",
    metal: "18K Yellow Gold",
    budget: "~ 500K",
    detail: "",
    name: "",
    phone: "",
    email: "",
    channel: "카카오톡",
  });
  const cats = [
    { key: "RING",     label: "반지",   icon: <RingSVG/> },
    { key: "NECKLACE", label: "목걸이", icon: <NecklaceSVG/> },
    { key: "EARRING",  label: "귀걸이", icon: <EarringSVG/> },
    { key: "BRACELET", label: "팔찌",   icon: <BraceletSVG/> },
    { key: "WATCH",    label: "시계",   icon: <WatchSVG/> },
  ];
  const update = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = async () => {
    setError("");
    if (!form.name.trim()) { setError("성함을 입력해주세요"); return; }
    if (!/^[0-9+\-\s()]{7,20}$/.test(form.phone.trim())) {
      setError("연락처 형식이 올바르지 않습니다"); return;
    }
    setSubmitting(true);
    try {
      const r = await fetch("/api/contact", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(form),
      });
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || "전송 실패");
      setSubmitted(true);
    } catch (e) {
      setError(e.message || "전송 중 오류가 발생했습니다");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section className="section-tight" id="inquiry">
      <div className="container">
        <div className="eyebrow-row">
          <span className="lbl">11 — INQUIRY · 제작 문의</span>
          <span className="rule"></span>
        </div>
        <h2 className="serif" style={{ margin: "0 0 32px", fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: "clamp(36px, 4.4vw, 64px)", letterSpacing: "0.02em", lineHeight: 1.1 }}>
          제작 <em style={{ fontStyle: "italic", color: "var(--gold)" }}>문의.</em>
        </h2>
        {submitted ? (
          <div className="inquiry-card" style={{ textAlign: "center", padding: "60px 24px" }}>
            <div style={{ fontSize: 48, color: "var(--gold)", marginBottom: 16 }}>✦</div>
            <h3 style={{ fontFamily: "var(--font-serif)", fontWeight: 500, fontSize: 28, margin: "0 0 12px" }}>문의가 접수되었습니다</h3>
            <p style={{ color: "var(--fg-2)", lineHeight: 1.7 }}>
              24시간 내에 입력하신 연락 채널로 회신드리겠습니다.<br/>
              벨로엔과 함께해 주셔서 감사합니다.
            </p>
          </div>
        ) : (
        <div className="inquiry-card">
          <div className="inquiry-steps">
            <div className={"inquiry-step " + (step >= 1 ? "active" : "")} onClick={() => setStep(1)}>
              <div className="n">STEP 01</div><div className="t">카테고리 선택</div>
            </div>
            <div className={"inquiry-step " + (step >= 2 ? "active" : "")} onClick={() => setStep(2)}>
              <div className="n">STEP 02</div><div className="t">상세 디자인</div>
            </div>
            <div className={"inquiry-step " + (step >= 3 ? "active" : "")} onClick={() => setStep(3)}>
              <div className="n">STEP 03</div><div className="t">연락처</div>
            </div>
          </div>

          {step === 1 && (
            <div>
              <div className="cat-grid">
                {cats.map(c => (
                  <div className={"cat-tile " + (form.category === c.key ? "selected" : "")} key={c.key} onClick={() => update("category", c.key)}>
                    {c.icon}
                    <span>{c.label}</span>
                  </div>
                ))}
              </div>
              <div className="field">
                <label>REFERENCE · 원하는 스타일 / 레퍼런스</label>
                <input type="text" value={form.reference} onChange={(e) => update("reference", e.target.value)} placeholder="제작을 희망하시는 제품명 또는 이미지 링크를 입력해주세요."/>
              </div>
              <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 16 }}>
                <button className="cta-btn" onClick={() => setStep(2)}>다음 단계 →</button>
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <div className="field-row">
                <div className="field">
                  <label>METAL · 소재</label>
                  <select value={form.metal} onChange={(e) => update("metal", e.target.value)}>
                    <option>18K Yellow Gold</option><option>18K White Gold</option><option>18K Rose Gold</option><option>Platinum</option><option>Silver</option>
                  </select>
                </div>
                <div className="field">
                  <label>BUDGET · 예산</label>
                  <select value={form.budget} onChange={(e) => update("budget", e.target.value)}>
                    <option>~ 500K</option><option>500K — 1M</option><option>1M — 2M</option><option>2M +</option>
                  </select>
                </div>
              </div>
              <div className="field">
                <label>DETAIL · 상세 요청</label>
                <textarea rows="5" value={form.detail} onChange={(e) => update("detail", e.target.value)} placeholder="원하시는 디자인, 사이즈, 디테일 요청사항을 자유롭게 적어주세요."></textarea>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 16 }}>
                <button className="cta-btn" onClick={() => setStep(1)} style={{ background: "transparent", color: "var(--gold)" }}>← 이전</button>
                <button className="cta-btn" onClick={() => setStep(3)}>다음 단계 →</button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <div className="field-row">
                <div className="field"><label>NAME · 성함</label><input type="text" value={form.name} onChange={(e) => update("name", e.target.value)}/></div>
                <div className="field"><label>PHONE · 연락처</label><input type="text" value={form.phone} onChange={(e) => update("phone", e.target.value)} placeholder="010-0000-0000"/></div>
              </div>
              <div className="field"><label>EMAIL · 이메일 (선택)</label><input type="email" value={form.email} onChange={(e) => update("email", e.target.value)}/></div>
              <div className="field">
                <label>PREFERRED CHANNEL · 응답 채널</label>
                <select value={form.channel} onChange={(e) => update("channel", e.target.value)}>
                  <option>카카오톡</option><option>전화</option><option>이메일</option>
                </select>
              </div>
              {error && <p style={{ color: "var(--danger, #C45A4F)", fontSize: 14, marginTop: 12 }}>{error}</p>}
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 24 }}>
                <button className="cta-btn" onClick={() => setStep(2)} style={{ background: "transparent", color: "var(--gold)" }} disabled={submitting}>← 이전</button>
                <button className="cta-btn" onClick={submit} disabled={submitting}>
                  {submitting ? "전송 중..." : "의뢰 보내기 →"}
                </button>
              </div>
            </div>
          )}
        </div>
        )}
      </div>
    </section>
  );
}

function KakaoFAB() {
  return (
    <button
      className="kakao-fab"
      aria-label="카카오톡 상담"
      onClick={() => window.dispatchEvent(new CustomEvent("open-inquiry"))}
    >
      <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 3C6.5 3 2 6.5 2 10.8c0 2.7 1.8 5.1 4.5 6.5l-1 3.6 4.2-2.4c.7.1 1.5.2 2.3.2 5.5 0 10-3.5 10-7.9S17.5 3 12 3z"/></svg>
    </button>
  );
}

function Footer() {
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="top">
          <div>
            <div className="brand" style={{ fontFamily: "var(--font-serif)", letterSpacing: "0.20em" }}>VELOEN</div>
            <div className="tag">Everyday Mood, Veloen Jewelry.</div>
            <p>벨로엔 쥬얼리 워크샵<br/>섬세한 디테일과 높은 완성도 — Premium Jewelry Manufacturing</p>
          </div>
          <div>
            <div className="col-title">MENU</div>
            <a style={{cursor:"pointer"}} onClick={() => document.getElementById("portfolio")?.scrollIntoView({behavior:"smooth"})}>포트폴리오</a>
            <a style={{cursor:"pointer"}} onClick={() => document.getElementById("reviews")?.scrollIntoView({behavior:"smooth"})}>고객 후기</a>
            <a style={{cursor:"pointer"}} onClick={() => window.dispatchEvent(new CustomEvent("open-inquiry"))}>제작 문의</a>
          </div>
          <div>
            <div className="col-title">CONTACT</div>
            <a>카카오톡 · @veloen</a>
            <a>VELOEN JEWELRY</a>
          </div>
          <div>
            <div className="col-title">HOURS</div>
            <p>평일 11:00 — 19:00<br/>토 · 일 · 공휴일 휴무<br/>방문 상담 · 예약제</p>
          </div>
        </div>
        <div className="legal">
          <small>© 2026 VELOEN JEWELRY · ALL RIGHTS RESERVED</small>
          <small>BUSINESS NO. 000-00-00000</small>
        </div>
      </div>
    </footer>
  );
}

window.FAQ = FAQ;
window.InquiryModal = InquiryModal;
window.KakaoFAB = KakaoFAB;
window.Footer = Footer;
