// admin-verification-modal.jsx — Admin "Request verification" dialog.
//
// Renders a modal where the admin picks which of the 4 sections to require
// (identity / gov_id / address / bank), an optional note, and a "send email
// now" toggle. On submit it calls admin_request_verification() which (a)
// upserts the verification row to status='requested', (b) audit-logs, (c)
// fires the email via send_booking_email().
//
// Mirrors the visual pattern of AIAddModal in admin-instructors.jsx.

const AVMSections = [
  { key:'identity', title:'Identity verification', body:'Legal name, date of birth, Social Security Number. Encrypted at rest.' },
  { key:'gov_id',   title:'Government ID photo',   body:"Driver's license, state ID, or US passport." },
  { key:'address',  title:'Mailing address (W-9)', body:"Required if we'll be issuing a 1099-NEC." },
  { key:'bank',     title:'Bank account for payouts', body:'Routing + account number. Encrypted at rest.' },
];

const AdminVerificationModal = ({ instructor, onClose, onSent }) => {
  const [picked, setPicked] = React.useState({ identity:true, gov_id:true, address:false, bank:false });
  const [note, setNote]       = React.useState(
    `Hi ${(instructor.name || '').split(' ')[0] || 'there'} — quick verification step so we can get your first payout ready. Takes about 4 minutes.`
  );
  const [sendEmail, setSendEmail] = React.useState(true);
  const [busy, setBusy]   = React.useState(false);
  const [error, setError] = React.useState('');

  const toggle = (k) => setPicked(p => ({ ...p, [k]: !p[k] }));
  const fields = Object.keys(picked).filter(k => picked[k]);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    if (fields.length === 0) { setError('Pick at least one section.'); return; }
    setBusy(true);
    try {
      const { error: rpcErr } = await window.supa.rpc('admin_request_verification', {
        p_instructor_id: instructor.id,
        p_fields:        fields,
        p_message:       note.trim() || null,
        p_send_email:    sendEmail,
      });
      if (rpcErr) throw rpcErr;
      onSent && onSent();
      onClose();
    } catch (e2) {
      setError(window.friendlyError ? window.friendlyError(e2, 'Could not send request') : (e2.message || 'Could not send request'));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(10,12,24,0.4)', display:'flex', alignItems:'center', justifyContent:'center', zIndex:9000, padding:16 }}>
      <div onClick={e => e.stopPropagation()} style={{ background:'#fff', borderRadius:16, padding:'24px', width:560, maxWidth:'100%', maxHeight:'90vh', overflowY:'auto', boxShadow:'0 20px 60px rgba(0,0,0,0.2)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14 }}>
          <div>
            <div style={{ fontWeight:700, fontSize:17, color:'oklch(18% 0.03 265)', marginBottom:3 }}>
              Request verification
            </div>
            <div style={{ fontSize:13, color:'oklch(50% 0.03 265)' }}>
              from <strong>{instructor.name}</strong>
            </div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background:'none', border:'none', fontSize:20, color:'oklch(50% 0.03 265)', cursor:'pointer', lineHeight:1 }}>×</button>
        </div>

        <p style={{ fontSize:13, color:'oklch(45% 0.04 265)', lineHeight:1.55, marginBottom:14 }}>
          Pick the sections you want them to send. They'll get an email and see a dashboard banner with a deep-link to the verification page.
        </p>

        <form onSubmit={submit}>
          <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:18 }}>
            {AVMSections.map(s => (
              <label key={s.key} style={{ display:'flex', alignItems:'flex-start', gap:12, padding:'12px 14px', border:`1.5px solid ${picked[s.key] ? 'oklch(22% 0.06 265)' : 'oklch(88% 0.02 265)'}`, background: picked[s.key] ? 'oklch(97% 0.02 265)' : '#fff', borderRadius:10, cursor:'pointer', transition:'background 0.1s' }}>
                <input type="checkbox" checked={picked[s.key]} onChange={() => toggle(s.key)}
                  style={{ marginTop:2, width:18, height:18, cursor:'pointer', accentColor:'oklch(22% 0.06 265)' }} />
                <div>
                  <div style={{ fontSize:14, fontWeight:700, color:'oklch(18% 0.03 265)', marginBottom:2 }}>{s.title}</div>
                  <div style={{ fontSize:12, color:'oklch(50% 0.03 265)', lineHeight:1.5 }}>{s.body}</div>
                </div>
              </label>
            ))}
          </div>

          <div style={{ marginBottom:14 }}>
            <label style={{ display:'block', fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(52% 0.04 265)', marginBottom:6 }}>
              Optional note shown to {(instructor.name || '').split(' ')[0] || 'instructor'}
            </label>
            <textarea value={note} onChange={e => setNote(e.target.value)} rows={3}
              style={{ width:'100%', padding:'10px 12px', borderRadius:10, border:'1.5px solid oklch(88% 0.02 265)', fontFamily:"'Plus Jakarta Sans', sans-serif", fontSize:13, color:'oklch(22% 0.06 265)', resize:'vertical', minHeight:70, lineHeight:1.55, outline:'none' }} />
          </div>

          <label style={{ display:'flex', alignItems:'center', gap:10, marginBottom:18, fontSize:13, color:'oklch(28% 0.05 265)', cursor:'pointer' }}>
            <input type="checkbox" checked={sendEmail} onChange={e => setSendEmail(e.target.checked)}
              style={{ width:16, height:16, cursor:'pointer', accentColor:'oklch(22% 0.06 265)' }} />
            Send notification email now
          </label>

          {error && (
            <div style={{ background:'oklch(95% 0.06 25)', color:'oklch(40% 0.15 25)', padding:'9px 12px', borderRadius:8, fontSize:12, marginBottom:12 }}>
              {error}
            </div>
          )}

          <div style={{ display:'flex', gap:10 }}>
            <button type="submit" disabled={busy || fields.length === 0}
              style={{ flex:1, background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:10, padding:'12px 0', fontWeight:700, fontSize:14, cursor: (busy || fields.length === 0) ? 'not-allowed' : 'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: (busy || fields.length === 0) ? 0.6 : 1 }}>
              {busy ? 'Sending…' : 'Send request →'}
            </button>
            <button type="button" onClick={onClose} disabled={busy}
              style={{ padding:'12px 22px', background:'oklch(95% 0.01 265)', border:'none', borderRadius:10, fontSize:14, fontWeight:600, cursor: busy ? 'wait' : 'pointer', color:'oklch(45% 0.04 265)', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

window.AdminVerificationModal = AdminVerificationModal;
