// 守望小生灵 · 通用 Modal 组件（紧急上报 / 捐赠 / 领养申请）

const ModalShell = ({ title, subtitle, onClose, children, width = 520 }) => {
  React.useEffect(() => {
    const onKey = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [onClose]);
  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 99,
      background: 'rgba(10,20,30,0.55)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20,
    }} onClick={onClose}>
      <div style={{
        background: '#fff', borderRadius: 16, width: '100%', maxWidth: width,
        maxHeight: '90vh', overflow: 'auto',
        boxShadow: '0 30px 80px -20px rgba(0,0,0,0.4)',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ padding: '24px 28px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <h3 style={{ fontSize: 22, fontWeight: 800, color: 'var(--text)', letterSpacing: '-0.01em' }}>{title}</h3>
            {subtitle && <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>{subtitle}</div>}
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 999, background: 'var(--neutral-bg)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg className="gp-icon" style={{ width: 16, height: 16, stroke: 'var(--text)' }} viewBox="0 0 24 24"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>
        <div style={{ padding: '20px 28px 28px' }}>
          {children}
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, required, hint, children }) => (
  <label style={{ display: 'block', marginBottom: 14 }}>
    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text)', marginBottom: 6 }}>
      {label}{required && <span style={{ color: 'var(--accent)' }}> *</span>}
      {hint && <span style={{ fontWeight: 400, color: 'var(--text-muted)', marginLeft: 6 }}>{hint}</span>}
    </div>
    {children}
  </label>
);

const fieldStyle = {
  width: '100%', padding: '10px 12px', borderRadius: 8,
  border: '1px solid var(--border-strong)', background: '#fff',
  fontSize: 14, fontFamily: 'inherit', color: 'var(--text)',
  outline: 'none',
};

// ---------- 紧急上报 ----------
const EmergencyModal = ({ onClose }) => {
  const [form, setForm] = React.useState({ reporter_name: '', contact: '', location: '', description: '', photo_url: '' });
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(null);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const submit = async () => {
    if (!form.contact || !form.location || !form.description) return alert('请完整填写联系方式、位置、情况描述');
    setBusy(true);
    try {
      const r = await window.GP.submitEmergency(form);
      setDone(r);
    } catch (e) { alert('提交失败：' + e.message); }
    finally { setBusy(false); }
  };

  if (done) return (
    <ModalShell title="已收到紧急上报" subtitle={`工单受理号 #${done.id}，志愿者会尽快联系你`} onClose={onClose}>
      <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.6, marginBottom: 16 }}>
        我们会按属地优先派员，预计 1 小时内回电核实。请保持手机通畅。
      </p>
      <button className="gp-btn gp-btn-primary" style={{ width: '100%' }} onClick={onClose}>好的</button>
    </ModalShell>
  );

  return (
    <ModalShell title="紧急救助上报" subtitle="任何人都可以提交，志愿者会就近响应" onClose={onClose}>
      <Field label="你的称呼" hint="选填">
        <input style={fieldStyle} value={form.reporter_name} onChange={e => set('reporter_name', e.target.value)} placeholder="如：路人甲" />
      </Field>
      <Field label="联系方式" required hint="电话 / 微信 / 邮箱">
        <input style={fieldStyle} value={form.contact} onChange={e => set('contact', e.target.value)} placeholder="139xxxx xxxx" />
      </Field>
      <Field label="发现位置" required>
        <input style={fieldStyle} value={form.location} onChange={e => set('location', e.target.value)} placeholder="城市 · 区 · 街道 / 标志物" />
      </Field>
      <Field label="情况描述" required>
        <textarea style={{ ...fieldStyle, minHeight: 90, resize: 'vertical' }} value={form.description} onChange={e => set('description', e.target.value)} placeholder="动物种类、伤情、当前状态、能否靠近等" />
      </Field>
      <Field label="现场照片链接" hint="选填，方便志愿者快速判断">
        <input style={fieldStyle} value={form.photo_url} onChange={e => set('photo_url', e.target.value)} placeholder="https://..." />
      </Field>
      <button className="gp-btn gp-btn-accent" style={{ width: '100%', marginTop: 8 }} disabled={busy} onClick={submit}>
        {busy ? '提交中…' : '立即上报'}
      </button>
    </ModalShell>
  );
};

// ---------- 捐赠 ----------
const DonateModal = ({ onClose }) => {
  const presets = [30, 50, 100, 200, 500, 1000];
  const [amount, setAmount] = React.useState(50);
  const [form, setForm] = React.useState({ donor_name: '', donor_email: '', message: '', category: '通用', anonymous: false });
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(null);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const submit = async () => {
    if (!amount || amount <= 0) return alert('请填写有效金额');
    setBusy(true);
    try {
      const r = await window.GP.donate({ ...form, amount });
      setDone(r);
    } catch (e) { alert('提交失败：' + e.message); }
    finally { setBusy(false); }
  };

  if (done) return (
    <ModalShell title="感谢你的善意" subtitle={`已记录 ¥${done.amount.toFixed(2)} · 收据将发送到邮箱`} onClose={onClose}>
      <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.7, marginBottom: 16 }}>
        每一笔捐赠都会出现在「透明公示」页面。你可以随时核对去向。
      </p>
      <button className="gp-btn gp-btn-primary" style={{ width: '100%' }} onClick={onClose}>好的</button>
    </ModalShell>
  );

  return (
    <ModalShell title="支持我们" subtitle="¥30 起 · 月捐 / 单次都可以" onClose={onClose} width={560}>
      <Field label="捐赠金额（元）" required>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8, marginBottom: 10 }}>
          {presets.map(v => (
            <button key={v} onClick={() => setAmount(v)} style={{
              padding: '10px 0', borderRadius: 8, fontSize: 14, fontWeight: 700,
              border: amount === v ? '2px solid var(--accent)' : '1px solid var(--border-strong)',
              background: amount === v ? '#FFF4F0' : '#fff',
              color: amount === v ? 'var(--accent-hover)' : 'var(--text)',
            }}>¥{v}</button>
          ))}
        </div>
        <input type="number" style={fieldStyle} value={amount} min={1} onChange={e => setAmount(parseFloat(e.target.value) || 0)} />
      </Field>
      <Field label="资金用途">
        <select style={fieldStyle} value={form.category} onChange={e => set('category', e.target.value)}>
          <option>通用</option>
          <option>医疗救治</option>
          <option>驻站养护</option>
          <option>绝育与防疫</option>
          <option>月捐计划</option>
        </select>
      </Field>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="姓名">
          <input style={fieldStyle} value={form.donor_name} onChange={e => set('donor_name', e.target.value)} placeholder="选填" />
        </Field>
        <Field label="邮箱（接收收据）">
          <input style={fieldStyle} value={form.donor_email} onChange={e => set('donor_email', e.target.value)} placeholder="选填" />
        </Field>
      </div>
      <Field label="留言">
        <textarea style={{ ...fieldStyle, minHeight: 70 }} value={form.message} onChange={e => set('message', e.target.value)} />
      </Field>
      <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-muted)', marginBottom: 16 }}>
        <input type="checkbox" checked={form.anonymous} onChange={e => set('anonymous', e.target.checked)} />
        匿名捐赠（捐赠墙不显示姓名）
      </label>
      <button className="gp-btn gp-btn-accent" style={{ width: '100%' }} disabled={busy} onClick={submit}>
        {busy ? '提交中…' : `确认捐赠 ¥${amount}`}
      </button>
      <div style={{ fontSize: 12, color: 'var(--text-soft)', textAlign: 'center', marginTop: 12 }}>
        本演示环境不接入真实支付通道
      </div>
    </ModalShell>
  );
};

// ---------- 领养申请 ----------
const AdoptModal = ({ animal, onClose }) => {
  const [form, setForm] = React.useState({
    applicant_name: '', contact: '', city: '', address: '',
    occupation: '', has_pets: false, experience: '', notes: ''
  });
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(null);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const submit = async () => {
    if (!form.applicant_name || !form.contact) return alert('请填写姓名与联系方式');
    setBusy(true);
    try {
      const r = await window.GP.applyAdoption({ ...form, animal_id: animal.id });
      setDone(r);
    } catch (e) { alert('提交失败：' + e.message); }
    finally { setBusy(false); }
  };

  if (done) return (
    <ModalShell title={`申请已收到 · ${animal.name}`} subtitle={`申请号 #${done.id}`} onClose={onClose}>
      <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.7, marginBottom: 16 }}>
        志愿者会在 3 个工作日内与你联系预约家访。期间请保持手机通畅。
      </p>
      <button className="gp-btn gp-btn-primary" style={{ width: '100%' }} onClick={onClose}>好的</button>
    </ModalShell>
  );

  return (
    <ModalShell title={`申请领养 · ${animal.name}`}
                subtitle={`${animal.breed || ''} · ${animal.location || ''}`}
                onClose={onClose} width={560}>
      <div style={{ display: 'flex', gap: 14, padding: 14, background: 'var(--neutral-bg)', borderRadius: 12, marginBottom: 20 }}>
        <img src={animal.image_url} alt={animal.name} style={{ width: 64, height: 64, borderRadius: 8, objectFit: 'cover' }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 16 }}>{animal.name}</div>
          <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4, lineHeight: 1.5 }}>
            {animal.medical_note || animal.story?.slice(0, 60) + '…'}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="姓名" required>
          <input style={fieldStyle} value={form.applicant_name} onChange={e => set('applicant_name', e.target.value)} />
        </Field>
        <Field label="联系方式" required>
          <input style={fieldStyle} value={form.contact} onChange={e => set('contact', e.target.value)} placeholder="电话 / 微信" />
        </Field>
        <Field label="所在城市">
          <input style={fieldStyle} value={form.city} onChange={e => set('city', e.target.value)} />
        </Field>
        <Field label="职业">
          <input style={fieldStyle} value={form.occupation} onChange={e => set('occupation', e.target.value)} />
        </Field>
      </div>
      <Field label="居住地址" hint="家访用，不会公开">
        <input style={fieldStyle} value={form.address} onChange={e => set('address', e.target.value)} />
      </Field>
      <Field label="过往养宠经验">
        <textarea style={{ ...fieldStyle, minHeight: 70 }} value={form.experience} onChange={e => set('experience', e.target.value)} />
      </Field>
      <Field label="补充说明">
        <textarea style={{ ...fieldStyle, minHeight: 60 }} value={form.notes} onChange={e => set('notes', e.target.value)} />
      </Field>
      <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--text-muted)', marginBottom: 16 }}>
        <input type="checkbox" checked={form.has_pets} onChange={e => set('has_pets', e.target.checked)} />
        家中已有其它宠物
      </label>
      <button className="gp-btn gp-btn-primary" style={{ width: '100%' }} disabled={busy} onClick={submit}>
        {busy ? '提交中…' : '提交申请'}
      </button>
    </ModalShell>
  );
};

// ---------- 志愿者申请 ----------
const VolunteerModal = ({ onClose }) => {
  const [form, setForm] = React.useState({
    name: '', email: '', phone: '', city: '', skills: '', availability: '', motivation: ''
  });
  const [busy, setBusy] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const submit = async () => {
    if (!form.name || !form.email) return alert('请填写姓名和邮箱');
    setBusy(true);
    try { await window.GP.applyVolunteer(form); setDone(true); }
    catch (e) { alert('提交失败：' + e.message); }
    finally { setBusy(false); }
  };

  if (done) return (
    <ModalShell title="谢谢你愿意加入" subtitle="48 小时内会有志愿者联系你" onClose={onClose}>
      <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.7, marginBottom: 16 }}>
        你的信息已经进入志愿者库。我们会优先匹配你所在城市的常驻任务。
      </p>
      <button className="gp-btn gp-btn-primary" style={{ width: '100%' }} onClick={onClose}>好的</button>
    </ModalShell>
  );

  return (
    <ModalShell title="加入志愿者" subtitle="把你的时间和技能借给小生灵" onClose={onClose} width={560}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="姓名" required>
          <input style={fieldStyle} value={form.name} onChange={e => set('name', e.target.value)} />
        </Field>
        <Field label="邮箱" required>
          <input style={fieldStyle} value={form.email} onChange={e => set('email', e.target.value)} />
        </Field>
        <Field label="手机">
          <input style={fieldStyle} value={form.phone} onChange={e => set('phone', e.target.value)} />
        </Field>
        <Field label="所在城市">
          <input style={fieldStyle} value={form.city} onChange={e => set('city', e.target.value)} placeholder="如：上海·浦东" />
        </Field>
      </div>
      <Field label="可参与方向" hint="多选，逗号分隔">
        <input style={fieldStyle} value={form.skills} onChange={e => set('skills', e.target.value)}
               placeholder="如：现场救助, 医疗陪同, 摄影, 翻译, 公众号编辑" />
      </Field>
      <Field label="时间安排">
        <select style={fieldStyle} value={form.availability} onChange={e => set('availability', e.target.value)}>
          <option value="">请选择</option>
          <option>周末 4 小时</option>
          <option>工作日晚 2 小时</option>
          <option>每周 8 小时以上</option>
          <option>项目制 / 不固定</option>
        </select>
      </Field>
      <Field label="你为什么想加入">
        <textarea style={{ ...fieldStyle, minHeight: 70 }} value={form.motivation} onChange={e => set('motivation', e.target.value)} />
      </Field>
      <button className="gp-btn gp-btn-primary" style={{ width: '100%' }} disabled={busy} onClick={submit}>
        {busy ? '提交中…' : '提交申请'}
      </button>
    </ModalShell>
  );
};

window.EmergencyModal = EmergencyModal;
window.DonateModal    = DonateModal;
window.AdoptModal     = AdoptModal;
window.VolunteerModal = VolunteerModal;
