// page-recruit.jsx — 団員募集・お問い合わせ

(function() {
  // --- 問い合わせフォーム ---
  function ContactForm({ T, isM }) {
    const [form, setForm] = React.useState({
      name: '',
      kana: '',
      email: '',
      phone: '',
      subject: '見学希望',
      experience: 'はい',
      message: '',
      _hp: '',
    });
    const [errors, setErrors] = React.useState({});
    const [sent, setSent] = React.useState(false);
    const [submitting, setSubmitting] = React.useState(false);
    const [submitError, setSubmitError] = React.useState('');

    const update = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));

    const handleSubmit = async (e) => {
      e.preventDefault();
      const errs = {};
      if (!form.name.trim()) errs.name = 'お名前をご入力ください';
      if (!form.email.trim()) errs.email = 'メールアドレスをご入力ください';
      else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) errs.email = 'メールアドレスの形式が正しくありません';
      if (!form.message.trim()) errs.message = 'お問い合わせ内容をご入力ください';
      setErrors(errs);
      if (Object.keys(errs).length > 0) return;

      setSubmitting(true);
      setSubmitError('');
      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 || '送信に失敗しました');
        setSent(true);
      } catch (err) {
        setSubmitError(err.message || '送信に失敗しました。しばらくしてからもう一度お試しください。');
      } finally {
        setSubmitting(false);
      }
    };

    const inputStyle = (hasError) => ({
      width: '100%',
      padding: isM ? '12px 14px' : '14px 16px',
      fontSize: isM ? 15 : 16,
      fontFamily: T.fontSerif,
      background: '#fff',
      color: T.ink,
      border: `1px solid ${hasError ? T.wine : T.rule}`,
      borderRadius: 0,
      outline: 'none',
      transition: 'border-color .15s',
      boxSizing: 'border-box',
    });

    const labelStyle = {
      display: 'block',
      fontFamily: T.fontSerif,
      fontSize: isM ? 14 : 15,
      color: T.ink,
      marginBottom: 8,
      fontWeight: 500,
      letterSpacing: '.05em',
    };

    const requiredBadge = (
      <span style={{
        background: T.wine, color: '#fff',
        fontSize: 10, padding: '2px 6px',
        marginLeft: 8, letterSpacing: '.1em',
        verticalAlign: '2px',
        fontFamily: T.fontSans,
      }}>必須</span>
    );

    const errorMsg = (msg) => msg && (
      <div style={{
        fontSize: 12, color: T.wine, marginTop: 6,
        fontFamily: T.fontSerif,
      }}>※ {msg}</div>
    );

    if (sent) {
      return (
        <div style={{
          background: T.bgAlt,
          padding: isM ? '32px 24px' : '48px 40px',
          border: `1px solid ${T.gold}`,
          textAlign: 'center',
        }}>
          <div style={{
            fontFamily: T.fontSerifEn, fontStyle:'italic',
            fontSize: 13, letterSpacing: '.3em',
            color: T.gold, marginBottom: 12,
          }}>THANK YOU</div>
          <h3 style={{
            fontFamily: T.fontSerif, fontWeight: 500,
            fontSize: isM ? 20 : 24,
            color: T.wine, margin: '0 0 16px',
            letterSpacing: '.08em',
          }}>お問い合わせを受付いたしました</h3>
          <p style={{
            fontFamily: T.fontSerif,
            fontSize: isM ? 14 : 15,
            color: T.ink, lineHeight: 1.9, margin: 0,
          }}>
            ご記入いただいた内容を確認し、<br/>
            数日以内にご返信させていただきます。<br/>
            ご連絡ありがとうございました。
          </p>
          <button
            onClick={() => { setSent(false); setForm({ name:'', kana:'', email:'', phone:'', subject:'見学希望', experience:'はい', message:'' }); }}
            style={{
              marginTop: 24,
              background: 'transparent',
              border: `1px solid ${T.gold}`,
              color: T.wine,
              fontFamily: T.fontSerif,
              fontSize: 13,
              padding: '10px 24px',
              cursor: 'pointer',
              letterSpacing: '.15em',
            }}
          >フォームに戻る</button>
        </div>
      );
    }

    return (
      <form onSubmit={handleSubmit} style={{
        background: T.bg,
        border: `1px solid ${T.rule}`,
        padding: isM ? '28px 22px' : '44px 44px',
      }}>
        <div style={{
          display: 'grid',
          gridTemplateColumns: isM ? '1fr' : '1fr 1fr',
          gap: isM ? 18 : 22,
        }}>
          {/* 名前 */}
          <div>
            <label style={labelStyle}>お名前{requiredBadge}</label>
            <input type="text" value={form.name} onChange={update('name')}
              style={inputStyle(errors.name)} placeholder="例：山田 太郎"/>
            {errorMsg(errors.name)}
          </div>
          {/* ふりがな */}
          <div>
            <label style={labelStyle}>ふりがな</label>
            <input type="text" value={form.kana} onChange={update('kana')}
              style={inputStyle(false)} placeholder="例：やまだ たろう"/>
          </div>
          {/* email */}
          <div>
            <label style={labelStyle}>メールアドレス{requiredBadge}</label>
            <input type="email" value={form.email} onChange={update('email')}
              style={inputStyle(errors.email)} placeholder="例：sample@example.com"/>
            {errorMsg(errors.email)}
          </div>
          {/* phone */}
          <div>
            <label style={labelStyle}>電話番号</label>
            <input type="tel" value={form.phone} onChange={update('phone')}
              style={inputStyle(false)} placeholder="例：090-0000-0000"/>
          </div>
          {/* 件名 */}
          <div>
            <label style={labelStyle}>ご用件{requiredBadge}</label>
            <select value={form.subject} onChange={update('subject')}
              style={{...inputStyle(false), appearance:'none', backgroundImage:`linear-gradient(45deg, transparent 50%, ${T.gold} 50%), linear-gradient(135deg, ${T.gold} 50%, transparent 50%)`, backgroundPosition:`calc(100% - 18px) center, calc(100% - 12px) center`, backgroundSize:'6px 6px, 6px 6px', backgroundRepeat:'no-repeat'}}>
              <option>見学希望</option>
              <option>入団希望</option>
              <option>演奏会について</option>
              <option>その他</option>
            </select>
          </div>
          {/* 合唱経験 */}
          <div>
            <label style={labelStyle}>合唱経験</label>
            <div style={{display:'flex', gap:14, paddingTop: isM ? 4 : 12}}>
              {['はい', 'いいえ', '少しあり'].map(opt => (
                <label key={opt} style={{
                  display:'inline-flex', alignItems:'center', gap:6,
                  fontFamily: T.fontSerif, fontSize: isM ? 14 : 15,
                  cursor:'pointer', color: T.ink,
                }}>
                  <input
                    type="radio"
                    name="exp"
                    value={opt}
                    checked={form.experience === opt}
                    onChange={update('experience')}
                    style={{accentColor: T.wine}}
                  />
                  {opt}
                </label>
              ))}
            </div>
          </div>
        </div>

        {/* メッセージ */}
        <div style={{marginTop: isM ? 18 : 22}}>
          <label style={labelStyle}>お問い合わせ内容{requiredBadge}</label>
          <textarea value={form.message} onChange={update('message')}
            rows={isM ? 5 : 6}
            style={{...inputStyle(errors.message), resize:'vertical', minHeight: isM ? 120 : 150, lineHeight:1.7}}
            placeholder="ご質問やご見学希望日などをご記入ください"/>
          {errorMsg(errors.message)}
        </div>

        {/* Honeypot — ボットが埋めたら送信を拒否（人間には見えない） */}
        <div style={{position:'absolute', left:'-9999px', opacity:0, height:0, overflow:'hidden'}} aria-hidden="true">
          <input
            type="text"
            name="website"
            value={form._hp}
            onChange={update('_hp')}
            tabIndex={-1}
            autoComplete="off"
          />
        </div>

        {/* Privacy note */}
        <p style={{
          fontFamily: T.fontSerif, fontSize: 12,
          color: T.inkSoft, marginTop: 20, lineHeight: 1.7,
        }}>
          ※ ご入力いただいた個人情報は、お問い合わせへの返信にのみ使用し、第三者に提供することはありません。
        </p>

        {/* エラーメッセージ */}
        {submitError && (
          <div style={{
            marginTop: 16, padding: '12px 16px',
            background: '#fef2f2', border: `1px solid ${T.wine}`,
            fontFamily: T.fontSerif, fontSize: 13,
            color: T.wine, lineHeight: 1.7,
          }}>
            {submitError}
          </div>
        )}

        {/* Submit */}
        <div style={{textAlign:'center', marginTop: isM ? 28 : 32}}>
          <button type="submit" disabled={submitting} style={{
            display:'inline-block',
            padding: isM ? '14px 40px' : '16px 56px',
            background: submitting ? '#a0837c' : T.wine,
            color: '#fff',
            border: `1px solid ${submitting ? '#a0837c' : T.wine}`,
            cursor: submitting ? 'not-allowed' : 'pointer',
            fontFamily: T.fontSerif,
            fontSize: isM ? 15 : 16,
            letterSpacing: '.2em',
            position: 'relative',
            transition: 'background .2s',
          }}>
            <span style={{position:'absolute', inset:4, border:`1px solid rgba(255,255,255,.3)`, pointerEvents:'none'}}/>
            {submitting ? '送信中...' : '送　信'}
          </button>
        </div>
      </form>
    );
  }

  window.PageRecruit = function PageRecruit({ mobile, onNav }) {
    const T = window.A_TOKENS;
    const isM = mobile;

    return (
      <>
        <window.APageTitle en="JOIN US" jp="団員募集・お問い合わせ" mobile={isM}/>

        {/* Hero photo — choir group portrait */}
        <section style={{
          position: 'relative',
          background: T.bgAlt,
          overflow: 'hidden',
        }}>
          <img
            src="assets/recruit-group2025.jpg"
            alt="混声合唱団ハーモニーゆう 集合写真"
            style={{
              display: 'block',
              width: isM ? '100%' : '80%',
              margin: '0 auto',
            }}
          />
        </section>

        {/* Lead & Info */}
        <section style={{padding: isM ? '50px 24px' : '80px 60px'}}>
          <div style={{maxWidth:780, margin:'0 auto'}}>
            <p style={{
              fontFamily: T.fontSerif,
              fontSize: isM ? 18 : 22,
              color: T.wine,
              fontWeight:500,
              letterSpacing:'.05em',
              margin:'0 0 32px',
            }}>ハーモニーゆうは一緒に歌う仲間を募集しています。</p>

            <div style={{
              fontFamily: T.fontSerif,
              fontSize: isM ? 15 : 16,
              lineHeight:2,
              color: T.ink,
            }}>
              {/* 練習日 */}
              <div style={{marginBottom:6}}>
                <span style={{color: T.wine, fontWeight:600}}>◆練習日</span>
                {'　'}毎月第2、第4、第5水曜日
              </div>
              {/* 練習時間 */}
              <div style={{marginBottom:24}}>
                <span style={{color: T.wine, fontWeight:600}}>◆練習時間</span>
                {'　'}13時〜15時30分
              </div>

              {/* 現在練習中の曲目 */}
              <div style={{marginBottom:24}}>
                <div style={{color: T.wine, fontWeight:600, marginBottom:8}}>◆現在、練習中の主な曲目</div>
                <div style={{
                  border:`1px solid ${T.wine}`,
                  padding: isM ? '12px 16px' : '16px 20px',
                  fontFamily: T.fontSerif,
                  fontSize: isM ? 14 : 15,
                  lineHeight:2,
                  color: T.ink,
                  whiteSpace:'pre-line',
                }}>
                  {window.A_DATA_RECRUIT?.repertoire || ''}
                </div>
              </div>

              {/* 会費 */}
              <div style={{marginBottom:28}}>
                <div style={{color: T.wine, fontWeight:600, marginBottom:6}}>◆会費</div>
                <div style={{paddingLeft: isM ? 14 : 20}}>
                  <div>入会金　1,000円</div>
                  <div>団　費　2,000円/月（2ヶ月に1回集金しています）</div>
                </div>
              </div>

              {/* 締めの文 */}
              <div style={{color: T.inkSoft}}>
                <div>合唱経験は問いません。</div>
                <div>興味のある方は是非一度見学におこしください。</div>
              </div>
            </div>
          </div>
        </section>

        {/* Contact Form */}
        <section style={{
          background: T.bgAlt,
          padding: isM ? '50px 24px' : '80px 60px',
          borderTop: `1px solid ${T.rule}`,
        }}>
          <div style={{maxWidth: 880, margin:'0 auto'}}>
            <div style={{textAlign:'center', marginBottom: isM ? 32 : 48}}>
              <div style={{
                fontFamily: T.fontSerifEn, fontStyle:'italic',
                fontSize:13, letterSpacing:'.3em',
                color: T.gold, marginBottom:10,
              }}>CONTACT FORM</div>
              <h2 style={{
                fontFamily: T.fontSerif, fontWeight:500,
                fontSize: isM ? 24 : 32,
                margin:0, color: T.wine,
                letterSpacing:'.12em',
              }}>お問い合わせ</h2>
              <div style={{width:40, height:1, background: T.gold, margin:'22px auto 24px'}}/>
              <p style={{
                fontFamily: T.fontSerif,
                fontSize: isM ? 14 : 15,
                color: T.ink, lineHeight: 1.9, margin: 0,
              }}>
                下記フォームよりお気軽にお問い合わせください。
              </p>
            </div>

            <ContactForm T={T} isM={isM}/>
          </div>
        </section>

        {/* Related links */}
        <section style={{padding: isM ? '40px 24px 60px' : '70px 60px 100px'}}>
          <div style={{maxWidth:1000, margin:'0 auto'}}>
            <div style={{textAlign:'center', marginBottom: isM ? 24 : 36}}>
              <div style={{
                fontFamily: T.fontSerifEn, fontStyle:'italic',
                fontSize:13, letterSpacing:'.3em',
                color: T.gold,
              }}>RELATED</div>
              <h3 style={{
                fontFamily: T.fontSerif, fontWeight:500,
                fontSize: isM ? 20 : 24,
                margin:'8px 0 0', color: T.wine,
                letterSpacing:'.1em',
              }}>関連情報</h3>
            </div>
            <div style={{
              display:'grid',
              gridTemplateColumns: isM ? '1fr' : 'repeat(3, 1fr)',
              gap: isM ? 12 : 18,
            }}>
              {[
                { id:'venue',    label:'練習会場', sub:'神戸文化ホール' },
                { id:'schedule', label:'練習予定', sub:'今後の予定一覧' },
                { id:'concerts', label:'演奏会の記録', sub:'活動の様子' },
              ].map((l, i) => (
                <a key={i} href="#" onClick={(e) => { e.preventDefault(); onNav(l.id); }}
                  style={{
                    display:'block', textDecoration:'none',
                    padding: isM ? 20 : 24,
                    border:`1px solid ${T.rule}`,
                    background: T.bg,
                    transition:'all .15s',
                  }}
                  onMouseOver={(e) => { e.currentTarget.style.background = T.bgAlt; }}
                  onMouseOut={(e) => { e.currentTarget.style.background = T.bg; }}
                >
                  <div style={{
                    fontFamily: T.fontSerif, fontSize: isM ? 17 : 19,
                    fontWeight:500, color: T.wine, letterSpacing:'.05em',
                  }}>{l.label}　→</div>
                  <div style={{
                    fontFamily: T.fontSerif, fontSize: 13,
                    color: T.inkSoft, marginTop:6,
                  }}>{l.sub}</div>
                </a>
              ))}
            </div>
          </div>
        </section>
      </>
    );
  };
})();
