// contact.jsx — お問い合わせフォーム（3ステップ: 入力→確認→完了）
// Web3Forms（https://web3forms.com）で実際にメール送信。
// WEB3FORMS_KEY に発行されたアクセスキーを設定してください。
// （無料・1000件/月）https://web3forms.com から取得

// ★ここにWeb3Formsのアクセスキーを入れてください★
const WEB3FORMS_KEY = 'YOUR_ACCESS_KEY_HERE';
// 送信先メールアドレス（Web3Formsアカウントに紐付いています）

const { useState: useStateC, useRef: useRefC } = React;

function Contact() {
  const [step, setStep] = useStateC('form'); // form | confirm | done
  const [form, setForm] = useStateC({
    type: '',
    company: '',
    name: '',
    kana: '',
    email: '',
    tel: '',
    message: '',
    agree: false,
  });
  const [errors, setErrors] = useStateC({});

  const update = (k, v) => {
    setForm((f) => ({ ...f, [k]: v }));
    setErrors((e) => ({ ...e, [k]: undefined }));
  };

  const validate = () => {
    const e = {};
    if (!form.type) e.type = 'お問い合わせ種別を選択してください';
    if (!form.name.trim()) e.name = 'お名前を入力してください';
    if (!form.email.trim()) e.email = 'メールアドレスを入力してください';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'メールアドレスの形式が正しくありません';
    if (form.tel && !/^[\d\-+()\s]{6,}$/.test(form.tel)) e.tel = '電話番号の形式が正しくありません';
    if (!form.message.trim()) e.message = 'お問い合わせ内容を入力してください';
    else if (form.message.trim().length < 10) e.message = '10文字以上で入力してください';
    if (!form.agree) e.agree = 'プライバシーポリシーへの同意が必要です';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const [sending, setSending] = useStateC(false);
  const [sendError, setSendError] = useStateC('');

  const onSubmit = (ev) => {
    ev.preventDefault();
    if (validate()) {
      setStep('confirm');
      window.scrollTo({ top: document.getElementById('contact').offsetTop - 60, behavior: 'smooth' });
    } else {
      const first = document.querySelector('[data-error="true"]');
      first?.focus?.();
    }
  };

  const onConfirm = async () => {
    setSending(true);
    setSendError('');
    try {
      const payload = {
        access_key: WEB3FORMS_KEY,
        subject: `【古窯グループ お問い合わせ】${form.type}`,
        from_name: form.name,
        reply_to: form.email,
        '種別': form.type,
        '会社名': form.company || '（なし）',
        'お名前': `${form.name}${form.kana ? ` (${form.kana})` : ''}`,
        'メール': form.email,
        '電話番号': form.tel || '（なし）',
        '内容': form.message,
      };
      const res = await fetch('https://api.web3forms.com/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      const data = await res.json();
      if (data.success) {
        setStep('done');
      } else {
        setSendError('送信に失敗しました。しばらく経ってから再度お試しください。');
      }
    } catch (err) {
      setSendError('ネットワークエラーが発生しました。接続を確認してください。');
    } finally {
      setSending(false);
    }
  };

  const types = [
    'ご宿泊・お料理のご相談',
    'ブライダル・KOYO Weddingについて',
    '法人・団体でのご利用',
    '取材・メディア',
    '採用について',
    'その他のお問い合わせ',
  ];

  return (
    <section id="contact" className="ct" data-screen-label="Contact">
      <style>{`
        .ct{padding:120px 0;background:var(--cream);border-top:1px solid var(--line-2)}
        .ct .wrap{display:grid;grid-template-columns:340px 1fr;gap:64px}
        @media(max-width:820px){.ct .wrap{grid-template-columns:1fr;gap:32px}}
        .ct h2{margin:14px 0 24px}
        .ct .aside p{font-size:14px;line-height:1.95;color:var(--mute)}
        .ct .channels{display:flex;flex-direction:column;gap:14px;margin-top:28px;
          border-top:1px solid var(--line-2);padding-top:24px}
        .ct .channels .c{display:grid;grid-template-columns:80px 1fr;gap:14px;padding:14px 0;border-bottom:1px solid var(--line-2)}
        .ct .channels .c:last-child{border-bottom:0}
        .ct .channels .lbl{font-family:var(--f-en);font-size:10.5px;letter-spacing:.2em;color:var(--accent)}
        .ct .channels .v{font-family:var(--f-serif);font-size:16px;color:var(--ink)}
        .ct .channels .s{font-size:12px;color:var(--mute);margin-top:2px}

        .ct .panel{background:#fff;border:1px solid var(--line-2);border-radius:8px;padding:40px 40px 36px;
          box-shadow:0 1px 0 rgba(255,255,255,.6) inset,0 8px 40px rgba(14,22,34,.04)}
        @media(max-width:640px){.ct .panel{padding:28px 22px}}
        .ct .steps{display:flex;align-items:center;gap:14px;margin-bottom:32px;
          font-family:var(--f-en);font-size:11px;letter-spacing:.18em;color:var(--mute)}
        .ct .steps .s{display:flex;align-items:center;gap:8px}
        .ct .steps .s .n{width:22px;height:22px;border-radius:50%;border:1px solid var(--line);display:grid;place-items:center;font-size:11px}
        .ct .steps .s.on .n{background:var(--ink);color:var(--cream);border-color:var(--ink)}
        .ct .steps .s.on{color:var(--ink)}
        .ct .steps .line{flex:1;height:1px;background:var(--line-2)}

        .ct .row{display:flex;flex-direction:column;gap:8px;margin-bottom:20px}
        .ct .row.two{display:grid;grid-template-columns:1fr 1fr;gap:16px}
        @media(max-width:540px){.ct .row.two{grid-template-columns:1fr}}
        .ct label{font-size:12.5px;color:var(--ink);letter-spacing:.02em;font-weight:500;display:flex;align-items:center;gap:8px}
        .ct label .req{font-size:10px;background:var(--accent);color:#fff;padding:2px 7px;border-radius:3px;letter-spacing:.1em;font-weight:600}
        .ct label .opt{font-size:10px;color:var(--mute);border:1px solid var(--line);padding:2px 7px;border-radius:3px;letter-spacing:.1em}
        .ct input[type=text],.ct input[type=email],.ct input[type=tel],.ct textarea,.ct select{
          width:100%;border:1px solid var(--line);background:var(--cream);
          padding:13px 14px;font:14px/1.5 var(--f-sans);color:var(--ink);
          border-radius:4px;transition:border-color .2s,background .2s;
        }
        .ct input:focus,.ct textarea:focus,.ct select:focus{outline:none;border-color:var(--ink);background:#fff;
          box-shadow:0 0 0 3px rgba(14,22,34,.05)}
        .ct textarea{min-height:160px;resize:vertical}
        .ct .types{display:grid;grid-template-columns:1fr 1fr;gap:8px}
        @media(max-width:540px){.ct .types{grid-template-columns:1fr}}
        .ct .types label{padding:14px 16px;border:1px solid var(--line);border-radius:4px;cursor:pointer;
          display:flex;gap:10px;align-items:center;background:var(--cream);transition:all .2s}
        .ct .types label:hover{border-color:var(--ink)}
        .ct .types label.is-on{border-color:var(--ink);background:#fff}
        .ct .types label .b{width:14px;height:14px;border-radius:50%;border:1px solid var(--line);display:grid;place-items:center;flex-shrink:0}
        .ct .types label.is-on .b{border-color:var(--ink)}
        .ct .types label.is-on .b::after{content:"";width:7px;height:7px;border-radius:50%;background:var(--ink)}
        .ct .types input{position:absolute;opacity:0;pointer-events:none}

        .ct .err{color:var(--accent);font-size:12px;margin-top:2px}
        .ct .agree{display:flex;align-items:flex-start;gap:10px;font-size:13px;color:var(--mute);
          padding:16px 18px;border:1px solid var(--line-2);background:var(--paper-2);border-radius:4px}
        .ct .agree a{color:var(--ink);text-decoration:underline}
        .ct .agree input{margin-top:4px}
        .ct .submit{display:flex;gap:12px;align-items:center;margin-top:28px}
        .ct .submit .help{font-size:12px;color:var(--mute)}

        .ct .conf{display:flex;flex-direction:column;gap:0;border-top:1px solid var(--line-2)}
        .ct .conf .r{display:grid;grid-template-columns:140px 1fr;gap:18px;padding:18px 0;border-bottom:1px solid var(--line-2)}
        @media(max-width:540px){.ct .conf .r{grid-template-columns:1fr;gap:4px}}
        .ct .conf .l{font-size:11.5px;letter-spacing:.18em;color:var(--mute);font-family:var(--f-en);text-transform:uppercase}
        .ct .conf .v{font-size:14px;color:var(--ink);white-space:pre-wrap;line-height:1.85}

        .ct .done{text-align:center;padding:36px 0}
        .ct .done .ic{width:64px;height:64px;border-radius:50%;border:1px solid var(--ink);
          display:grid;place-items:center;margin:0 auto 24px}
        .ct .done h3{font-family:var(--f-serif);font-size:28px;font-weight:500;margin:0 0 12px}
        .ct .done p{color:var(--mute);font-size:14px;max-width:36ch;margin:0 auto}
      `}</style>
      <div className="wrap">
        <div className="aside">
          <div className="sec-title" style={{marginBottom:24}}>
            <span className="en">Contact</span>
            <span className="jp">お問い合わせ</span>
          </div>
          <p style={{fontSize:14,lineHeight:2,color:'var(--mute)'}}>古窯グループへのご相談・ご質問は、こちらのフォームよりお気軽にお寄せください。営業日2日以内に、担当よりご連絡いたします。<br /><br />※ ご宿泊の予約は、各施設の予約ページから直接お申し込みください。</p>
          <div className="channels">
            <div className="c">
              <span className="lbl">TEL</span>
              <div>
                <div className="v">023-672-5454</div>
                <div className="s">平日 9:00 — 17:30</div>
              </div>
            </div>
            <div className="c">
              <span className="lbl">EMAIL</span>
              <div>
                <div className="v">info@koyo-gr.com</div>
                <div className="s">24時間受付・営業日内に返信</div>
              </div>
            </div>
            <div className="c">
              <span className="lbl">ADDRESS</span>
              <div>
                <div className="v">山形県上山市葉山 5-20</div>
                <div className="s">〒999-3292 ／ 日本の宿 古窯 内</div>
              </div>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="steps" aria-hidden="true">
            <div className={`s ${step==='form'?'on':''}`}><span className="n">1</span> ENTER</div>
            <div className="line"></div>
            <div className={`s ${step==='confirm'?'on':''}`}><span className="n">2</span> CONFIRM</div>
            <div className="line"></div>
            <div className={`s ${step==='done'?'on':''}`}><span className="n">3</span> SENT</div>
          </div>

          {step === 'form' && (
            <form noValidate onSubmit={onSubmit}>
              <div className="row">
                <label>お問い合わせ種別 <span className="req">必須</span></label>
                <div className="types" role="radiogroup" data-error={!!errors.type}>
                  {types.map((t) => (
                    <label key={t} className={form.type===t?'is-on':''}>
                      <input type="radio" name="type" value={t} checked={form.type===t} onChange={() => update('type', t)} />
                      <span className="b"></span>
                      <span>{t}</span>
                    </label>
                  ))}
                </div>
                {errors.type && <div className="err">{errors.type}</div>}
              </div>

              <div className="row two">
                <div>
                  <label>会社名・団体名 <span className="opt">任意</span></label>
                  <input type="text" autoComplete="organization" value={form.company} onChange={(e)=>update('company',e.target.value)} />
                </div>
                <div>
                  <label htmlFor="ct-name">お名前 <span className="req">必須</span></label>
                  <input id="ct-name" type="text" autoComplete="name" data-error={!!errors.name} value={form.name} onChange={(e)=>update('name',e.target.value)} />
                  {errors.name && <div className="err">{errors.name}</div>}
                </div>
              </div>

              <div className="row two">
                <div>
                  <label>フリガナ <span className="opt">任意</span></label>
                  <input type="text" value={form.kana} onChange={(e)=>update('kana',e.target.value)} />
                </div>
                <div>
                  <label htmlFor="ct-tel">電話番号 <span className="opt">任意</span></label>
                  <input id="ct-tel" type="tel" autoComplete="tel" data-error={!!errors.tel} value={form.tel} onChange={(e)=>update('tel',e.target.value)} placeholder="03-1234-5678" />
                  {errors.tel && <div className="err">{errors.tel}</div>}
                </div>
              </div>

              <div className="row">
                <label htmlFor="ct-email">メールアドレス <span className="req">必須</span></label>
                <input id="ct-email" type="email" autoComplete="email" data-error={!!errors.email} value={form.email} onChange={(e)=>update('email',e.target.value)} placeholder="name@example.com" />
                {errors.email && <div className="err">{errors.email}</div>}
              </div>

              <div className="row">
                <label htmlFor="ct-msg">お問い合わせ内容 <span className="req">必須</span></label>
                <textarea id="ct-msg" data-error={!!errors.message} value={form.message} onChange={(e)=>update('message',e.target.value)} placeholder="ご相談内容、ご希望の納期、数量などをお書きください。" />
                {errors.message && <div className="err">{errors.message}</div>}
              </div>

              <label className="agree">
                <input type="checkbox" checked={form.agree} onChange={(e)=>update('agree',e.target.checked)} data-error={!!errors.agree} />
                <span>
                  <a href="#privacy">プライバシーポリシー</a>に同意します。お預かりした個人情報は、お問い合わせへのご回答およびそれに付随する業務にのみ使用します。
                </span>
              </label>
              {errors.agree && <div className="err" style={{marginTop:8}}>{errors.agree}</div>}

              <div className="submit">
                <button className="btn btn-fill" type="submit">入力内容を確認する <IconArrow /></button>
                <span className="help">* 必須項目を入力のうえ、確認画面へ進んでください。</span>
              </div>
            </form>
          )}

          {step === 'confirm' && (
            <div>
              <p style={{marginTop:0,marginBottom:24,color:'var(--mute)',fontSize:14}}>
                内容をご確認のうえ、「送信する」ボタンを押してください。
              </p>
              <div className="conf">
                <div className="r"><div className="l">Type</div><div className="v">{form.type}</div></div>
                <div className="r"><div className="l">Company</div><div className="v">{form.company || '—'}</div></div>
                <div className="r"><div className="l">Name</div><div className="v">{form.name} {form.kana ? `（${form.kana}）` : ''}</div></div>
                <div className="r"><div className="l">Email</div><div className="v">{form.email}</div></div>
                <div className="r"><div className="l">Tel</div><div className="v">{form.tel || '—'}</div></div>
                <div className="r"><div className="l">Message</div><div className="v">{form.message}</div></div>
              </div>
              <div className="submit">
                <button className="btn btn-fill" type="button" onClick={onConfirm} disabled={sending}
                  style={sending ? {opacity:.65, cursor:'not-allowed'} : {}}>
                  {sending ? '送信中...' : '送信する'} {!sending && <IconArrow />}
                </button>
                <button className="btn" type="button" onClick={() => setStep('form')} disabled={sending}>修正する</button>
              </div>
              {sendError && <div className="err" style={{marginTop:16, fontSize:13}}>{sendError}</div>}
            </div>
          )}

          {step === 'done' && (
            <div className="done">
              <div className="ic">
                <svg width="20" height="14" viewBox="0 0 20 14" aria-hidden="true"><path d="M1 7 L7 13 L19 1" stroke="currentColor" strokeWidth="1.2" fill="none" /></svg>
              </div>
              <h3>送信ありがとうございました。</h3>
              <p>担当者より、営業日2日以内にご連絡いたします。確認のため、ご記入のメールアドレス宛にも自動返信メールをお送りしました。</p>
              <div className="submit" style={{justifyContent:'center',marginTop:28}}>
                <a className="btn" href="#top">トップに戻る</a>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Contact });
