// Owner Onboarding — 5-step pet-owner registration flow.
// Reuses the shared register field helpers but with owner-side content.

const Field = window.RegField;
const inputCss = window.regInputCss;

function OwnerRegister({ initialStep = 0 }) {
  const [step, setStep] = React.useState(initialStep);
  const [form, setForm] = React.useState({
    pets: [
      { name: '', species: 'dog', breed: '', age: '', sex: '',
        weight: '', traits: [],
        allergies: '', meds: '',
        likes: '' },
    ],
    services: ['visit'],
    frequency: 'occasional',
    keyMethod: 'smart-lock',
    reportFreq: 'every-visit',
    emergency: '',
  });
  const set = (k,v) => setForm(f => ({...f, [k]:v}));
  const toggle = (k,v) => setForm(f => ({...f, [k]: f[k].includes(v) ? f[k].filter(x=>x!==v) : [...f[k],v]}));
  const updatePet = (i,patch) => setForm(f => ({...f, pets: f.pets.map((p,idx)=>idx===i?{...p,...patch}:p)}));
  const togglePetTrait = (i,trait) => setForm(f => ({...f, pets: f.pets.map((p,idx)=>idx===i?{...p, traits: p.traits.includes(trait)?p.traits.filter(t=>t!==trait):[...p.traits,trait]}:p)}));

  const steps = [
    ['ようこそ','01'],
    ['ペットの基本情報','02'],
    ['性格・健康','03'],
    ['希望のお世話','04'],
    ['お留守番の希望','05'],
  ];

  const next = () => setStep(s => Math.min(s+1, steps.length-1));
  const prev = () => setStep(s => Math.max(s-1, 0));

  // 送信状態
  const [submitState, setSubmitState] = React.useState({ phase:'idle', message:'' });
  const submit = async () => {
    setSubmitState({ phase:'loading', message:'送信中…' });
    const p = form.pets[0] || {};
    const data = {
      ownerName: form.ownerName || '',
      email: form.email || '',
      phone: form.phone || '',
      address: form.address || '',
      petName: p.name || '',
      petKind: p.species || '',
      petAge: p.age || '',
      petBreed: p.breed || '',
      petWeight: p.weight || '',
      petTemperament: (p.traits || []).join('・'),
      petHealth: [p.allergies && `アレルギー: ${p.allergies}`, p.meds && `投薬: ${p.meds}`].filter(Boolean).join(' / '),
      services: form.services || [],
      reportFreq: form.frequency || '',
      keyHandling: form.keyMethod || '',
      reportFreqDetail: form.reportFreq || '',
      emergency: form.emergency || '',
    };
    const res = await window.palpetSubmitRegistration({
      type: 'customer',
      data,
      photos: [
        ['petPhoto', p.photo],
      ],
    });
    if (res.ok) {
      setSubmitState({
        phase:'success',
        message: res.demo
          ? 'デモ送信が完了しました（実際の通知は走っていません）。次は「シッターを探す」へどうぞ。'
          : `登録完了。受付ID: ${res.row?.id || '—'}。コンシェルジュより1〜2営業日でご案内します。`,
        res,
      });
    } else {
      setSubmitState({
        phase:'error',
        message: res.message || res.error || '送信に失敗しました。',
        res,
      });
    }
  };

  return (
    <div data-page="owner-register" style={{width:'100%',minHeight:'100%',background:'var(--c-bg)',color:'#2E2418',fontFamily:'var(--font-jp)',display:'flex',flexDirection:'column'}}>
      <header style={{display:'flex',alignItems:'center',justifyContent:'space-between',padding:'20px 40px',background:'#fff',borderBottom:'1px solid rgba(0,0,0,.04)'}}>
        <img src="assets/logo-horizontal.png" alt="palpet" style={{height:48}}/>
        <div style={{fontSize:13,color:'#7a6a55'}}>はじめまして！ ペットの登録をお願いします</div>
        <div style={{fontSize:13}}>
          <a style={{color:'#9c8a72'}}>あとで設定する</a>
        </div>
      </header>

      <div style={{display:'grid',gridTemplateColumns:'280px 1fr 320px',flex:1,minHeight:0}}>
        {/* Stepper rail */}
        <aside style={{padding:'40px 24px',background:'#fff',borderRight:'1px solid rgba(0,0,0,.04)'}}>
          <div style={{fontSize:12,color:'#9c8a72',fontWeight:600,letterSpacing:'.04em',marginBottom:14}}>STEP {step+1} / {steps.length}</div>
          <div style={{display:'flex',flexDirection:'column',gap:4}}>
            {steps.map(([n,k],i)=>{
              const done = i < step, active = i === step;
              return (
                <button key={i} onClick={()=>setStep(i)} style={{
                  display:'flex',gap:14,alignItems:'center',padding:'12px 12px',
                  borderRadius:14,border:'none',cursor:'pointer',textAlign:'left',
                  background: active ? 'var(--c-primary-soft)' : 'transparent',
                  color: active ? 'var(--c-primary-deep)' : done ? '#7a6a55' : '#9c8a72',
                  fontWeight: active ? 700 : 500, fontFamily:'inherit',fontSize:14,
                }}>
                  <span style={{
                    width:28,height:28,borderRadius:'50%',
                    background: done ? 'var(--c-primary)' : active ? '#fff' : 'transparent',
                    border: active ? '1.5px solid var(--c-primary)' : '1.5px solid rgba(0,0,0,.08)',
                    color: done ? '#fff' : active ? 'var(--c-primary-deep)' : '#9c8a72',
                    display:'grid',placeItems:'center',fontSize:12,fontWeight:700,
                    fontFamily:'ui-monospace',flex:'0 0 auto',
                  }}>{done ? <Icons.Check size={14} stroke={2.4}/> : k}</span>
                  {n}
                </button>
              );
            })}
          </div>
          <div style={{marginTop:32,padding:18,borderRadius:18,background:'var(--c-bg)',fontSize:13,lineHeight:1.7,color:'#5d4d3a'}}>
            <div style={{fontWeight:700,marginBottom:6,display:'flex',alignItems:'center',gap:6,color:'var(--c-primary-deep)'}}><Icons.Heart size={16}/> 1分で完了</div>
            登録後すぐに、シッターさんに依頼ができます。
          </div>
        </aside>

        {/* Main */}
        <main style={{padding:'40px 48px',overflowY:'auto'}}>
          <div style={{height:6,background:'rgba(0,0,0,.06)',borderRadius:999,marginBottom:32}}>
            <div style={{width:`${((step+1)/steps.length)*100}%`,height:'100%',background:'var(--c-primary)',borderRadius:999,transition:'.4s'}}/>
          </div>

          {step === 0 && <OwnerWelcome/>}
          {step === 1 && <OwnerPet form={form} updatePet={updatePet}/>}
          {step === 2 && <OwnerHealth form={form} updatePet={updatePet} togglePetTrait={togglePetTrait}/>}
          {step === 3 && <OwnerService form={form} set={set} toggle={toggle}/>}
          {step === 4 && <OwnerCare form={form} set={set}/>}

          {submitState.phase !== 'idle' && (() => {
            const SF = window.SubmitFeedback;
            return SF ? <SF state={submitState} onReset={()=>setSubmitState({phase:'idle',message:''})}/> : null;
          })()}

          <div style={{display:'flex',gap:12,marginTop:40,justifyContent:'space-between'}}>
            <button onClick={prev} disabled={step===0 || submitState.phase==='loading'} style={{
              background:'#fff',border:'1.5px solid rgba(0,0,0,.1)',
              padding:'14px 22px',borderRadius:14,fontSize:15,fontWeight:600,
              cursor:(step===0||submitState.phase==='loading')?'not-allowed':'pointer',
              opacity:(step===0||submitState.phase==='loading')?.4:1,
              fontFamily:'inherit',display:'inline-flex',gap:6,alignItems:'center',
            }}><Icons.ChevL size={16}/> 戻る</button>
            <button
              onClick={step === steps.length-1 ? submit : next}
              disabled={submitState.phase==='loading' || submitState.phase==='success'}
              style={{
                background: submitState.phase==='success' ? '#a8c98a' : 'var(--c-primary-deep)',
                color:'#fff',border:'none',
                padding:'14px 28px',borderRadius:14,fontSize:15,fontWeight:700,
                cursor:(submitState.phase==='loading'||submitState.phase==='success')?'not-allowed':'pointer',
                opacity: submitState.phase==='loading'?.7:1,
                fontFamily:'inherit',display:'inline-flex',gap:6,alignItems:'center',
              }}>
              {submitState.phase==='loading' ? '送信中…' :
               submitState.phase==='success' ? '送信完了 ✓' :
               step === steps.length-1 ? '登録して始める' : '次へ進む'} <Icons.ChevR size={16}/>
            </button>
          </div>
        </main>

        {/* Pet preview */}
        <aside style={{padding:'40px 24px',background:'#fff',borderLeft:'1px solid rgba(0,0,0,.04)',overflowY:'auto'}}>
          <div style={{fontSize:12,color:'#9c8a72',fontWeight:600,letterSpacing:'.04em',marginBottom:10}}>YOUR PET</div>
          <div style={{fontSize:13,color:'#7a6a55',marginBottom:18}}>このプロフィールがシッターさんに共有されます。</div>
          {form.pets.map((p,i)=> <PetPreviewCard key={i} pet={p}/>)}
        </aside>
      </div>
    </div>
  );
}

// ----- step bodies -----

function OwnerWelcome() {
  return (
    <div>
      <div style={{fontSize:13,color:'var(--c-primary-deep)',fontWeight:700,fontFamily:'ui-monospace',marginBottom:6}}>STEP 01</div>
      <h2 style={{fontSize:34,fontWeight:700,letterSpacing:'-.01em',lineHeight:1.3,marginBottom:14}}>
        はじめまして 🐾<br/>
        うちの子のこと、教えてください。
      </h2>
      <p style={{fontSize:15,color:'#5d4d3a',lineHeight:1.85,maxWidth:540}}>
        ペットの性格や好きなこと、お留守番のときに気をつけて欲しいこと。
        シッターさんがその子と向き合うために、ご家族の声を集めさせてください。
      </p>
      <div style={{
        marginTop:28,padding:24,borderRadius:24,background:'var(--c-primary-soft)',
        display:'flex',gap:20,alignItems:'center',
      }}>
        <div style={{
          width:80,height:80,borderRadius:20,background:'#fff',
          color:'var(--c-primary-deep)',display:'grid',placeItems:'center',flex:'0 0 auto',
        }}><PetGlyph.Paw size={44}/></div>
        <div>
          <div style={{fontSize:16,fontWeight:700,color:'var(--c-primary-deep)'}}>1分で登録、すぐ依頼できます</div>
          <div style={{fontSize:13,color:'#5d4d3a',marginTop:4,lineHeight:1.7}}>後からプロフィールはいつでも更新できます。複数のペットも登録OK。</div>
        </div>
      </div>
      <div style={{marginTop:24,display:'grid',gridTemplateColumns:'1fr 1fr',gap:14}}>
        <Field label="お名前">
          <input style={inputCss} placeholder="例：佐藤 ゆうこ"/>
        </Field>
        <Field label="ニックネーム（公開）">
          <input style={inputCss} placeholder="例：ゆーこ"/>
        </Field>
        <Field label="メールアドレス">
          <input style={inputCss} placeholder="例：yuko@example.com"/>
        </Field>
        <Field label="ご住所（郵便番号）">
          <input style={inputCss} placeholder="例：107-0062 港区南青山"/>
        </Field>
      </div>
    </div>
  );
}

// ペット写真用の縦型アップローダー（PhotoUpload の vertical 変形）
function PetPhotoUpload({ value, onChange }) {
  const inputRef = React.useRef(null);
  const [previewURL, setPreviewURL] = React.useState(null);
  React.useEffect(() => {
    if (value instanceof File) {
      const url = URL.createObjectURL(value);
      setPreviewURL(url);
      return () => URL.revokeObjectURL(url);
    } else {
      setPreviewURL(null);
    }
  }, [value]);
  const pick = () => inputRef.current?.click();
  const onFile = (e) => {
    const f = e.target.files?.[0];
    if (f) onChange(f);
    e.target.value = '';
  };
  return (
    <div>
      <div style={{
        aspectRatio:'1/1',borderRadius:20,
        background: previewURL ? '#fff' : 'repeating-linear-gradient(135deg,#F8CFB8 0 12px,#EBA689 12px 24px)',
        display:'grid',placeItems:'center',color:'#5b4326',
        fontFamily:'ui-monospace',fontSize:11,
        overflow:'hidden',cursor:'pointer',
        border: previewURL ? '1.5px solid var(--c-primary)' : '1.5px dashed rgba(0,0,0,.15)',
      }} onClick={pick}>
        {previewURL ? (
          <img src={previewURL} alt="pet" style={{width:'100%',height:'100%',objectFit:'cover'}}/>
        ) : (
          <span>📷 photo</span>
        )}
      </div>
      <button onClick={pick} style={{
        width:'100%',marginTop:10,background:'var(--c-primary-soft)',color:'var(--c-primary-deep)',
        border:'none',padding:'10px',borderRadius:10,fontWeight:700,cursor:'pointer',fontFamily:'inherit',fontSize:13,
      }}>{previewURL ? '写真を変更' : '写真を選ぶ'}</button>
      <input ref={inputRef} type="file" accept="image/*" onChange={onFile} style={{display:'none'}}/>
    </div>
  );
}

function OwnerPet({form, updatePet}) {
  const p = form.pets[0];
  return (
    <div>
      <div style={{fontSize:13,color:'var(--c-primary-deep)',fontWeight:700,fontFamily:'ui-monospace',marginBottom:6}}>STEP 02</div>
      <h2 style={{fontSize:30,fontWeight:700,letterSpacing:'-.01em',marginBottom:8}}>ペットの基本情報</h2>
      <p style={{fontSize:14,color:'#7a6a55',marginBottom:24,lineHeight:1.7}}>あとで何頭でも追加できます。</p>

      <div style={{
        background:'#fff',borderRadius:24,padding:'28px',display:'grid',gridTemplateColumns:'200px 1fr',gap:24,
        border:'1.5px solid rgba(0,0,0,.06)',
      }}>
        <div>
          <PetPhotoUpload
            value={p.photo}
            onChange={(f)=>updatePet(0,{photo:f})}/>
          <div style={{fontSize:11,color:'#9c8a72',marginTop:8,lineHeight:1.6,textAlign:'center'}}>
            お顔がはっきり見える写真を選んでください
          </div>
        </div>
        <div style={{display:'flex',flexWrap:'wrap',gap:14}}>
          <Field label="お名前" half>
            <input style={inputCss} value={p.name} placeholder="例：モカ" onChange={e=>updatePet(0,{name:e.target.value})}/>
          </Field>
          <Field label="種類" half>
            <div style={{display:'flex',gap:6}}>
              {[['dog','犬'],['cat','猫'],['rabbit','うさぎ'],['other','他']].map(([k,n])=>{
                const sel = p.species === k;
                return (
                  <button key={k} onClick={()=>updatePet(0,{species:k})} style={{
                    flex:1,padding:'14px 0',borderRadius:12,fontFamily:'inherit',cursor:'pointer',
                    border:'1.5px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
                    background:sel?'var(--c-primary-soft)':'#fff',
                    color:sel?'var(--c-primary-deep)':'#5d4d3a',fontWeight:600,fontSize:13,
                  }}>{n}</button>
                );
              })}
            </div>
          </Field>
          <Field label="品種" half>
            <input style={inputCss} value={p.breed} placeholder="例：柴犬" onChange={e=>updatePet(0,{breed:e.target.value})}/>
          </Field>
          <Field label="年齢（歳）" half>
            <input style={inputCss} type="number" value={p.age} placeholder="例：3" onChange={e=>updatePet(0,{age:+e.target.value})}/>
          </Field>
          <Field label="性別" half>
            <div style={{display:'flex',gap:6}}>
              {[['F','メス'],['M','オス']].map(([k,n])=>{
                const sel = p.sex === k;
                return (
                  <button key={k} onClick={()=>updatePet(0,{sex:k})} style={{
                    flex:1,padding:'14px 0',borderRadius:12,fontFamily:'inherit',cursor:'pointer',
                    border:'1.5px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
                    background:sel?'var(--c-primary-soft)':'#fff',
                    color:sel?'var(--c-primary-deep)':'#5d4d3a',fontWeight:600,fontSize:13,
                  }}>{n}</button>
                );
              })}
            </div>
          </Field>
          <Field label="体重（kg）" half>
            <input style={inputCss} type="number" value={p.weight} placeholder="例：8" onChange={e=>updatePet(0,{weight:+e.target.value})}/>
          </Field>
        </div>
      </div>

      <button style={{
        marginTop:14,background:'transparent',color:'var(--c-primary-deep)',
        border:'1.5px dashed rgba(216,120,131,.4)',
        padding:'14px',borderRadius:14,width:'100%',cursor:'pointer',
        fontFamily:'inherit',fontSize:14,fontWeight:600,
        display:'inline-flex',gap:8,alignItems:'center',justifyContent:'center',
      }}><Icons.Plus size={16}/> もう一頭、追加する</button>
    </div>
  );
}

function OwnerHealth({form, updatePet, togglePetTrait}) {
  const p = form.pets[0];
  const traits = [
    ['friendly','人懐っこい'],
    ['shy_strangers','人見知り'],
    ['active','元気いっぱい'],
    ['calm','おとなしい'],
    ['barks','よく吠える'],
    ['food_motivated','食いしん坊'],
    ['other_pets_ok','他の動物OK'],
    ['kids_ok','子ども慣れ'],
    ['anxious_alone','留守番が苦手'],
  ];
  return (
    <div>
      <div style={{fontSize:13,color:'var(--c-primary-deep)',fontWeight:700,fontFamily:'ui-monospace',marginBottom:6}}>STEP 03</div>
      <h2 style={{fontSize:30,fontWeight:700,letterSpacing:'-.01em',marginBottom:8}}>{p.name ? `${p.name}ちゃんのこと、教えてください` : 'ペットのこと、教えてください'}</h2>
      <p style={{fontSize:14,color:'#7a6a55',marginBottom:24,lineHeight:1.7}}>シッターさんがその子に合わせて、寄り添ってお世話できるように。</p>

      <div style={{marginBottom:22}}>
        <div style={{fontSize:14,fontWeight:600,marginBottom:10}}>性格・特徴（複数選択可）</div>
        <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
          {traits.map(([k,n])=>{
            const sel = p.traits.includes(k);
            return (
              <button key={k} onClick={()=>togglePetTrait(0,k)} style={{
                padding:'10px 16px',borderRadius:999,fontFamily:'inherit',cursor:'pointer',
                border:'1.5px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
                background:sel?'var(--c-primary-soft)':'#fff',
                color:sel?'var(--c-primary-deep)':'#3c2f1e',
                fontWeight:600,fontSize:13,display:'inline-flex',gap:6,alignItems:'center',
              }}>{sel && <Icons.Check size={13} stroke={2.6}/>}{n}</button>
            );
          })}
        </div>
      </div>

      <div style={{display:'flex',flexWrap:'wrap',gap:16}}>
        <Field label="アレルギー・苦手なもの">
          <input style={inputCss} value={p.allergies} placeholder="例：小麦アレルギー" onChange={e=>updatePet(0,{allergies:e.target.value})}/>
        </Field>
        <Field label="持病・服用中の薬" hint="投薬が必要な場合はシッター側にも反映されます">
          <input style={inputCss} value={p.meds} placeholder="例：心臓の薬を毎朝1錠" onChange={e=>updatePet(0,{meds:e.target.value})}/>
        </Field>
        <Field label="好きなこと・くせ" hint="シッターさんが仲良くなるためのヒントに">
          <textarea style={{...inputCss,minHeight:90,resize:'vertical',lineHeight:1.8}}
                    value={p.likes} placeholder="例：ボール遊び、おやつのささみ" onChange={e=>updatePet(0,{likes:e.target.value})}/>
        </Field>
        <Field label="かかりつけ動物病院">
          <input style={inputCss} placeholder="例：青山どうぶつ病院 ・ 03-XXXX-XXXX"/>
        </Field>
      </div>
    </div>
  );
}

function OwnerService({form, set, toggle}) {
  const types = [
    ['visit','訪問ケア','飼い主様宅にお伺いします',Icons.Pin],
    ['walk','お散歩のみ','お家までお迎えに行きます',Icons.Sparkle],
    ['stay','お預かり（シッター宅）','シッターの自宅でお預かり',Icons.Heart],
    ['overnight','お泊まり','宿泊を含む長時間のケア',Icons.Calendar],
  ];
  const freqs = [
    ['occasional','たまに（旅行・出張時）'],
    ['weekly','週1〜2回'],
    ['daily','毎日（平日 日中）'],
  ];
  return (
    <div>
      <div style={{fontSize:13,color:'var(--c-primary-deep)',fontWeight:700,fontFamily:'ui-monospace',marginBottom:6}}>STEP 04</div>
      <h2 style={{fontSize:30,fontWeight:700,letterSpacing:'-.01em',marginBottom:8}}>どんなお世話を希望されますか？</h2>
      <p style={{fontSize:14,color:'#7a6a55',marginBottom:24,lineHeight:1.7}}>あとから依頼ごとに変更できます。</p>

      <div style={{fontSize:14,fontWeight:600,marginBottom:10}}>依頼したいサービス（複数選択可）</div>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:14,marginBottom:24}}>
        {types.map(([k,n,d,I])=>{
          const sel = form.services.includes(k);
          return (
            <button key={k} onClick={()=>toggle('services',k)} style={{
              padding:'22px',borderRadius:18,fontFamily:'inherit',textAlign:'left',cursor:'pointer',
              border:'2px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
              background:sel?'var(--c-primary-soft)':'#fff',
              display:'flex',gap:14,alignItems:'center',
            }}>
              <div style={{
                width:46,height:46,borderRadius:14,
                background:sel?'#fff':'var(--c-bg-alt)',
                color:sel?'var(--c-primary-deep)':'#9c8a72',
                display:'grid',placeItems:'center',flex:'0 0 auto',
              }}><I size={22}/></div>
              <div style={{flex:1}}>
                <div style={{fontWeight:700,fontSize:15}}>{n}</div>
                <div style={{fontSize:12,color:'#7a6a55',marginTop:2}}>{d}</div>
              </div>
              <div style={{
                width:22,height:22,borderRadius:6,
                border:'2px solid '+(sel?'var(--c-primary-deep)':'rgba(0,0,0,.12)'),
                background:sel?'var(--c-primary-deep)':'transparent',
                color:'#fff',display:'grid',placeItems:'center',
              }}>{sel && <Icons.Check size={12} stroke={3}/>}</div>
            </button>
          );
        })}
      </div>

      <div style={{fontSize:14,fontWeight:600,marginBottom:10}}>頻度</div>
      <div style={{display:'flex',gap:6}}>
        {freqs.map(([k,n])=>{
          const sel = form.frequency === k;
          return (
            <button key={k} onClick={()=>set('frequency',k)} style={{
              flex:1,padding:'18px 14px',borderRadius:14,fontFamily:'inherit',cursor:'pointer',
              border:'1.5px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
              background:sel?'var(--c-primary-soft)':'#fff',
              color:sel?'var(--c-primary-deep)':'#3c2f1e',
              fontWeight:600,fontSize:14,
            }}>{n}</button>
          );
        })}
      </div>
    </div>
  );
}

function OwnerCare({form, set}) {
  const keys = [
    ['smart-lock','スマートロック','一時的なパスコードを発行'],
    ['hand-over','対面で受け渡し','初回打ち合わせ時に',],
    ['locker','宅配ボックス','コインロッカーなど'],
    ['hidden','ご自宅の隠し場所','詳細はチャットで'],
  ];
  const reports = [
    ['every-visit','毎訪問のあと','写真付き / 散歩ルート付き'],
    ['daily','1日1回まとめて',''],
    ['emergency','緊急時のみ',''],
  ];
  return (
    <div>
      <div style={{fontSize:13,color:'var(--c-primary-deep)',fontWeight:700,fontFamily:'ui-monospace',marginBottom:6}}>STEP 05</div>
      <h2 style={{fontSize:30,fontWeight:700,letterSpacing:'-.01em',marginBottom:8}}>お留守番中のご希望</h2>
      <p style={{fontSize:14,color:'#7a6a55',marginBottom:24,lineHeight:1.7}}>シッターさんとの連絡や、鍵の受け渡し方法を選んでください。</p>

      <div style={{marginBottom:24}}>
        <div style={{fontSize:14,fontWeight:600,marginBottom:10}}>鍵の受け渡し方法</div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:10}}>
          {keys.map(([k,n,d])=>{
            const sel = form.keyMethod === k;
            return (
              <button key={k} onClick={()=>set('keyMethod',k)} style={{
                padding:'16px 18px',borderRadius:16,fontFamily:'inherit',textAlign:'left',cursor:'pointer',
                border:'2px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
                background:sel?'var(--c-primary-soft)':'#fff',
              }}>
                <div style={{display:'flex',alignItems:'center',gap:8}}>
                  <span style={{
                    width:18,height:18,borderRadius:'50%',flex:'0 0 auto',
                    border:'2px solid '+(sel?'var(--c-primary-deep)':'rgba(0,0,0,.15)'),
                    background:sel?'var(--c-primary-deep)':'transparent',
                  }}/>
                  <strong style={{fontSize:14}}>{n}</strong>
                </div>
                <div style={{fontSize:12,color:'#7a6a55',marginTop:4,marginLeft:26}}>{d}</div>
              </button>
            );
          })}
        </div>
      </div>

      <div style={{marginBottom:24}}>
        <div style={{fontSize:14,fontWeight:600,marginBottom:10}}>レポートの頻度</div>
        <div style={{display:'flex',flexDirection:'column',gap:8}}>
          {reports.map(([k,n,d])=>{
            const sel = form.reportFreq === k;
            return (
              <button key={k} onClick={()=>set('reportFreq',k)} style={{
                padding:'14px 18px',borderRadius:14,fontFamily:'inherit',textAlign:'left',cursor:'pointer',
                border:'1.5px solid '+(sel?'var(--c-primary)':'rgba(0,0,0,.08)'),
                background:sel?'var(--c-primary-soft)':'#fff',
                display:'flex',gap:12,alignItems:'center',
              }}>
                <span style={{
                  width:18,height:18,borderRadius:'50%',flex:'0 0 auto',
                  border:'2px solid '+(sel?'var(--c-primary-deep)':'rgba(0,0,0,.15)'),
                  background:sel?'var(--c-primary-deep)':'transparent',
                }}/>
                <div>
                  <strong style={{fontSize:14}}>{n}</strong>
                  {d && <div style={{fontSize:12,color:'#7a6a55',marginTop:2}}>{d}</div>}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      <Field label="緊急時連絡先" hint="ご家族や、近くの友人など">
        <input style={inputCss} value={form.emergency} placeholder="例：夫 090-XXXX-XXXX" onChange={e=>set('emergency',e.target.value)}/>
      </Field>

      <div style={{
        marginTop:20,padding:'14px 18px',borderRadius:14,
        background:'var(--c-bg)',border:'1px solid rgba(0,0,0,.06)',
        display:'flex',gap:12,alignItems:'flex-start',
      }}>
        <Icons.Shield size={18}/>
        <div style={{fontSize:12,color:'#5d4d3a',lineHeight:1.8}}>
          ご登録内容は運営の管理用スプレッドシートに自動で記録され、Palpet運営宛に通知メールが届きます。
          1〜2営業日でコンシェルジュより、初回カウンセリングのご案内をお送りします。
        </div>
      </div>
    </div>
  );
}

// ----- right preview -----
function PetPreviewCard({pet}) {
  const speciesLabel = {dog:'犬',cat:'猫',rabbit:'うさぎ',other:'その他'};
  const traitLabel = {
    friendly:'人懐っこい',shy_strangers:'人見知り',active:'元気',calm:'おとなしい',
    barks:'よく吠える',food_motivated:'食いしん坊',other_pets_ok:'動物OK',
    kids_ok:'子ども慣れ',anxious_alone:'留守番苦手',
  };
  return (
    <div style={{background:'var(--c-bg)',borderRadius:18,padding:14,border:'1px solid rgba(0,0,0,.04)'}}>
      <div style={{
        aspectRatio:'4/3',borderRadius:12,
        background:'repeating-linear-gradient(135deg,#F8CFB8 0 12px,#EBA689 12px 24px)',
        marginBottom:12,
      }}/>
      <div style={{display:'flex',alignItems:'center',gap:6,marginBottom:6}}>
        <strong style={{fontSize:16}}>{pet.name}</strong>
        <span style={{fontSize:11,color:'#7a6a55'}}>{pet.age}歳・{pet.sex==='F'?'♀':'♂'}</span>
      </div>
      <div style={{fontSize:12,color:'#7a6a55'}}>{speciesLabel[pet.species]} / {pet.breed} / {pet.weight}kg</div>
      <div style={{display:'flex',gap:4,marginTop:10,flexWrap:'wrap'}}>
        {pet.traits.slice(0,4).map((t,i)=>(
          <span key={i} style={{fontSize:10,padding:'3px 8px',borderRadius:999,background:'#fff',color:'#5d4d3a',border:'1px solid rgba(0,0,0,.06)'}}>{traitLabel[t]}</span>
        ))}
      </div>
      {pet.allergies && (
        <div style={{marginTop:10,padding:'8px 10px',background:'#fff',borderRadius:8,fontSize:11,color:'#7a6a55',lineHeight:1.5}}>
          <strong style={{color:'var(--c-primary-deep)'}}>⚠</strong> {pet.allergies}
        </div>
      )}
    </div>
  );
}

window.OwnerRegister = OwnerRegister;
