/* ContactPage.jsx */

function Field({ id, label, required, type='text', placeholder, children, form, errors, onFieldChange }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <label style={{ display:'block', fontSize:13, fontWeight:700, color:'#333', marginBottom:7, letterSpacing:'-0.01em' }}>
        {label}{required && <span style={{ color:'#C8271D', marginLeft:3 }}>*</span>}
      </label>
      {children || (
        <input type={type} placeholder={placeholder || label}
          value={form[id] || ''}
          onChange={e => onFieldChange(id, e.target.value)}
          style={{ width:'100%', padding:'13px 16px', border:'1.5px solid', borderColor:errors[id]?'#C8271D':'#e0e0e0', borderRadius:8, fontSize:14, fontFamily:'inherit', fontWeight:500, color:'#1a1a1a', outline:'none', transition:'border-color 200ms', background:'#fff', letterSpacing:'-0.01em', boxSizing:'border-box' }}
          onFocus={e => e.target.style.borderColor='#1a1a1a'}
          onBlur={e => e.target.style.borderColor=errors[id]?'#C8271D':'#e0e0e0'}
        />
      )}
      {errors[id] && <div style={{ fontSize:12, color:'#C8271D', marginTop:5, fontWeight:500 }}>{errors[id]}</div>}
    </div>
  );
}

function ContactPage() {
  const [form, setForm] = React.useState({ name:'', org:'', email:'', phone:'', product:'', industry:'', message:'', agree:false });
  const [submitted, setSubmitted] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [sendError, setSendError] = React.useState('');
  const [errors, setErrors] = React.useState({});
  const [fileName, setFileName] = React.useState('');
  const formRef = React.useRef(null);

  const handleFieldChange = React.useCallback((id, val) => {
    setForm(p => ({ ...p, [id]: val }));
  }, []);

  const products = ['PFS-304', 'PFS-303 Apparel', 'Shape Care', 'SHAPENIX', '미정 / 추천 요청'];
  const industries = ['한의원', '비만센터', '에스테틱', '의류', '연구기관', '보건소', '기타'];

  const validate = () => {
    const e = {};
    if (!form.org.trim()) e.org = '소속명을 입력해주세요';
    if (!form.name.trim()) e.name = '담당자 이름을 입력해주세요';
    if (!form.email.trim() || !/\S+@\S+\.\S+/.test(form.email)) e.email = '올바른 이메일을 입력해주세요';
    if (!form.phone.trim()) e.phone = '연락처를 입력해주세요';
    if (!form.agree) e.agree = '개인정보 수집에 동의해주세요';
    return e;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const errs = validate();
    if (Object.keys(errs).length > 0) { setErrors(errs); return; }

    setSending(true);
    setSendError('');

    const messageWithFile = (form.message || '(내용 없음)') +
      (fileName ? `\n\n[첨부파일 요청: ${fileName}]\n※ 파일은 담당자가 별도로 요청드립니다.` : '');

    const now = new Date();
    const submitted_at = now.toLocaleString('ko-KR', { timeZone:'Asia/Seoul', year:'numeric', month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit', second:'2-digit' });

    // 구글 시트 기록 추가 (응답을 읽을 수 없으므로 실패해도 이메일 전송에는 영향 없음)
    fetch('https://script.google.com/macros/s/AKfycbxo5DAvbRqfJoiuq8zCu6MhOuA3G2HphM6vDdcy71n2EsWNuasu-xu4gPmH2uWxy5gZ/exec', {
      method: 'POST',
      mode: 'no-cors',
      body: JSON.stringify({
        org:      form.org,
        name:     form.name,
        email:    form.email,
        phone:    form.phone,
        product:  form.product  || '미선택',
        industry: form.industry || '미선택',
        message:  messageWithFile,
      }),
    }).catch(() => {});

    emailjs.send('service_c2sgd84', 'template_yj6j999', {
      org:          form.org,
      name:         form.name,
      email:        form.email,
      phone:        form.phone,
      product:      form.product  || '미선택',
      industry:     form.industry || '미선택',
      message:      messageWithFile,
      submitted_at: submitted_at,
    })
    .then(() => {
      setSending(false);
      setSubmitted(true);
      setFileName('');
    })
    .catch((err) => {
      setSending(false);
      setSendError('전송 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요. (' + (err?.text || err) + ')');
    });



  };

  const fp = { form, errors, onFieldChange: handleFieldChange };

  return (
    <div style={{ paddingTop: NAV_HEIGHT, background:'#fff', minHeight:'100vh' }}>

      {/* Header */}
      <div className="pmt-pad-lg" style={{ background:'#1a1a1a', padding:'56px 48px' }}>
        <div style={{ maxWidth:1280, margin:'0 auto' }}>
          <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.14em', textTransform:'uppercase', color:'rgba(255,255,255,0.35)', marginBottom:14 }}>Contact Us</div>
          <h1 style={{ fontSize:'clamp(32px,6vw,48px)', fontWeight:800, color:'#fff', letterSpacing:'-0.04em', lineHeight:1.1, marginBottom:16 }}>문의하기</h1>

        </div>
      </div>

      <div className="pmt-pad-lg" style={{ maxWidth:1280, margin:'0 auto', padding:'64px 48px' }}>

        {/* Quote Form */}
        <div className="rgrid-2" style={{ display:'grid', gridTemplateColumns:'3fr 2fr', gap:64 }}>
            <div>
              {submitted ? (
                <div style={{ background:'#f0fff4', border:'1.5px solid #b2f2c1', borderRadius:16, padding:'48px', textAlign:'center' }}>
                  <div style={{ fontSize:48, marginBottom:16 }}>✓</div>
                  <h3 style={{ fontSize:24, fontWeight:800, color:'#1a1a1a', marginBottom:12, letterSpacing:'-0.03em' }}>문의가 접수되었습니다</h3>
                  <p style={{ fontSize:16, color:'#555', lineHeight:1.7, fontWeight:500 }}>영업일 기준 1일 이내에 담당자가 연락드리겠습니다.<br/>감사합니다.</p>
                  <button onClick={()=>{ setSubmitted(false); setForm({ name:'', org:'', email:'', phone:'', product:'', industry:'', message:'', agree:false }); }} style={{ marginTop:24, background:'#1a1a1a', color:'#fff', border:'none', borderRadius:99, padding:'12px 28px', fontSize:14, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>새 문의 작성</button>
                </div>
              ) : (
                <form onSubmit={handleSubmit} noValidate>
                  <h2 style={{ fontSize:28, fontWeight:800, color:'#1a1a1a', letterSpacing:'-0.03em', marginBottom:32 }}>견적 문의서</h2>

                  <div className="rgrid-2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
                    <Field {...fp} id="org" label="소속명" required placeholder="회사명 / 기관명" />
                    <Field {...fp} id="name" label="담당자 이름" required placeholder="홍길동" />
                  </div>
                  <div className="rgrid-2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
                    <Field {...fp} id="email" label="이메일" required type="email" placeholder="example@company.com" />
                    <Field {...fp} id="phone" label="연락처" required placeholder="010-0000-0000" />
                  </div>

                  <Field {...fp} id="product" label="관심 제품">
                    <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                      {products.map(p => (
                        <button key={p} type="button" onClick={()=>setForm(prev=>({...prev, product:p}))}
                          style={{ padding:'8px 16px', borderRadius:99, border:'1.5px solid', borderColor:form.product===p?'#C8271D':'#e0e0e0', background:form.product===p?'#fff5f5':'#fafafa', fontSize:13, fontWeight:600, color:form.product===p?'#C8271D':'#666', cursor:'pointer', fontFamily:'inherit', transition:'all 200ms' }}>{p}</button>
                      ))}
                    </div>
                  </Field>

                  <Field {...fp} id="industry" label="관련 업종">
                    <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                      {industries.map(ind => (
                        <button key={ind} type="button" onClick={()=>setForm(prev=>({...prev, industry:ind}))}
                          style={{ padding:'8px 16px', borderRadius:99, border:'1.5px solid', borderColor:form.industry===ind?'#C8271D':'#e0e0e0', background:form.industry===ind?'#fff5f5':'#fafafa', fontSize:13, fontWeight:600, color:form.industry===ind?'#C8271D':'#666', cursor:'pointer', fontFamily:'inherit', transition:'all 200ms' }}>{ind}</button>
                      ))}
                    </div>
                  </Field>

                  <Field {...fp} id="message" label="문의 내용">
                    <textarea placeholder="도입을 고려하시는 배경, 설치 공간, 기타 요청사항을 자유롭게 작성해주세요."
                      value={form.message}
                      onChange={e=>setForm(p=>({...p, message:e.target.value}))}
                      style={{ width:'100%', padding:'13px 16px', border:'1.5px solid #e0e0e0', borderRadius:8, fontSize:14, fontFamily:'inherit', fontWeight:500, color:'#1a1a1a', outline:'none', resize:'vertical', minHeight:120, letterSpacing:'-0.01em' }}
                      onFocus={e=>e.target.style.borderColor='#1a1a1a'}
                      onBlur={e=>e.target.style.borderColor='#e0e0e0'}
                    />
                  </Field>

                  {/* Agree */}
                  <label onClick={()=>setForm(p=>({...p, agree:!p.agree}))} style={{ display:'flex', alignItems:'flex-start', gap:12, cursor:'pointer', marginBottom:8 }}>
                    <div style={{ width:22, height:22, borderRadius:6, border:'2px solid', borderColor:form.agree?'#C8271D':'#d0d0d0', background:form.agree?'#C8271D':'#fff', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, marginTop:1, transition:'all 200ms' }}>
                      {form.agree && <svg width="12" height="10" viewBox="0 0 12 10" fill="none"><path d="M1 5L4.5 8.5L11 1" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                    </div>
                    <span style={{ fontSize:14, color:'#555', fontWeight:500, lineHeight:1.5 }}>개인정보 수집 및 이용에 동의합니다. (수집 항목: 이름, 연락처, 이메일 / 목적: 문의 처리 / 보유 기간: 문의 처리 완료 후 즉시 삭제)</span>
                  </label>
                  {errors.agree && <div style={{ fontSize:12, color:'#C8271D', marginBottom:16, fontWeight:500 }}>{errors.agree}</div>}

                  {sendError && (
                    <div style={{ background:'#fff0f0', border:'1px solid #ffd5d3', borderRadius:8, padding:'12px 16px', fontSize:13, color:'#C8271D', fontWeight:600, marginBottom:12 }}>{sendError}</div>
                  )}

                  <button type="submit" disabled={sending} style={{ width:'100%', background: sending ? '#aaa' : '#C8271D', color:'#fff', border:'none', borderRadius:12, padding:'18px', fontSize:16, fontWeight:700, cursor: sending ? 'not-allowed' : 'pointer', fontFamily:'inherit', marginTop:8, boxShadow:'0 4px 20px rgba(200,39,29,0.2)', transition:'all 200ms', letterSpacing:'-0.01em' }}
                    onMouseEnter={e=>{ if(!sending){ e.currentTarget.style.background='#a81f17'; e.currentTarget.style.transform='translateY(-1px)'; }}}
                    onMouseLeave={e=>{ if(!sending){ e.currentTarget.style.background='#C8271D'; e.currentTarget.style.transform=''; }}}
                  >{sending ? '전송 중...' : '문의 제출하기 →'}</button>
                </form>
              )}
            </div>

            {/* Side info */}
            <div>
              <div style={{ background:'#fafafa', borderRadius:16, padding:'32px', border:'1px solid #f0f0f0', marginBottom:24 }}>
                <h4 style={{ fontSize:16, fontWeight:800, color:'#1a1a1a', marginBottom:20, letterSpacing:'-0.02em' }}>안심 문구</h4>
                {[['견적은 무료입니다.'],['수집된 정보는 문의 처리 목적으로만 사용됩니다.'],['부담 없이 문의하세요. ']].map(([t],i) => (
                  <div key={i} style={{ display:'flex', gap:12, marginBottom:16 }}>
                    <span style={{ width:20, height:20, borderRadius:'50%', background:'#fff0f0', border:'1px solid #ffd5d3', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, marginTop:1 }}>
                      <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4L3.5 6.5L9 1" stroke="#C8271D" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </span>
                    <span style={{ fontSize:14, color:'#555', fontWeight:500, lineHeight:1.5 }}>{t}</span>
                  </div>
                ))}
              </div>

             
            </div>
          </div>

      </div>
    </div>
  );
}

Object.assign(window, { ContactPage });
