// FORM + FOOTER

const MAIL_TO = 'impact.value.japan@gmail.com';

function KBForm() {
  const K = window.KB;
  const { Sparkle, ArrowRight, Line, Check } = window.KBIcon;
  const [step, setStep] = React.useState(1);
  const [cats, setCats] = React.useState([]);
  const [tel, setTel] = React.useState('');
  const [name, setName] = React.useState('');
  const [detail, setDetail] = React.useState('');
  const [agreed, setAgreed] = React.useState(false);
  const [submitError, setSubmitError] = React.useState('');
  const [isSubmitting, setIsSubmitting] = React.useState(false);

  const CATS = ['ロレックス','高級時計','金・貴金属','宝飾品','ブランドバッグ','カメラ','テレカ','古銭','着物','洋酒','骨董品','その他'];

  const toggleCat = (c) => {
    setCats(prev => prev.includes(c) ? prev.filter(x => x !== c) : [...prev, c]);
  };

  const submit = async (e) => {
    e.preventDefault();
    setSubmitError('');
    setIsSubmitting(true);
    try {
      const response = await fetch('/api/inquiries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          phone: tel,
          category: cats.join('、') || 'その他',
          message: detail || '（特記なし）',
        }),
      });
      if (!response.ok) {
        const data = await response.json().catch(() => null);
        setSubmitError(data?.error || '送信に失敗しました。時間をおいて再度お試しください。');
        return;
      }
      window.location.href = '/inquiry-complete';
    } catch {
      setSubmitError('送信に失敗しました。通信環境をご確認ください。');
    } finally {
      setIsSubmitting(false);
    }
  };

  const stepLabels = ['品目', '電話番号', 'お名前'];

  return (
    <section id="form" style={{
      background: K.bone, color: K.charcoal,
      padding: '56px 24px 64px', position: 'relative',
    }}>
      <div style={{
        position: 'absolute', top: 0, left: 0, right: 0, height: 8,
        background: `linear-gradient(90deg, ${K.gold} 0%, ${K.goldLight} 50%, ${K.gold} 100%)`,
      }} />

      <div style={{ textAlign: 'center' }}>
        <div style={{
          fontFamily: K.fontMono, fontSize: 9.5,
          letterSpacing: '0.3em', color: K.goldDeep,
        }}>— FREE APPRAISAL —</div>
        <h2 style={{
          margin: '10px 0 0',
          fontFamily: K.fontSerif, fontWeight: 700, fontSize: 28,
          color: K.charcoal, letterSpacing: '0.04em',
        }}>無料査定、承ります。</h2>
        <div style={{
          marginTop: 10, fontFamily: K.fontSans, fontSize: 12.5,
          color: 'rgba(26,26,26,0.6)', lineHeight: 1.7,
        }}>30秒でかんたん入力。まずはお気軽にご相談ください。</div>
      </div>

      <div style={{
        marginTop: 28,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {stepLabels.map((label, i) => {
          const n = i + 1;
          const active = step === n;
          const done = step > n;
          return (
            <React.Fragment key={n}>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                <div style={{
                  width: 28, height: 28, borderRadius: '50%',
                  background: done ? K.gold : active ? K.navy900 : 'transparent',
                  border: `2px solid ${done || active ? K.gold : 'rgba(26,26,26,0.18)'}`,
                  color: done ? K.navy900 : active ? K.goldLight : 'rgba(26,26,26,0.35)',
                  display: 'grid', placeItems: 'center',
                  fontFamily: K.fontMono, fontSize: 12, fontWeight: 700,
                }}>
                  {done ? <Check size={12} color={K.navy900} /> : n}
                </div>
                <div style={{
                  fontFamily: K.fontSans, fontSize: 9.5,
                  color: active ? K.charcoal : done ? K.goldDeep : 'rgba(26,26,26,0.35)',
                  fontWeight: active ? 700 : 400,
                }}>{label}</div>
              </div>
              {i < stepLabels.length - 1 && (
                <div style={{
                  width: 36, height: 1, marginBottom: 16,
                  background: step > n ? K.gold : 'rgba(26,26,26,0.15)',
                }} />
              )}
            </React.Fragment>
          );
        })}
      </div>

      {step === 1 && (
        <div style={{ marginTop: 24 }}>
          <FormLabel>
            お品物カテゴリ
            <span style={{
              marginLeft: 6, padding: '2px 7px',
              background: 'rgba(201,169,97,0.15)', color: K.goldDeep,
              fontFamily: K.fontMono, fontSize: 8.5, fontWeight: 700, letterSpacing: '0.08em',
              border: `1px solid ${K.gold}40`,
            }}>複数選択可</span>
          </FormLabel>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 10 }}>
            {CATS.map(c => {
              const on = cats.includes(c);
              return (
                <button type="button" key={c} onClick={() => toggleCat(c)} style={{
                  padding: '10px 14px', border: 'none',
                  background: on ? K.navy900 : '#fff',
                  color: on ? K.goldLight : K.charcoal,
                  fontFamily: K.fontSans, fontSize: 12, fontWeight: on ? 700 : 500,
                  letterSpacing: '0.04em', borderRadius: 2,
                  boxShadow: on ? 'none' : 'inset 0 0 0 1px rgba(26,26,26,0.12)',
                  cursor: 'pointer',
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                }}>
                  {on && <Check size={11} color={K.goldLight} />}
                  {c}
                </button>
              );
            })}
          </div>
          <button type="button" onClick={() => setStep(2)} style={{
            marginTop: 24, width: '100%', height: 56,
            border: 'none', borderRadius: 4,
            background: `linear-gradient(180deg, ${K.navy700} 0%, ${K.navy900} 100%)`,
            color: K.goldLight,
            fontFamily: K.fontSans, fontWeight: 900, fontSize: 15,
            letterSpacing: '0.1em',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            cursor: 'pointer', boxShadow: '0 10px 24px rgba(10,22,40,0.2)',
          }}>
            次へ — 電話番号を入力
            <ArrowRight size={16} color={K.goldLight} />
          </button>
        </div>
      )}

      {step === 2 && (
        <form onSubmit={e => { e.preventDefault(); if (tel.replace(/[^0-9]/g,'').length < 7) return; setStep(3); }} style={{ marginTop: 24 }}>
          <FormLabel required htmlFor="kb-tel">お電話番号</FormLabel>
          <input
            id="kb-tel" type="tel" autoComplete="tel"
            value={tel} onChange={e => setTel(e.target.value)}
            required placeholder="090-0000-0000" inputMode="tel"
            style={inputStyle(K)}
          />
          <div style={{
            marginTop: 10, fontFamily: K.fontSans, fontSize: 11.5,
            color: 'rgba(26,26,26,0.5)', lineHeight: 1.7,
          }}>折り返しご連絡いたします。受付: 月〜金 10:00-18:00</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 10, marginTop: 20 }}>
            <button type="button" onClick={() => setStep(1)} style={{
              height: 52, border: '1px solid rgba(26,26,26,0.18)', borderRadius: 4,
              background: '#fff', color: K.charcoal,
              fontFamily: K.fontSans, fontWeight: 700, fontSize: 13, cursor: 'pointer',
            }}>戻る</button>
            <button type="submit" style={{
              height: 52, border: 'none', borderRadius: 4,
              background: `linear-gradient(180deg, ${K.navy700} 0%, ${K.navy900} 100%)`,
              color: K.goldLight,
              fontFamily: K.fontSans, fontWeight: 900, fontSize: 15,
              letterSpacing: '0.1em',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              cursor: 'pointer', boxShadow: '0 10px 24px rgba(10,22,40,0.2)',
            }}>
              次へ — お名前を入力
              <ArrowRight size={16} color={K.goldLight} />
            </button>
          </div>
        </form>
      )}

      {step === 3 && (
        <form onSubmit={submit} style={{ marginTop: 24 }}>
          <FormLabel required htmlFor="kb-name">お名前</FormLabel>
          <input
            id="kb-name" type="text" autoComplete="name"
            value={name} onChange={e => setName(e.target.value)}
            required placeholder="山田 太郎"
            style={inputStyle(K)}
          />
          <div style={{ marginTop: 16 }}>
            <FormLabel htmlFor="kb-detail">お品物について（任意）</FormLabel>
            <textarea id="kb-detail" value={detail} onChange={e => setDetail(e.target.value)}
              placeholder="メーカー・型番・ご購入時期など、わかる範囲でご記入ください。"
              rows={3} style={{ ...inputStyle(K), padding: '14px 14px', height: 'auto', resize: 'none', fontFamily: K.fontSans }}
            />
          </div>
          <label style={{
            marginTop: 18, display: 'flex', alignItems: 'flex-start', gap: 10,
            padding: '14px 14px', cursor: 'pointer',
            background: 'rgba(201,169,97,0.08)',
            border: `1px solid ${K.gold}50`,
          }}>
            <input
              type="checkbox" checked={agreed}
              onChange={e => setAgreed(e.target.checked)}
              style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }}
            />
            <div style={{
              flexShrink: 0, width: 18, height: 18, marginTop: 1,
              background: agreed ? K.navy900 : 'transparent',
              border: agreed ? 'none' : '2px solid rgba(26,26,26,0.45)',
              display: 'grid', placeItems: 'center',
            }}>
              {agreed && <Check size={12} color={K.goldLight} />}
            </div>
            <div style={{
              fontFamily: K.fontSans, fontSize: 11.5, lineHeight: 1.7,
              color: 'rgba(26,26,26,0.72)',
            }}>
              <a href="/legal/privacy" target="_blank" rel="noopener noreferrer" style={{ color: K.goldLight, textDecoration: 'underline' }}>プライバシーポリシー</a>に同意します。入力情報は査定の目的以外には使用しません。
            </div>
          </label>
          {submitError && (
            <div role="alert" style={{
              marginTop: 12, textAlign: 'center',
              fontFamily: K.fontSans, fontSize: 12.5, fontWeight: 700,
              color: '#9b1c1c', lineHeight: 1.6,
            }}>{submitError}</div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 10, marginTop: 20 }}>
            <button type="button" onClick={() => setStep(2)} style={{
              height: 60, border: '1px solid rgba(26,26,26,0.18)', borderRadius: 4,
              background: '#fff', color: K.charcoal,
              fontFamily: K.fontSans, fontWeight: 700, fontSize: 13, cursor: 'pointer',
            }}>戻る</button>
            <button type="submit" disabled={!agreed || isSubmitting} style={{
              height: 60, border: 'none', borderRadius: 4,
              background: `linear-gradient(180deg, ${K.navy700} 0%, ${K.navy900} 100%)`,
              color: K.goldLight,
              fontFamily: K.fontSans, fontWeight: 900, fontSize: 15,
              letterSpacing: '0.14em',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
              boxShadow: (agreed && !isSubmitting) ? '0 20px 40px rgba(10,22,40,0.3)' : 'none',
              cursor: (agreed && !isSubmitting) ? 'pointer' : 'not-allowed',
              opacity: (agreed && !isSubmitting) ? 1 : 0.45,
            }}>
              <Sparkle size={14} color={K.goldLight} />
              {isSubmitting ? '送信中...' : '無料査定を依頼する'}
              <ArrowRight size={16} color={K.goldLight} />
            </button>
          </div>
          <div style={{
            marginTop: 10, textAlign: 'center',
            fontFamily: K.fontMono, fontSize: 9.5,
            color: 'rgba(26,26,26,0.5)', letterSpacing: '0.18em',
          }}>送信先 · {MAIL_TO}</div>
        </form>
      )}

      <div style={{
        marginTop: 22, display: 'flex', alignItems: 'center', gap: 10,
        fontFamily: K.fontMono, fontSize: 9.5, color: 'rgba(26,26,26,0.4)',
        letterSpacing: '0.25em',
      }}>
        <div style={{ flex: 1, height: 1, background: 'rgba(26,26,26,0.12)' }} />
        OR
        <div style={{ flex: 1, height: 1, background: 'rgba(26,26,26,0.12)' }} />
      </div>

      <a href="https://line.me/ti/p/xWmu96gEhw" target="_blank" rel="noopener noreferrer" style={{
        marginTop: 16, width: '100%', height: 52,
        border: 'none', borderRadius: 4,
        background: '#06C755', color: '#fff',
        fontFamily: K.fontSans, fontWeight: 800, fontSize: 14,
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        textDecoration: 'none',
      }}>
        <Line size={18} color="#fff" /> LINEで査定する
      </a>
    </section>
  );
}

function FormLabel({ children, required, htmlFor }) {
  const K = window.KB;
  return (
    <label htmlFor={htmlFor} style={{
      display: 'flex', alignItems: 'center', gap: 8,
      fontFamily: K.fontSans, fontSize: 12, fontWeight: 700,
      color: K.charcoal, letterSpacing: '0.04em',
    }}>
      {children}
      {required && <span style={{
        padding: '2px 6px',
        background: K.gold, color: K.navy900,
        fontFamily: K.fontMono, fontSize: 8, fontWeight: 700, letterSpacing: '0.1em',
      }}>必須</span>}
    </label>
  );
}

function inputStyle(K) {
  return {
    width: '100%',
    height: 52, padding: '0 14px',
    marginTop: 10,
    background: '#fff',
    border: '1px solid rgba(26,26,26,0.12)',
    borderRadius: 2,
    fontFamily: K.fontSans, fontSize: 14,
    color: K.charcoal,
    outline: 'none',
    boxSizing: 'border-box',
  };
}

function KBFooter() {
  const K = window.KB;
  const { Pin, Clock, Phone } = window.KBIcon;
  return (
    <footer style={{
      background: K.navy900,
      padding: '48px 24px 120px',
      color: K.inkDim,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <KBLogo />
      </div>

      <div style={{
        marginTop: 28, display: 'flex', flexDirection: 'column', gap: 14,
      }}>
        <InfoRow icon={Pin} label="本社所在地" value="〒544-0002 大阪府大阪市生野区小路一丁目9番20号 N-04" />
        <InfoRow icon={Phone} label="電話番号" value="06-4400-8382" href="tel:0644008382" />
        <InfoRow icon={Clock} label="LINE査定・申込受付" value="24時間受付（平日対応）" />
        <InfoRow icon={Clock} label="電話受付" value="月〜金 10:00 — 18:00（土日休業）" />
      </div>

      <div style={{
        marginTop: 32, padding: '20px 18px',
        border: `1px solid ${K.gold}30`,
      }}>
        <div style={{
          fontFamily: K.fontMono, fontSize: 9,
          letterSpacing: '0.25em', color: K.goldLight,
        }}>LICENSE</div>
        <div style={{
          marginTop: 6,
          fontFamily: K.fontSerif, fontWeight: 600, fontSize: 13,
          color: K.ink, letterSpacing: '0.04em', lineHeight: 1.7,
        }}>
          大阪府公安委員会許可<br/>
          <span style={{ fontFamily: K.fontMono, fontSize: 14, color: K.goldLight }}>第 621118R072427 号</span>
        </div>
        <div style={{
          marginTop: 10,
          fontFamily: K.fontSans, fontSize: 10.5, color: K.inkMute, lineHeight: 1.7,
        }}>
          時計・宝飾品商として、法令遵守のもと営業しております。
        </div>
      </div>

      <div style={{
        marginTop: 28, paddingTop: 20,
        borderTop: `1px solid rgba(201,169,97,0.15)`,
        textAlign: 'center',
      }}>
        <div style={{
          fontFamily: K.fontSerif, fontWeight: 700, fontSize: 13,
          color: K.ink, letterSpacing: '0.08em',
        }}>株式会社 IMPACT</div>
        <div style={{
          marginTop: 6,
          fontFamily: K.fontMono, fontSize: 9,
          color: K.inkMute, letterSpacing: '0.2em',
        }}>© 2026 IMPACT CO.,LTD · ALL RIGHTS RESERVED</div>
        <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center', gap: 16 }}>
          <a href="/legal/tokusho" target="_blank" rel="noopener noreferrer" style={{ fontFamily: K.fontSans, fontSize: 12, color: 'rgba(201,169,97,0.6)', textDecoration: 'none', padding: '8px 0', display: 'inline-block' }}>特定商取引法に基づく表示</a>
          <span style={{ color: 'rgba(201,169,97,0.3)', fontSize: 10 }}>|</span>
          <a href="/legal/privacy" target="_blank" rel="noopener noreferrer" style={{ fontFamily: K.fontSans, fontSize: 12, color: 'rgba(201,169,97,0.6)', textDecoration: 'none', padding: '8px 0', display: 'inline-block' }}>プライバシーポリシー</a>
          <span style={{ color: 'rgba(201,169,97,0.3)', fontSize: 10 }}>|</span>
          <a href="/legacy/recruit.html" style={{ fontFamily: K.fontSans, fontSize: 12, color: 'rgba(201,169,97,0.6)', textDecoration: 'none', padding: '8px 0', display: 'inline-block' }}>採用情報</a>
        </div>
      </div>
    </footer>
  );
}

function InfoRow({ icon: Icon, label, value, href }) {
  const K = window.KB;
  const valStyle = {
    marginTop: 3,
    fontFamily: K.fontSans, fontSize: 12.5, fontWeight: 500,
    color: K.ink, lineHeight: 1.6, textDecoration: 'none',
  };
  return (
    <div style={{ display: 'flex', gap: 12 }}>
      <div style={{
        flexShrink: 0, width: 32, height: 32,
        display: 'grid', placeItems: 'center',
        background: 'rgba(201,169,97,0.08)',
        border: `1px solid ${K.gold}30`,
      }}>
        <Icon size={14} color={K.gold} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: K.fontMono, fontSize: 9,
          letterSpacing: '0.22em', color: K.inkMute,
        }}>{label}</div>
        {href
          ? <a href={href} style={valStyle}>{value}</a>
          : <div style={valStyle}>{value}</div>}
      </div>
    </div>
  );
}

Object.assign(window, { KBForm, KBFooter });
