/* 온라인 예약 — 기존 예약 폼 리스타일(UI만). 단계·필드·순서는 그대로.
   어르신도 쉽게: 큰 글씨·큰 버튼·명확한 단계·필수 * 표시·항상 활성 신청 버튼. */

const HOME = "/";

/* 작은 인라인 아이콘 (검색·카메라 등 DS에 딱 맞는 게 없을 때만) */
function SearchIcon() {
  return (<svg className="ic" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2" /><path d="M20 20l-3.2-3.2" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" /></svg>);
}
function CameraIcon() {
  return (<svg className="ic" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M4 8.5h3l1.4-2h7.2L17 8.5h3a1.5 1.5 0 0 1 1.5 1.5v8A1.5 1.5 0 0 1 20 19.5H4A1.5 1.5 0 0 1 2.5 18v-8A1.5 1.5 0 0 1 4 8.5Z" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" /><circle cx="12" cy="13" r="3.2" stroke="currentColor" strokeWidth="2" /></svg>);
}

/* ---------- 상단 네비 (메인과 동일) ---------- */
function BookingNav() {
  const { Icon } = window.WantedDesignSystem_954e41;
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const closeMenu = () => setMenuOpen(false);
  return (
    <header className={"nav" + (scrolled ? " scrolled" : "") + (menuOpen ? " menu-open" : "")}>
      <div className="wrap nav-inner">
        <a href={HOME} className="brand" style={{ textDecoration: "none" }}>
          <img src="assets/logo-kkf.png" alt="깔끔한친구들" className="brand-logo" />
        </a>
        <nav className="nav-links">
          <a href="/about">깔끔한친구들은?</a>
          <div className="nav-drop">
            <a href={HOME + "#services"} className="nav-drop-trigger">서비스 상품<Chevron /></a>
            <div className="nav-menu" role="menu">
              {window.SERVICE_LIST.map((s, i) =>
              <a key={i} href={window.SERVICE_URLS[s] || (HOME + "#services")} role="menuitem">{s}{!window.SERVICE_URLS[s] && <span className="soon">준비중</span>}</a>
              )}
            </div>
          </div>
          <a href="/reviews">고객 후기</a>
          <a href="/blog">작업사례 &amp; 관리팁</a>
        </nav>
        <a href={window.TEL_HREF} className="nav-phone" style={{ color: scrolled ? "var(--mint-600)" : "#fff", textDecoration: "none", fontSize: 16 }}>{window.TEL}</a>
        <button className="nav-burger" aria-label={menuOpen ? "메뉴 닫기" : "메뉴 열기"} aria-expanded={menuOpen} onClick={() => setMenuOpen((v) => !v)}>
          <Icon name={menuOpen ? "close" : "menu"} size={26} />
        </button>
      </div>
      <div className={"nav-mobile" + (menuOpen ? " open" : "")}>
        <a href="/about" onClick={closeMenu}>깔끔한친구들은?</a>
        <div className="sub-label">서비스 상품</div>
        {window.SERVICE_LIST.map((s, i) =>
        <a key={i} href={window.SERVICE_URLS[s] || (HOME + "#services")} className="svc" onClick={closeMenu}>{s}{!window.SERVICE_URLS[s] && <span className="soon">준비중</span>}</a>
        )}
        <a href="/reviews" onClick={closeMenu}>고객 후기</a>
        <a href="/blog" onClick={closeMenu}>작업사례 &amp; 관리팁</a>
      </div>
    </header>);
}

/* ---------- 품목 데이터 (예상 소요시간·가격) ---------- */
const ITEM_GROUPS = [
  { cat: "에어컨", items: [
    { id: "ac-wall", name: "벽걸이 에어컨", min: 60, price: 75000, won: "원" },
    { id: "ac-stand", name: "스탠드 에어컨", min: 90, price: 120000, won: "원~" },
    { id: "ac-1way", name: "천장형 1way", min: 60, price: 100000, won: "원" },
    { id: "ac-4way", name: "천장형 4way", min: 90, price: 140000, won: "원" },
    { id: "ac-pkg", name: "스탠드 + 벽걸이 패키지", min: 120, price: 190000, won: "원~" } ] },
  { cat: "세탁기", items: [
    { id: "wm-top", name: "통돌이 세탁기", min: 90, price: 120000, won: "원" },
    { id: "wm-drum", name: "드럼 세탁기", min: 120, price: 180000, won: "원" } ] } ];
const ALL_ITEMS = ITEM_GROUPS.flatMap((g) => g.items);

/* 주소 검색 데모 결과 */
const SAMPLE_ADDR = [
  { zip: "13529", road: "경기 성남시 분당구 판교역로 235" },
  { zip: "16942", road: "경기 용인시 기흥구 흥덕중앙로 120" },
  { zip: "05510", road: "서울 송파구 올림픽로 300" },
  { zip: "13595", road: "경기 성남시 분당구 성남대로 343번길 9" } ];

const TIME_SLOTS = [
  { t: "09:00", full: false }, { t: "10:30", full: false }, { t: "13:00", full: false },
  { t: "14:30", full: true }, { t: "16:00", full: false }, { t: "17:30", full: false } ];

function won(n) { return n.toLocaleString("ko-KR"); }
function fmtMin(m) {
  const h = Math.floor(m / 60), mm = m % 60;
  return (h ? h + "시간" : "") + (mm ? " " + mm + "분" : "");
}
function fmtDate(d) {
  if (!d) return "";
  const days = ["일", "월", "화", "수", "목", "금", "토"];
  return `${d.getMonth() + 1}월 ${d.getDate()}일 (${days[d.getDay()]})`;
}

/* ---------- 예약 폼 ---------- */
function Booking() {
  const { Icon, Calendar } = window.WantedDesignSystem_954e41;
  const [qty, setQty] = React.useState({});
  const [pickOpen, setPickOpen] = React.useState(false);
  const [addrOpen, setAddrOpen] = React.useState(false);
  const [road, setRoad] = React.useState("");
  const [detail, setDetail] = React.useState("");
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [wait, setWait] = React.useState(false);
  const [name, setName] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [request, setRequest] = React.useState("");
  const [files, setFiles] = React.useState([]);
  const [done, setDone] = React.useState(false);

  const totalCount = Object.values(qty).reduce((a, b) => a + b, 0);
  const totalPrice = ALL_ITEMS.reduce((sum, it) => sum + (qty[it.id] || 0) * it.price, 0);
  const totalMin = ALL_ITEMS.reduce((sum, it) => sum + (qty[it.id] || 0) * it.min, 0);
  const bump = (id, d) => setQty((q) => { const n = Math.max(0, (q[id] || 0) + d); return { ...q, [id]: n }; });

  const pickAddr = (a) => { setRoad(a.road); setAddrOpen(false); };

  /* 다음 할 일(항상 하나만 안내) */
  const next =
    totalCount === 0 ? { step: "s1", msg: "품목을 선택해 주세요" } :
    !road ? { step: "s2", msg: "주소를 검색해 주세요" } :
    !detail.trim() ? { step: "s2", msg: "상세주소를 입력해 주세요" } :
    !date ? { step: "s3", msg: "방문 날짜를 선택해 주세요" } :
    !time ? { step: "s3", msg: "방문 시간을 선택해 주세요" } :
    !name.trim() ? { step: "s4", msg: "이름을 입력해 주세요" } :
    !phone.trim() ? { step: "s4", msg: "전화번호를 입력해 주세요" } :
    null;

  const goStep = (id) => {
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 88, behavior: "smooth" });
  };
  const submit = () => { if (next) goStep(next.step); else setDone(true); };

  const onFiles = (e) => {
    const list = Array.from(e.target.files || []).map((f) => f.name);
    if (list.length) setFiles((prev) => [...prev, ...list]);
  };

  return (
    <React.Fragment>
      {/* 헤더 */}
      <section className="bk-hero">
        <div className="wrap">
          <span className="eyebrow">온라인 예약</span>
          <h1>30초면 예약 끝</h1>
          <p className="sub">아래 순서대로 채워주시면 돼요. 어려우면 <b style={{ color: "#fff" }}>{window.TEL}</b> 로 전화 주세요.</p>
          <div className="trust-line">
            <span><b>✓</b> 가격 정찰제 · 추가금 없음</span>
            <span><b>✓</b> 서울·경기 출장비 무료</span>
            <span><b>✓</b> 3개월 무상 A/S</span>
          </div>
        </div>
      </section>

      <div className="bk-body">
        <div className="bk-wrap">

          {/* STEP 1 품목 */}
          <section className="step reveal" id="s1">
            <div className="step-head">
              <div className="step-no">1</div>
              <div>
                <h2 className="step-title">품목 선택<span className="req">*</span></h2>
                <p className="step-sub">청소할 가전을 고르고, 수량을 정해 주세요.</p>
              </div>
            </div>

            {totalCount > 0 &&
            <div className="picked-list">
              {ALL_ITEMS.filter((it) => (qty[it.id] || 0) > 0).map((it) => {
                const q = qty[it.id] || 0;
                return (
                  <div className="item-row on" key={it.id}>
                    <div className="item-main">
                      <div className="item-name">{it.name}</div>
                      <div className="item-meta">
                        <span className="time"><Icon name="clock" size={16} color="var(--label-alternative)" />예상 {fmtMin(it.min)}</span>
                        <span className="price">{won(it.price)}{it.won}</span>
                      </div>
                    </div>
                    <div className="stepper">
                      <button type="button" aria-label={it.name + " 수량 줄이기"} onClick={() => bump(it.id, -1)}>−</button>
                      <span className="qty">{q}</span>
                      <button type="button" className="plus" aria-label={it.name + " 수량 늘리기"} onClick={() => bump(it.id, 1)}>+</button>
                    </div>
                  </div>);
              })}
            </div>}

            <button type="button" className="add-item" onClick={() => setPickOpen(true)}>
              <span className="ai-plus">+</span>{totalCount > 0 ? "품목 추가·변경하기" : "품목 추가하기"}
            </button>
            {totalCount === 0 &&
            <p className="add-item-hint"><Icon name="circle-info" size={16} color="var(--label-alternative)" />위 버튼을 눌러 청소할 가전을 골라주세요.</p>}

            {totalCount > 0 ?
            <div className="bk-summary">
              <div className="row">
                <span className="lab"><Icon name="clock" size={18} color="rgba(255,255,255,.7)" />예상 소요시간</span>
                <span className="val">약 {fmtMin(totalMin)}</span>
              </div>
              <div className="row">
                <span className="lab">예상 금액 ({totalCount}개)</span>
                <span className="val"><span className="mk">{won(totalPrice)}</span>원~</span>
              </div>
              <p className="note">* 예상 금액이며, 현장 확인 후 최종 확정됩니다. 안내 금액 외 당일 추가금은 없습니다.</p>
            </div> :
            <div className="bk-summary-empty">품목을 선택하면 예상 소요시간과 금액을 알려드려요.</div>}
          </section>

          {/* STEP 2 주소 */}
          <section className="step reveal" id="s2">
            <div className="step-head">
              <div className="step-no">2</div>
              <div>
                <h2 className="step-title">주소 입력<span className="req">*</span></h2>
                <p className="step-sub">방문할 집 주소를 알려주세요.</p>
              </div>
            </div>
            <div className="field">
              <label className="field-label">도로명 주소<span className="req">*</span></label>
              <div className="addr-row">
                <input className="input" type="text" placeholder="주소 검색 버튼을 눌러주세요" value={road} readOnly />
                <button type="button" className="addr-btn" onClick={() => setAddrOpen(true)}><SearchIcon />주소 검색</button>
              </div>
            </div>
            <div className="field">
              <label className="field-label">상세주소<span className="req">*</span></label>
              <input className="input" type="text" placeholder={road ? "동·호수 등 나머지 주소를 입력해 주세요" : "먼저 주소를 검색해 주세요"}
                value={detail} onChange={(e) => setDetail(e.target.value)} disabled={!road} />
              {!road &&
              <div className="help warn"><Icon name="circle-info" size={16} color="var(--req)" />먼저 위에서 주소를 검색해 주세요.</div>}
            </div>
          </section>

          {/* STEP 3 날짜·시간 */}
          <section className="step reveal" id="s3">
            <div className="step-head">
              <div className="step-no">3</div>
              <div>
                <h2 className="step-title">날짜 · 시간 선택<span className="req">*</span></h2>
                <p className="step-sub">원하시는 방문 날짜와 시간을 골라주세요.</p>
              </div>
            </div>
            <div className="cal-shell">
              <Calendar value={date || undefined} onChange={(d) => { setDate(d); setTime(null); }} />
            </div>

            <div className="slots-label">
              {date ? <>{<span className="day">{fmtDate(date)}</span>} 방문 가능 시간</> : "날짜를 먼저 선택해 주세요"}
            </div>
            {date ?
            <div className="slot-grid">
              {TIME_SLOTS.map((s) =>
              <button type="button" key={s.t} className={"slot" + (time === s.t ? " on" : "")}
                disabled={s.full} onClick={() => setTime(s.t)}>
                {s.full ? "마감" : s.t}
              </button>)}
            </div> :
            <div className="slots-empty">위 달력에서 날짜를 선택하면 가능한 시간이 나타나요.</div>}

            <div className={"wait-card" + (wait ? " on" : "")} onClick={() => setWait((v) => !v)} role="checkbox" aria-checked={wait} tabIndex={0}>
              <div className="wait-box"><Icon name="circle-check-fill" size={18} color="#fff" /></div>
              <div className="wait-txt">
                <strong>취소·공백 발생 시 빠른 일정 제안 받기</strong>
                <span>다른 예약이 취소되어 더 빠른 방문이 가능해지면, 상시방문 대기로 먼저 알려드려요. (선택)</span>
              </div>
            </div>
          </section>

          {/* STEP 4 신청자 정보 */}
          <section className="step reveal" id="s4">
            <div className="step-head">
              <div className="step-no">4</div>
              <div>
                <h2 className="step-title">신청자 정보</h2>
                <p className="step-sub">연락드릴 수 있게 이름과 전화번호를 남겨주세요.</p>
              </div>
            </div>
            <div className="field">
              <label className="field-label">이름<span className="req">*</span></label>
              <input className="input" type="text" placeholder="예: 홍길동" value={name} onChange={(e) => setName(e.target.value)} />
            </div>
            <div className="field">
              <label className="field-label">전화번호<span className="req">*</span></label>
              <input className="input" type="tel" inputMode="numeric" placeholder="예: 010-1234-5678" value={phone} onChange={(e) => setPhone(e.target.value)} />
            </div>
            <div className="field">
              <label className="field-label">요청사항<span className="opt">선택</span></label>
              <textarea className="textarea" placeholder="주차 안내, 반려동물, 특이사항 등 편하게 적어주세요." value={request} onChange={(e) => setRequest(e.target.value)}></textarea>
            </div>
            <div className="field">
              <label className="field-label">환경 사진 업로드<span className="opt">선택</span></label>
              <label className="upload">
                <span className="up-ic"><CameraIcon /></span>
                <span className="up-txt">
                  <strong>사진 추가하기</strong>
                  <span>가전 상태·설치 위치 사진을 올려주시면 상담이 빨라져요.</span>
                </span>
                <input type="file" accept="image/*" multiple onChange={onFiles} />
              </label>
              {files.length > 0 &&
              <div className="up-files">
                {files.map((f, i) =>
                <div className="up-file" key={i}><Icon name="circle-check-fill" size={16} color="var(--mint-600)" />{f}</div>)}
              </div>}
            </div>
          </section>
        </div>
      </div>

      {/* 하단 고정 신청 영역 */}
      <div className="bk-submit">
        <div className="bk-submit-inner">
          <div className={"bk-hint " + (next ? "todo" : "done")}>
            {next ? <>👉 다음: {next.msg}</> : <>✅ 모두 입력됐어요! 이제 신청하시면 돼요.</>}
          </div>
          <button type="button" className="bk-btn" onClick={submit}>
            <Icon name="circle-check-fill" size={22} color="#fff" />서비스 신청하기
          </button>
        </div>
      </div>

      {/* 품목 선택 모달 */}
      {pickOpen &&
      <div className="addr-pop" onClick={() => setPickOpen(false)}>
        <div className="addr-pop-card pick-card" onClick={(e) => e.stopPropagation()}>
          <div className="addr-pop-head">
            <strong>품목 선택</strong>
            <button type="button" aria-label="닫기" onClick={() => setPickOpen(false)}><Icon name="close" size={22} /></button>
          </div>
          <div className="pick-body">
            {ITEM_GROUPS.map((g) =>
            <div className="cat-group" key={g.cat}>
              <div className="cat-label">{g.cat}</div>
              {g.items.map((it) => {
                const q = qty[it.id] || 0;
                return (
                  <div className={"item-row" + (q > 0 ? " on" : "")} key={it.id}>
                    <div className="item-main">
                      <div className="item-name">{it.name}</div>
                      <div className="item-meta">
                        <span className="time"><Icon name="clock" size={16} color="var(--label-alternative)" />예상 {fmtMin(it.min)}</span>
                        <span className="price">{won(it.price)}{it.won}</span>
                      </div>
                    </div>
                    <div className="stepper">
                      <button type="button" aria-label={it.name + " 수량 줄이기"} onClick={() => bump(it.id, -1)} disabled={q === 0}>−</button>
                      <span className="qty">{q}</span>
                      <button type="button" className="plus" aria-label={it.name + " 수량 늘리기"} onClick={() => bump(it.id, 1)}>+</button>
                    </div>
                  </div>);
              })}
            </div>
            )}
          </div>
          <div className="pick-foot">
            <button type="button" className="bk-btn" style={{ height: 58, fontSize: 19 }} onClick={() => setPickOpen(false)}>
              {totalCount > 0 ? `${totalCount}개 선택 완료` : "닫기"}
            </button>
          </div>
        </div>
      </div>}

      {/* 주소 검색 오버레이(데모) */}
      {addrOpen &&
      <div className="addr-pop" onClick={() => setAddrOpen(false)}>
        <div className="addr-pop-card" onClick={(e) => e.stopPropagation()}>
          <div className="addr-pop-head">
            <strong>주소 검색</strong>
            <button type="button" aria-label="닫기" onClick={() => setAddrOpen(false)}><Icon name="close" size={22} /></button>
          </div>
          <div className="search">
            <input className="input" type="text" placeholder="도로명·건물명·지번으로 검색" autoFocus />
          </div>
          <div className="results">
            {SAMPLE_ADDR.map((a, i) =>
            <button type="button" key={i} onClick={() => pickAddr(a)}>
              <span className="zip">{a.zip}</span><span className="road">{a.road}</span>
            </button>)}
          </div>
        </div>
      </div>}

      {/* 신청 완료(데모) */}
      {done &&
      <div className="addr-pop" onClick={() => setDone(false)}>
        <div className="addr-pop-card" onClick={(e) => e.stopPropagation()} style={{ maxWidth: 400, textAlign: "center", padding: "36px 28px" }}>
          <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--mint-soft)", color: "var(--mint-600)", display: "grid", placeItems: "center", margin: "0 auto 18px" }}>
            <Icon name="circle-check-fill" size={36} color="var(--mint-500)" />
          </div>
          <div style={{ fontFamily: "var(--font-brand)", fontWeight: 800, fontSize: 24, color: "var(--navy-800)", letterSpacing: "-0.02em" }}>신청이 접수됐어요</div>
          <p style={{ margin: "12px 0 24px", fontSize: 16, lineHeight: 1.6, color: "var(--label-neutral)" }}>담당자가 예약 확인 후 <b>{phone || "남겨주신 번호"}</b>로 연락드릴게요. 감사합니다.</p>
          <button type="button" className="bk-btn" style={{ height: 58, fontSize: 19 }} onClick={() => setDone(false)}>확인</button>
        </div>
      </div>}
    </React.Fragment>);
}

Object.assign(window, { BookingNav, Booking });
