/* ───────── Consulting Process ───────── */
function ProcessSection() {
  const [active, setActive] = useState(0);
  const steps = [
  { t: '상담신청', d: '온라인 또는 유선 상담 신청', sub: '영업일 1일 이내 연락' },
  { t: '진단 미팅', d: '사업 구조 · 자금 흐름 · 신용도 진단', sub: '담당 매니저 배정' },
  { t: '플랜 설계', d: '정책자금 · 렌탈 · 인증 조합 플랜 제안', sub: '맞춤 자금 구조 설계' },
  { t: '신청 · 승인', d: '서류 준비 · 기관 신청', sub: '심사 대응 및 승인' },
  { t: '사후 관리', d: '자금 집행 점검', sub: '연 단위 후속 컨설팅' }];


  return (
    <section className="py-24 lg:py-32 bg-white border-t border-line">
      <div className="max-w-container mx-auto px-6 lg:px-8">
        <div className="max-w-[760px]">
          <div className="text-[13px] font-bold text-brand tracking-[.18em] uppercase">Consulting Process</div>
          <h2 className="h-sec text-[32px] lg:text-[40px] text-ink mt-3">
            상담부터 사후 관리까지,<br />다섯 단계로 끝냅니다.
          </h2>
          <p className="mt-5 text-[16px] lg:text-[17px] text-body body-lg">운림은 신청 한 번으로 끝나지 않습니다. 진단부터 자금 집행 이후의 관리까지,
다섯 단계의 프로세스로 일관되게 운영합니다.

          </p>
          <p className="mt-3 text-[13px] text-mute"></p>
        </div>

        {/* Desktop — 5 bordered step cards in a row, clickable */}
        <div className="hidden md:grid mt-14 grid-cols-5 border border-line rounded-big overflow-hidden bg-white">
          {steps.map((s, i) => {
            const on = active === i;
            return (
              <button
                key={s.t}
                type="button"
                onClick={() => setActive(i)}
                onMouseEnter={() => setActive(i)}
                aria-pressed={on}
                className={`group text-left p-6 lg:p-7 transition-colors duration-200 outline-none focus-visible:ring-2 focus-visible:ring-brand/40 ${
                i < steps.length - 1 ? 'border-r border-line' : ''} ${
                on ? 'bg-tint/50' : 'bg-white hover:bg-soft'}`}>
                
                <div className="flex items-center justify-between">
                  <div className={`num text-[13px] font-bold tracking-[.12em] transition-colors ${
                  on ? 'text-brand' : 'text-mute group-hover:text-ink'}`
                  }>
                    STEP {String(i + 1).padStart(2, '0')}
                  </div>
                  {i < steps.length - 1 &&
                  <div className={`text-[18px] font-light leading-none -mr-1 transition-colors ${
                  on ? 'text-brand/70' : 'text-mute/40'}`
                  }>›</div>
                  }
                </div>

                <div className={`num mt-4 transition-colors ${on ? 'text-brand' : 'text-ink'}`}
                style={{ fontWeight: 800, fontSize: 54, letterSpacing: '-0.04em', lineHeight: 1 }}>
                  {String(i + 1).padStart(2, '0')}
                </div>

                <div className={`mt-6 pt-5 border-t transition-colors ${on ? 'border-brand/20' : 'border-line'}`}>
                  <div className="h-card text-[17px] lg:text-[18px] text-ink">{s.t}</div>
                  <p className="mt-2 text-[13.5px] text-body leading-relaxed">{s.d}</p>
                  <p className="mt-2 text-[12.5px] text-mute leading-relaxed">{s.sub}</p>
                </div>
              </button>);

          })}
        </div>

        {/* Mobile — stacked, also clickable */}
        <div className="md:hidden mt-12 space-y-3">
          {steps.map((s, i) => {
            const on = active === i;
            return (
              <button key={s.t} type="button" onClick={() => setActive(i)}
              className={`w-full text-left flex gap-4 rounded-card p-5 border transition-colors duration-200 ${
              on ? 'bg-tint/50 border-brand/30' : 'bg-white border-line'}`
              }>
                <div className={`num w-12 h-12 rounded-full flex-shrink-0 flex items-center justify-center text-[16px] font-bold transition-colors ${
                on ? 'bg-brand text-white' : 'bg-soft text-ink'}`
                }>{String(i + 1).padStart(2, '0')}</div>
                <div className="min-w-0">
                  <div className={`num text-[11px] font-bold tracking-[.12em] transition-colors ${on ? 'text-brand' : 'text-mute'}`}>
                    STEP {String(i + 1).padStart(2, '0')}
                  </div>
                  <div className="h-card text-[17px] text-ink mt-0.5">{s.t}</div>
                  <div className="mt-1 text-[13.5px] text-body">{s.d}</div>
                  <div className="text-[12.5px] text-mute">{s.sub}</div>
                </div>
              </button>);

          })}
        </div>
      </div>
    </section>);

}

/* ───────── Form ───────── */
function ContactForm() {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [biz, setBiz] = useState('개인사업자');
  const [interest, setInterest] = useState({ '정책자금': true, '렌탈': false, '무상지원': false, '기업인증': false });
  const [memo, setMemo] = useState('');
  const [status, setStatus] = useState('idle'); // idle | sending | success | error
  const [errMsg, setErrMsg] = useState('');

  const FORMSPREE_URL = 'https://formspree.io/f/mqejyoro';

  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    if (!name.trim() || !phone.trim()) {
      setErrMsg('이름과 연락처는 필수입니다.');
      setStatus('error');
      return;
    }
    setStatus('sending');
    setErrMsg('');
    const interests = Object.keys(interest).filter((k) => interest[k]).join(', ') || '미선택';
    const payload = {
      이름: name,
      연락처: phone,
      사업자종류: biz,
      관심서비스: interests,
      문의내용: memo,
      _subject: `[운림 상담신청] ${name} · ${biz} · ${interests}`
    };
    try {
      const r = await fetch(FORMSPREE_URL, {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      if (r.ok) {
        setStatus('success');
        setName('');setPhone('');setBiz('개인사업자');
        setInterest({ '정책자금': true, '렌탈': false, '무상지원': false, '기업인증': false });
        setMemo('');
      } else {
        const data = await r.json().catch(() => ({}));
        setErrMsg(data?.errors?.[0]?.message || '전송에 실패했습니다. 잠시 후 다시 시도해주세요.');
        setStatus('error');
      }
    } catch (err) {
      setErrMsg('네트워크 오류가 발생했습니다. 잠시 후 다시 시도해주세요.');
      setStatus('error');
    }
  };

  return (
    <section id="contact" className="py-24 lg:py-32">
      <div className="max-w-container mx-auto px-6 lg:px-8">
        <div className="max-w-[640px] mx-auto text-center">
          <div className="text-[13px] font-bold text-brand tracking-[.18em] uppercase">Free Consult</div>
          <h2 className="h-sec text-[32px] lg:text-[40px] text-ink mt-3">
            무료 상담으로,<br />플랜의 가능성부터 확인하세요.
          </h2>
          <p className="mt-4 text-[16px] text-body body-lg">
            제출 즉시 운림 담당자가 영업일 기준 1일 이내 연락드립니다.
          </p>
        </div>

        <form onSubmit={submit} className="mt-12 max-w-[640px] mx-auto bg-white border border-line rounded-xl2 p-7 lg:p-10">
          {status === 'success' &&
          <div className="mb-7 flex items-start gap-3 bg-tint border border-brand/20 rounded-[14px] px-5 py-4">
              <span className="flex-shrink-0 w-9 h-9 rounded-full bg-brand text-white flex items-center justify-center font-bold">✓</span>
              <div>
                <div className="text-[15px] font-bold text-ink">신청이 접수되었습니다.</div>
                <div className="text-[13.5px] text-body mt-0.5">영업일 기준 1일 이내 운림 담당자가 연락드립니다.</div>
              </div>
            </div>
          }
          {status === 'error' && errMsg &&
          <div className="mb-5 px-4 py-3 rounded-[12px] bg-red-50 border border-red-200 text-[13.5px] text-red-700">
              {errMsg}
            </div>
          }
          <div className="grid sm:grid-cols-2 gap-4">
            <Field label="이름" required>
              <input value={name} onChange={(e) => setName(e.target.value)}
              placeholder="홍길동" className="input w-full px-4 py-3.5 rounded-[12px] text-[15px] text-ink placeholder:text-mute" />
            </Field>
            <Field label="연락처" required>
              <input value={phone} onChange={(e) => setPhone(e.target.value)}
              placeholder="010-0000-0000" inputMode="tel"
              className="input w-full px-4 py-3.5 rounded-[12px] text-[15px] text-ink placeholder:text-mute num" />
            </Field>
          </div>

          <Field label="사업자 종류" className="mt-5">
            <div className="grid grid-cols-3 gap-2">
              {['개인사업자', '법인사업자', '예비창업'].map((v) =>
              <label key={v} className={`cursor-pointer px-3 py-3 rounded-[12px] text-[14px] font-semibold text-center transition-all ${
              biz === v ? 'bg-ink text-white' : 'bg-soft2 text-body hover:text-ink'}`
              }>
                  <input type="radio" name="biz" className="hidden" checked={biz === v} onChange={() => setBiz(v)} />
                  {v}
                </label>
              )}
            </div>
          </Field>

          <Field label="관심 서비스" className="mt-5">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {Object.keys(interest).map((k) => {
                const on = interest[k];
                return (
                  <button type="button" key={k}
                  onClick={() => setInterest({ ...interest, [k]: !on })}
                  className={`px-3 py-3 rounded-[12px] text-[13.5px] font-semibold transition-all border ${
                  on ? 'bg-tint text-brand border-brand/30' : 'bg-soft2 text-body border-transparent hover:text-ink'}`
                  }>
                    {k}
                  </button>);

              })}
            </div>
          </Field>

          <Field label="문의내용" className="mt-5">
            <textarea value={memo} onChange={(e) => setMemo(e.target.value)} rows={4}
            placeholder="업종, 현재 매출 규모, 자금 목적 등 자유롭게 적어주세요."
            className="input w-full px-4 py-3.5 rounded-[12px] text-[15px] text-ink placeholder:text-mute resize-none" />
          </Field>

          <button type="submit" disabled={status === 'sending'}
          className="btn-brand mt-7 w-full py-4 rounded-[14px] text-[16px] font-bold disabled:opacity-60 disabled:cursor-not-allowed">
            {status === 'sending' ? '전송 중…' : '무료 상담 신청하기'}
          </button>

          <p className="mt-4 text-[13px] text-mute text-center">
            제출 즉시 운림 담당자가 영업일 기준 1일 이내 연락드립니다.
          </p>
        </form>
      </div>
    </section>);

}

function Field({ label, required, className = '', children }) {
  return (
    <div className={className}>
      <div className="flex items-center gap-1.5 mb-2">
        <label className="text-[13px] font-bold text-ink">{label}</label>
        {required && <span className="text-[11px] font-bold text-brand">필수</span>}
      </div>
      {children}
    </div>);

}

/* ───────── Footer ───────── */
function Footer() {
  return (
    <footer className="bg-ink text-white relative">
      {/* CTA strip */}
      <div className="border-b border-white/10">
        <div className="max-w-container mx-auto px-6 lg:px-8 py-8 lg:py-10 flex flex-col lg:flex-row lg:items-center lg:justify-between gap-5">
          <div>
            <div className="text-[11.5px] tracking-[.22em] uppercase font-bold text-brand">Free Consult</div>
            <div className="mt-2 text-[20px] lg:text-[26px] font-extrabold tracking-tight leading-tight">
              지금 시작하면, 자금이 보입니다.
            </div>
          </div>
          <div className="flex flex-col sm:flex-row gap-2.5">
            <a href="tel:01086264638"
               className="px-5 py-3 rounded-[12px] bg-white text-ink font-bold text-[13.5px] hover:opacity-90 transition flex items-center justify-center gap-2">
              <span className="num">010-8626-4638</span>
            </a>
            <a href="https://pf.kakao.com/_pxmxjiG/chat" target="_blank" rel="noopener"
               className="px-5 py-3 rounded-[12px] bg-kakao text-ink font-bold text-[13.5px] hover:opacity-90 transition flex items-center justify-center">
              카카오톡 상담
            </a>
          </div>
        </div>
      </div>

      {/* Brand + contact */}
      <div className="max-w-container mx-auto px-6 lg:px-8 py-16 lg:py-20">
        <div className="grid lg:grid-cols-[1fr_auto] gap-12 lg:gap-20 items-start">
          {/* Left: brand */}
          <div>
            <div className="flex items-center gap-3">
              <img src="assets/logo.png" alt="운림 로고"
                   className="block w-10 h-10 rounded-md object-cover select-none"
                   draggable="false" />
              <span className="text-[12px] tracking-[.22em] font-bold text-white/55">UNLIM</span>
            </div>
            <div className="mt-6 text-[44px] lg:text-[64px] font-extrabold tracking-tight leading-[1.02]">
              운림<span className="text-brand">.</span>
            </div>
            <p className="mt-5 text-[14px] lg:text-[15px] text-white/60 body-lg max-w-[440px]">
              자금 확보의 무상·유상·렌탈·인증 플랜을 한 곳에서.
              신청부터 승인 후 관리까지 운림이 직접 책임집니다.
            </p>
          </div>

          {/* Right: contact dl */}
          <dl className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-1 gap-x-12 gap-y-6 text-[13px] min-w-[260px]">
            <div>
              <dt className="text-[11px] tracking-[.18em] uppercase font-bold text-white/40">전화</dt>
              <dd className="num font-bold text-white text-[16px] mt-1.5">010-8626-4638</dd>
            </div>
            <div>
              <dt className="text-[11px] tracking-[.18em] uppercase font-bold text-white/40">이메일</dt>
              <dd className="font-bold text-white text-[16px] mt-1.5">bizhyg@naver.com</dd>
            </div>
            <div>
              <dt className="text-[11px] tracking-[.18em] uppercase font-bold text-white/40">주소</dt>
              <dd className="text-white/75 text-[14px] mt-1.5 leading-relaxed">서울특별시 강서구<br/>공항대로 209 305호</dd>
            </div>
            <div>
              <dt className="text-[11px] tracking-[.18em] uppercase font-bold text-white/40">사업자등록번호</dt>
              <dd className="text-white/75 text-[14px] mt-1.5 num">727-24-01279</dd>
            </div>
          </dl>
        </div>
      </div>

      {/* Bottom strip */}
      <div className="border-t border-white/10">
        <div className="max-w-container mx-auto px-6 lg:px-8 py-5 flex flex-wrap items-center justify-between gap-3 text-[12.5px]">
          <div className="text-white/45">© 2026 UNLIM. All rights reserved.</div>
          <div className="flex gap-5 text-white/55">
            <a href="#" className="hover:text-white transition">이용약관</a>
            <a href="#" className="hover:text-white transition">개인정보처리방침</a>
          </div>
        </div>
      </div>
    </footer>);

}
function FootCol({ title, items }) {
  return (
    <div>
      <div className="text-[13px] font-bold text-ink">{title}</div>
      <ul className="mt-4 space-y-2 text-[14px] text-body">
        {items.map((x) => <li key={x}><a href="#" className="hover:text-ink">{x}</a></li>)}
      </ul>
    </div>);

}

/* ───────── Floating consult widget ───────── */
function FloatingConsult() {
  // Desktop: vertical quick-nav panel on right edge (replaces previous popover)
  // Mobile: bottom bar (KakaoTalk + phone)
  const items = [
  { label: '서비스 소개', target: 'services' },
  { label: '정책자금', target: 'policy' },
  { label: '승인사례', target: 'cases' },
  { label: 'FAQ', target: 'faq' },
  { label: '상담신청', target: 'contact' }];

  const go = (id) => () => {
    const el = document.getElementById(id);
    if (!el) return;
    const offset = 72; // sticky-nav clearance
    const y = el.getBoundingClientRect().top + window.scrollY - offset;
    window.scrollTo({ top: y, behavior: 'smooth' });
  };

  return (
    <>
      {/* Desktop side quick-nav */}
      <aside className="hidden lg:block fixed right-6 top-1/2 -translate-y-1/2 z-30">
        <div className="relative bg-brand text-white rounded-[14px] overflow-hidden shadow-[0_18px_40px_rgba(31,91,216,0.28)] w-[112px]">
          <div className="px-3 py-4 text-center text-[12.5px] font-bold tracking-tight border-b border-white/15">
            자주 찾는<br />서비스
          </div>
          <ul>
            {items.map((it, i) =>
            <li key={it.label} className={i ? 'border-t border-white/10' : ''}>
                <button onClick={go(it.target)}
              className="w-full px-3 py-4 text-center transition hover:bg-white/8 group">
                  <div className="num text-[11px] font-bold text-white/55 tracking-widest">0{i + 1}</div>
                  <div className="mt-1 text-[13px] font-semibold text-white leading-tight">{it.label}</div>
                </button>
              </li>
            )}
          </ul>
          {/* arrow notch */}
          <div className="absolute -left-[7px] top-1/2 -translate-y-1/2 w-3 h-3 bg-brand rotate-45 rounded-[2px]"></div>
        </div>

        {/* KakaoTalk pill — sits below the panel */}
        <a href="https://pf.kakao.com/_pxmxjiG/chat" target="_blank" rel="noopener"
        className="mt-3 w-full bg-kakao text-ink font-bold text-[13px] py-3 rounded-[12px] hover:opacity-90 transition shadow flex items-center justify-center">
          카카오톡 상담
        </a>
      </aside>

      {/* Mobile bottom bar */}
      <div className="lg:hidden fixed left-0 right-0 bottom-0 z-30 grid grid-cols-2 border-t border-line bg-white">
        <a href="https://pf.kakao.com/_pxmxjiG/chat" target="_blank" rel="noopener"
        className="bg-kakao text-ink font-bold py-3.5 text-[14.5px] flex items-center justify-center">
          카카오톡 상담
        </a>
        <a href="tel:01086264638"
        className="bg-brand text-white font-bold py-3.5 text-[14.5px] flex items-center justify-center num">
          010-8626-4638
        </a>
      </div>
    </>);

}

Object.assign(window, { ContactForm, Footer, FloatingConsult, ProcessSection });