// src/features/instructor/ui/instructor-verify-steps.jsx
//
// The five data-collection step components for the instructor
// verification flow. The final review screen + post-submit
// end-states live in instructor-verify-review.jsx so both halves
// stay under the 400 LOC budget.
//
// Public on window:
//   IVWelcomeStep, IVIdentityStep, IVGovIdStep, IVAddressStep, IVBankStep.
//
// Reads helpers + style consts from window (published by
// instructor-verify.jsx).

const {
  IVLabel, IVHelper, IVError, IVDetails, IVTrustStrip, IVFooterButtons,
  IV_NAVY, IV_GOLD, IV_BORDER, IV_MUTED, IV_INK,
  IV_INPUT_STYLE, IV_FIELD_META,
} = window;

const IVWelcomeStep = ({ requestedFields, adminMessage, onStart }) => (
  <div>
    <div style={{ fontSize:12, fontWeight:700, letterSpacing:'0.1em', color:IV_GOLD, textTransform:'uppercase', marginBottom:10 }}>
      Verification
    </div>
    <h1 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:34, fontWeight:600, color:IV_INK, marginBottom:10, lineHeight:1.1 }}>
      Let's verify your account
    </h1>
    <p style={{ fontSize:15, color:'oklch(40% 0.04 265)', lineHeight:1.65, marginBottom:18, maxWidth:520 }}>
      A few quick steps to keep your earnings flowing and your tax forms in order. Your information is encrypted the moment you submit it and is only visible to Coaching's admin team — never to students.
    </p>
    {adminMessage && (
      <div style={{ marginBottom:18, padding:'12px 14px', background:'oklch(97% 0.025 80)', border:`1px solid ${IV_GOLD}`, borderRadius:10, fontSize:13, color:'oklch(28% 0.07 80)', fontStyle:'italic', lineHeight:1.55 }}>
        "{adminMessage}"
      </div>
    )}
    <div style={{ marginBottom:14, fontSize:13, fontWeight:700, color:'oklch(34% 0.05 265)' }}>What we'll ask for:</div>
    <ul style={{ listStyle:'none', padding:0, margin:'0 0 22px', display:'flex', flexDirection:'column', gap:8 }}>
      {requestedFields.map(f => (
        <li key={f} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 14px', background:'#fff', border:`1px solid ${IV_BORDER}`, borderRadius:10 }}>
          <span style={{ fontSize:20 }}>{IV_FIELD_META[f]?.icon}</span>
          <span style={{ fontSize:14, fontWeight:600, color:IV_INK }}>{IV_FIELD_META[f]?.label}</span>
        </li>
      ))}
    </ul>
    <div style={{ fontSize:13, color:IV_MUTED, marginBottom:8 }}>Takes about 4 minutes. You can save and continue any time.</div>
    <IVTrustStrip chips={[
      '🔒 AES-256 encryption',
      '🇺🇸 IRS-compliant',
      '👤 Admin-only access',
      '📜 Every access logged',
    ]} />
    <button type="button" onClick={onStart}
      style={{ marginTop:24, background:IV_NAVY, color:'#fff', border:'none', borderRadius:10, padding:'14px 28px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
      Get started →
    </button>
  </div>
);

const IVIdentityStep = ({ initial, onSubmit, onBack, busy, error }) => {
  const [first, setFirst]   = React.useState(initial?.legal_first_name || '');
  const [mid, setMid]       = React.useState(initial?.legal_middle_name || '');
  const [last, setLast]     = React.useState(initial?.legal_last_name || '');
  const [dob, setDob]       = React.useState('');
  const [ssn, setSsn]       = React.useState('');
  const valid = first.trim() && last.trim() && dob && ssnDigits(ssn).length === 9;
  const submit = () => onSubmit({ first: first.trim(), mid: mid.trim(), last: last.trim(), dob, ssn: ssnDigits(ssn) });
  return (
    <div>
      <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:26, fontWeight:600, color:IV_INK, marginBottom:6 }}>
        Confirm your legal name
      </h2>
      <p style={{ fontSize:14, color:'oklch(45% 0.03 265)', lineHeight:1.6, marginBottom:22, maxWidth:520 }}>
        This should match the name on your tax documents — it's the name we'll use on your 1099-NEC at the end of the year.
      </p>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
        <div style={{ gridColumn:'1/-1' }}>
          <IVLabel>Legal first name</IVLabel>
          <input type="text" value={first} onChange={e => setFirst(e.target.value)} autoComplete="given-name" style={IV_INPUT_STYLE} />
        </div>
        <div>
          <IVLabel hint="optional">Middle name</IVLabel>
          <input type="text" value={mid} onChange={e => setMid(e.target.value)} autoComplete="additional-name" style={IV_INPUT_STYLE} />
        </div>
        <div>
          <IVLabel>Legal last name</IVLabel>
          <input type="text" value={last} onChange={e => setLast(e.target.value)} autoComplete="family-name" style={IV_INPUT_STYLE} />
        </div>
      </div>
      <div style={{ marginBottom:22 }}>
        <IVLabel>Date of birth</IVLabel>
        <input type="date" value={dob} onChange={e => setDob(e.target.value)} autoComplete="bday" max={new Date(Date.now() - 13*365*86400000).toISOString().slice(0,10)} style={{ ...IV_INPUT_STYLE, maxWidth:260 }} />
        <IVHelper>Used only for identity verification. Never displayed publicly.</IVHelper>
      </div>

      <h3 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:22, fontWeight:600, color:IV_INK, marginTop:30, marginBottom:6 }}>
        Your Social Security Number
      </h3>
      <p style={{ fontSize:14, color:'oklch(45% 0.03 265)', lineHeight:1.65, marginBottom:6, maxWidth:520 }}>
        Coaching is required by the IRS to collect a Taxpayer Identification Number from every U.S. instructor who earns income on the platform. For individuals, that's your SSN.
      </p>
      <p style={{ fontSize:14, color:'oklch(45% 0.03 265)', lineHeight:1.65, marginBottom:14, maxWidth:520 }}>
        We use it for two things only: filing your 1099-NEC tax form at year end, and verifying your identity.
      </p>
      <div style={{ maxWidth:280, marginBottom:6 }}>
        <IVLabel>Social Security Number</IVLabel>
        <input type="text" value={ssn} onChange={e => setSsn(formatSSN(e.target.value))}
          placeholder="123-45-6789"
          inputMode="numeric" autoComplete="off" maxLength={11}
          style={{ ...IV_INPUT_STYLE, fontVariantNumeric:'tabular-nums', letterSpacing:'0.04em' }} />
        <IVHelper>We never show your full SSN after you submit it — only the last 4 digits.</IVHelper>
      </div>

      <IVDetails summary="How is my SSN stored?">
        Your SSN is encrypted with AES-256 the moment you submit it. The encrypted value lives in our database; the key is held in a separate vault. Only Coaching's admin team can decrypt it, and every access is recorded in an audit log. We never share it with third parties except as required for IRS filing.
      </IVDetails>
      <IVDetails summary="Why does Coaching collect this directly?">
        Marketplaces that pay U.S. workers are required to collect a Taxpayer Identification Number (your SSN, if you're an individual) and issue a 1099-NEC when annual payouts exceed $600. Wyzant, Upwork, Uber, DoorDash, and Fiverr all do the same.
      </IVDetails>

      <IVTrustStrip chips={['🔒 AES-256', '🇺🇸 IRS 1099-NEC', '👤 Admin-only', '📜 Access logged']} />
      <IVError>{error}</IVError>
      <IVFooterButtons onBack={onBack} onContinue={submit} busy={busy} disableContinue={!valid} />
    </div>
  );
};

const IVGovIdStep = ({ initial, onSubmit, onBack, busy, error, userId }) => {
  const [idType, setIdType] = React.useState(initial?.gov_id_type || 'drivers_license');
  const [file, setFile]     = React.useState(null);
  const [preview, setPreview] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);
  const [storagePath, setStoragePath] = React.useState(initial?.gov_id_storage_path || null);
  const fileRef = React.useRef(null);

  const pickFile = async (f) => {
    if (!f) return;
    if (f.size > 10 * 1024 * 1024) { alert('File is over 10 MB — please choose a smaller image.'); return; }
    setFile(f);
    setPreview(URL.createObjectURL(f));
    setUploading(true);
    try {
      const ext = (f.name.split('.').pop() || 'jpg').toLowerCase();
      const path = `${userId}/${Date.now()}-gov-id.${ext}`;
      const { error: upErr } = await window.supa.storage.from('instructor-gov-ids').upload(path, f, { upsert:true, contentType: f.type });
      if (upErr) throw upErr;
      setStoragePath(path);
    } catch (e) {
      alert(window.friendlyError ? window.friendlyError(e, 'Upload failed') : (e.message || 'Upload failed'));
      setFile(null); setPreview(null); setStoragePath(null);
    } finally {
      setUploading(false);
    }
  };

  const submit = () => {
    if (!storagePath) { alert('Please upload a photo first.'); return; }
    onSubmit({ idType, storagePath });
  };

  const valid = !!storagePath && !uploading;

  return (
    <div>
      <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:26, fontWeight:600, color:IV_INK, marginBottom:6 }}>
        Upload a photo of your ID
      </h2>
      <p style={{ fontSize:14, color:'oklch(45% 0.03 265)', lineHeight:1.6, marginBottom:18, maxWidth:520 }}>
        Driver's license, state ID, or US passport. Front side only.
      </p>

      <div style={{ display:'flex', gap:10, flexWrap:'wrap', marginBottom:16 }}>
        {[
          { v:'drivers_license', label:"Driver's license" },
          { v:'state_id',        label:'State ID' },
          { v:'passport',        label:'US passport' },
        ].map(o => (
          <button key={o.v} type="button" onClick={() => setIdType(o.v)}
            style={{ padding:'9px 16px', borderRadius:20, fontSize:13, fontWeight:600,
              background: idType === o.v ? IV_NAVY : '#fff',
              color: idType === o.v ? '#fff' : IV_INK,
              border: idType === o.v ? `1.5px solid ${IV_NAVY}` : `1.5px solid ${IV_BORDER}`,
              cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
            {idType === o.v ? '✓ ' : ''}{o.label}
          </button>
        ))}
      </div>

      <input ref={fileRef} type="file" accept="image/*" capture="environment" style={{ display:'none' }}
        onChange={e => pickFile(e.target.files?.[0])} />
      <div onClick={() => fileRef.current?.click()}
        style={{ cursor:'pointer', border:`2px dashed ${IV_BORDER}`, borderRadius:14, padding:'30px 20px', textAlign:'center', background:'#fff', minHeight:160, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:8 }}>
        {preview ? (
          <>
            <img src={preview} alt="ID preview" style={{ maxWidth:'100%', maxHeight:220, borderRadius:10, objectFit:'contain' }} />
            <div style={{ fontSize:12, color:IV_MUTED, marginTop:8 }}>
              {uploading ? 'Uploading…' : storagePath ? '✓ Uploaded · tap to replace' : 'Tap to upload again'}
            </div>
          </>
        ) : (
          <>
            <div style={{ fontSize:32 }}>📷</div>
            <div style={{ fontSize:14, fontWeight:600, color:IV_INK }}>Tap to upload or take a photo</div>
            <div style={{ fontSize:12, color:IV_MUTED }}>JPG, PNG, or HEIC · under 10 MB</div>
          </>
        )}
      </div>

      <div style={{ marginTop:14, padding:'10px 14px', background:'oklch(96% 0.012 265)', borderRadius:10, fontSize:13, color:'oklch(34% 0.04 265)', lineHeight:1.55 }}>
        <strong style={{ fontWeight:700 }}>Tips:</strong>{' '}
        Good lighting, no glare · all four corners visible · text is sharp and readable.
      </div>

      <IVTrustStrip chips={['🔒 Private bucket', '👤 Admin-only access', '🔐 Encrypted transport']} />
      <IVError>{error}</IVError>
      <IVFooterButtons onBack={onBack} onContinue={submit} busy={busy || uploading} disableContinue={!valid} />
    </div>
  );
};

const IVAddressStep = ({ initial, onSubmit, onBack, busy, error }) => {
  const [l1, setL1]       = React.useState(initial?.address_line1 || '');
  const [l2, setL2]       = React.useState(initial?.address_line2 || '');
  const [city, setCity]   = React.useState(initial?.address_city || '');
  const [st, setSt]       = React.useState(initial?.address_state || '');
  const [zip, setZip]     = React.useState(initial?.address_zip || '');
  const valid = l1.trim() && city.trim() && st.length === 2 && /^[0-9]{5}(-[0-9]{4})?$/.test(zip);
  return (
    <div>
      <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:26, fontWeight:600, color:IV_INK, marginBottom:6 }}>
        Your mailing address
      </h2>
      <p style={{ fontSize:14, color:'oklch(45% 0.03 265)', lineHeight:1.6, marginBottom:22, maxWidth:520 }}>
        This is the address that will appear on your 1099-NEC at year end.
      </p>
      <div style={{ marginBottom:14 }}>
        <IVLabel>Address line 1</IVLabel>
        <input type="text" value={l1} onChange={e => setL1(e.target.value)} autoComplete="address-line1" style={IV_INPUT_STYLE} placeholder="123 Main St" />
      </div>
      <div style={{ marginBottom:14 }}>
        <IVLabel hint="apt, suite, unit — optional">Address line 2</IVLabel>
        <input type="text" value={l2} onChange={e => setL2(e.target.value)} autoComplete="address-line2" style={IV_INPUT_STYLE} placeholder="Apt 4B" />
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1fr', gap:14, marginBottom:14 }}>
        <div>
          <IVLabel>City</IVLabel>
          <input type="text" value={city} onChange={e => setCity(e.target.value)} autoComplete="address-level2" style={IV_INPUT_STYLE} />
        </div>
        <div>
          <IVLabel>State</IVLabel>
          <input type="text" value={st} onChange={e => setSt(e.target.value.toUpperCase().slice(0,2))} maxLength={2} autoComplete="address-level1" style={IV_INPUT_STYLE} placeholder="NY" />
        </div>
        <div>
          <IVLabel>ZIP</IVLabel>
          <input type="text" value={zip} onChange={e => setZip(e.target.value)} inputMode="numeric" autoComplete="postal-code" maxLength={10} style={IV_INPUT_STYLE} placeholder="10001" />
        </div>
      </div>
      <IVTrustStrip chips={['🔒 Stored securely', '🇺🇸 1099-NEC use only']} />
      <IVError>{error}</IVError>
      <IVFooterButtons onBack={onBack} onContinue={() => onSubmit({ l1: l1.trim(), l2: l2.trim(), city: city.trim(), st, zip })} busy={busy} disableContinue={!valid} />
    </div>
  );
};

const IVBankStep = ({ initial, onSubmit, onBack, busy, error }) => {
  const [holder, setHolder]   = React.useState(initial?.bank_account_holder_name || '');
  const [acctType, setType]   = React.useState(initial?.bank_account_type || 'checking');
  const [routing, setRouting] = React.useState('');
  const [acct, setAcct]       = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const valid = holder.trim() && routing.replace(/\D/g,'').length === 9 && acct.replace(/\D/g,'').length >= 4 && acct === confirm;
  return (
    <div>
      <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:26, fontWeight:600, color:IV_INK, marginBottom:6 }}>
        Where should your payouts go?
      </h2>
      <p style={{ fontSize:14, color:'oklch(45% 0.03 265)', lineHeight:1.6, marginBottom:22, maxWidth:520 }}>
        We deposit your earnings by ACH every other Friday. There are no payout fees from Coaching.
      </p>
      <div style={{ marginBottom:14 }}>
        <IVLabel>Account holder name</IVLabel>
        <input type="text" value={holder} onChange={e => setHolder(e.target.value)} autoComplete="cc-name" style={IV_INPUT_STYLE} />
        <IVHelper>Must match the name on your bank account.</IVHelper>
      </div>
      <div style={{ marginBottom:14 }}>
        <IVLabel>Account type</IVLabel>
        <div style={{ display:'flex', gap:10 }}>
          {['checking','savings'].map(t => (
            <button key={t} type="button" onClick={() => setType(t)}
              style={{ padding:'10px 18px', borderRadius:20, fontSize:13, fontWeight:600,
                background: acctType === t ? IV_NAVY : '#fff',
                color: acctType === t ? '#fff' : IV_INK,
                border: acctType === t ? `1.5px solid ${IV_NAVY}` : `1.5px solid ${IV_BORDER}`,
                cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif", textTransform:'capitalize' }}>
              {t}
            </button>
          ))}
        </div>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginBottom:14 }}>
        <div>
          <IVLabel hint="9 digits">Routing number</IVLabel>
          <input type="text" value={routing} onChange={e => setRouting(e.target.value.replace(/\D/g,'').slice(0,9))}
            inputMode="numeric" autoComplete="off" style={{ ...IV_INPUT_STYLE, fontVariantNumeric:'tabular-nums' }} />
        </div>
        <div>
          <IVLabel>Account number</IVLabel>
          <input type="text" value={acct} onChange={e => setAcct(e.target.value.replace(/\D/g,'').slice(0,17))}
            inputMode="numeric" autoComplete="off" style={{ ...IV_INPUT_STYLE, fontVariantNumeric:'tabular-nums' }} />
        </div>
      </div>
      <div style={{ marginBottom:14, maxWidth:'50%' }}>
        <IVLabel>Confirm account number</IVLabel>
        <input type="text" value={confirm} onChange={e => setConfirm(e.target.value.replace(/\D/g,'').slice(0,17))}
          inputMode="numeric" autoComplete="off" style={{ ...IV_INPUT_STYLE, fontVariantNumeric:'tabular-nums' }} />
        {confirm && confirm !== acct && <IVHelper><span style={{ color:'oklch(40% 0.15 25)' }}>Account numbers don't match.</span></IVHelper>}
      </div>

      <IVDetails summary="How is my bank info stored?">
        Your routing and account numbers are encrypted with AES-256 the moment you submit. After this screen, only the last 4 digits of your account are visible again — and only to you and Coaching's admin team.
      </IVDetails>

      <IVTrustStrip chips={['🔒 AES-256', '🏦 ACH only', '👤 Admin-only', '📜 Access logged']} />
      <IVError>{error}</IVError>
      <IVFooterButtons onBack={onBack} onContinue={() => onSubmit({ holder: holder.trim(), acctType, routing: routing.replace(/\D/g,''), acct: acct.replace(/\D/g,'') })} busy={busy} disableContinue={!valid} />
    </div>
  );
};

// IVReviewStep, ReviewBlock, IVEndState moved to instructor-verify-review.jsx
Object.assign(window, {
  IVWelcomeStep, IVIdentityStep, IVGovIdStep, IVAddressStep, IVBankStep,
});
