// src/features/instructor/ui/become-instructor-v2-steps-2.jsx
//
// Second half of the BecomeInstructorV2 wizard steps:
// Profile, Agreement, Review, Confirmation (+ small row helpers).
// Extracted from become-instructor-v2-steps.jsx to bring both halves
// under the 400 LOC budget.
//
// Public on window:
//   BIV2Profile, BIV2Agreement, BIV2Review, ReviewRow,
//   BIV2Confirmation, BIV2ConfRow.
//
// Depends on (via window): BIV2Field, BIV2NavBar, biv2H1, biv2H3,
// biv2Sub, biv2Input, biv2ErrorBox, biv2CheckLabel — all published
// from become-instructor-v2.jsx.

const {
  BIV2Field, BIV2NavBar,
  biv2H1, biv2H3, biv2Sub, biv2Input, biv2ErrorBox, biv2CheckLabel,
} = window;

const BIV2Profile = ({ progress, config, instructorRow, advance, setStep, isMobile }) => {
  const copy = config['step.profile'] || {};
  const [headline, setHeadline] = React.useState(instructorRow.profile_headline || '');
  const [free, setFree] = React.useState(instructorRow.free_response || instructorRow.bio || '');
  const [photoUrl, setPhotoUrl] = React.useState(instructorRow.photo_url || '');
  const [uploading, setUploading] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const auth = window.useAuth();

  const onPickFile = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (file.size > 8 * 1024 * 1024) { setError('Photo must be 8 MB or smaller.'); return; }
    setUploading(true); setError(null);
    try {
      const ext = (file.name.split('.').pop() || 'jpg').toLowerCase();
      const path = `${auth.user.id}/profile-${Date.now()}.${ext}`;
      const { error: e } = await window.supa.storage.from('instructor-photos').upload(path, file, { upsert: true, contentType: file.type });
      if (e) throw e;
      const { data: pub } = window.supa.storage.from('instructor-photos').getPublicUrl(path);
      setPhotoUrl(pub.publicUrl);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Upload failed') : e.message);
    } finally { setUploading(false); }
  };

  const onNext = async () => {
    setError(null);
    if (!headline.trim()) { setError('Profile headline is required.'); return; }
    if (free.trim().length < 80) { setError('Your free response should be at least a couple of sentences (80+ characters).'); return; }
    setBusy(true);
    try {
      const { error: e } = await window.supa.rpc('signup_save_profile', {
        p: { profile_headline: headline.trim(), free_response: free.trim(), photo_url: photoUrl },
      });
      if (e) throw e;
      await advance();
      setStep(5);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not save') : e.message);
    } finally { setBusy(false); }
  };

  const remaining = 2048 - free.length;

  return (
    <div>
      <h1 style={biv2H1}>{copy.title || 'Personalize your profile'}</h1>
      <p style={biv2Sub}>{copy.subtitle}</p>
      <div style={{ background:'#fff', border:'1px solid oklch(94% 0.01 265)', borderRadius:12, padding: isMobile ? 18 : 28, marginTop:22 }}>
        <BIV2Field label="Profile headline" hint={copy.headline_hint}>
          <input value={headline} onChange={e=>setHeadline(e.target.value)} maxLength={140} style={biv2Input} placeholder="A short headline about yourself" />
        </BIV2Field>
        <BIV2Field label="Profile photo" hint={copy.photo_hint}>
          <div style={{ display:'flex', alignItems:'center', gap:14, flexWrap:'wrap' }}>
            {photoUrl && <img src={photoUrl} alt="Profile" style={{ width:80, height:80, borderRadius:'50%', objectFit:'cover', border:'2px solid oklch(88% 0.02 265)' }} />}
            <label style={{ display:'inline-flex', alignItems:'center', gap:8, padding:'10px 16px', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:8, cursor:'pointer', fontSize:13, fontWeight:600, background:'#fff' }}>
              {uploading ? 'Uploading…' : photoUrl ? 'Replace photo' : '⇪ Choose a file…'}
              <input type="file" accept="image/*" onChange={onPickFile} style={{ display:'none' }} />
            </label>
            <span style={{ fontSize:12, color:'oklch(50% 0.03 265)' }}>Min 200×200 px · JPG / PNG / HEIC · 8 MB max</span>
          </div>
        </BIV2Field>
        <BIV2Field label="Free response" hint={copy.free_response_hint}>
          <textarea value={free} onChange={e=>setFree(e.target.value)} maxLength={2048}
            style={{ ...biv2Input, minHeight:200, resize:'vertical', lineHeight:1.55 }}
            placeholder="A paragraph or more about yourself" />
          <div style={{ textAlign:'right', fontSize:12, color: remaining < 0 ? 'oklch(50% 0.18 25)' : 'oklch(55% 0.03 265)', marginTop:4 }}>{remaining} characters remaining</div>
        </BIV2Field>
      </div>
      {error && <div style={biv2ErrorBox}>{error}</div>}
      <BIV2NavBar onBack={() => setStep(3)} onNext={onNext} nextLabel="Save & continue" busy={busy || uploading} />
    </div>
  );
};

// =====================================================================
// STEP 5 — Agreement (signature).
// =====================================================================
const BIV2Agreement = ({ progress, config, agreement, advance, setStep, instructorRow, isMobile }) => {
  const copy = config['step.agreement'] || {};
  const [c1, setC1] = React.useState(!!progress?.agreement_signed_at);
  const [c2, setC2] = React.useState(!!progress?.agreement_signed_at);
  const [c3, setC3] = React.useState(!!progress?.agreement_signed_at);

  const initial = (instructorRow.full_name || '').split(/\s+/);
  const [first, setFirst] = React.useState(progress?.signature_legal_first || initial[0] || '');
  const [last, setLast]   = React.useState(progress?.signature_legal_last  || initial.slice(1).join(' ') || '');

  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);

  const onNext = async () => {
    setError(null);
    if (!c1 || !c2 || !c3) { setError('Please confirm all three statements to sign.'); return; }
    if (!first.trim() || !last.trim()) { setError('Type your legal first and last name to sign.'); return; }
    setBusy(true);
    try {
      const { error: e } = await window.supa.rpc('signup_sign_agreement', { p_legal_first: first.trim(), p_legal_last: last.trim() });
      if (e) throw e;
      await advance();
      setStep(6);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not sign') : e.message);
    } finally { setBusy(false); }
  };

  return (
    <div>
      <h1 style={biv2H1}>{copy.title || 'Agreement and terms for tutoring'}</h1>
      <p style={biv2Sub}>{copy.subtitle}</p>
      <div style={{ background:'#fff', border:'1px solid oklch(94% 0.01 265)', borderRadius:12, padding: isMobile ? 18 : 28, marginTop:22 }}>
        <div style={{ maxHeight:300, overflowY:'auto', border:'1px solid oklch(94% 0.01 265)', borderRadius:8, padding:16, background:'oklch(99% 0.005 265)', fontSize:13, lineHeight:1.6, color:'oklch(28% 0.04 265)', whiteSpace:'pre-wrap' }}>
          {agreement?.body || 'Agreement text not configured.'}
        </div>
        <div style={{ marginTop:22, display:'grid', gap:10 }}>
          <label style={biv2CheckLabel}>
            <input type="checkbox" checked={c1} onChange={e=>setC1(e.target.checked)} style={{ marginTop:3, marginRight:10 }} />
            <span>{copy.consent_main}</span>
          </label>
          <label style={biv2CheckLabel}>
            <input type="checkbox" checked={c2} onChange={e=>setC2(e.target.checked)} style={{ marginTop:3, marginRight:10 }} />
            <span>{copy.consent_tou}</span>
          </label>
          <label style={biv2CheckLabel}>
            <input type="checkbox" checked={c3} onChange={e=>setC3(e.target.checked)} style={{ marginTop:3, marginRight:10 }} />
            <span>{copy.consent_legal}</span>
          </label>
        </div>
        <div style={{ marginTop:24 }}>
          <p style={{ fontSize:13, color:'oklch(40% 0.04 265)', marginBottom:10 }}>The following is your digital signature. Please use your legal name.</p>
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap:12 }}>
            <BIV2Field label="Legal first name"><input value={first} onChange={e=>setFirst(e.target.value)} style={biv2Input} required /></BIV2Field>
            <BIV2Field label="Legal last name"><input value={last} onChange={e=>setLast(e.target.value)} style={biv2Input} required /></BIV2Field>
          </div>
        </div>
      </div>
      {error && <div style={biv2ErrorBox}>{error}</div>}
      <BIV2NavBar onBack={() => setStep(4)} onNext={onNext} nextLabel="Save & continue" busy={busy} />
    </div>
  );
};

// =====================================================================
// STEP 6 — Review & submit.
// =====================================================================
const BIV2Review = ({ progress, config, instructorRow, categories, agreement, advance, setStep, isMobile }) => {
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const subjectNames = (categories || []).flatMap(c => c.subjects.filter(s => (progress?.subjects_picked || []).includes(s.id)).map(s => s.name));

  const onSubmit = async () => {
    setError(null);
    setBusy(true);
    try {
      const { error: e } = await window.supa.rpc('signup_submit_for_review');
      if (e) throw e;
      await advance();
      setStep(7);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e, 'Could not submit') : e.message);
    } finally { setBusy(false); }
  };

  return (
    <div>
      <h1 style={biv2H1}>Review and submit</h1>
      <p style={biv2Sub}>Take a moment to confirm everything's right. You can jump back to any step from the progress bar above.</p>
      <div style={{ background:'#fff', border:'1px solid oklch(94% 0.01 265)', borderRadius:12, padding: isMobile ? 18 : 28, marginTop:22, display:'grid', gap:18 }}>
        <ReviewRow label="Subjects" onEdit={() => setStep(1)} value={subjectNames.join(' · ') || '(none)'} />
        <ReviewRow label="How Coaching Works" onEdit={() => setStep(2)} value="Completed quiz" />
        <ReviewRow label="Basic information" onEdit={() => setStep(3)} value={[
          instructorRow.address_city, instructorRow.address_state, instructorRow.address_zip
        ].filter(Boolean).join(', ') + ` · $${instructorRow.rate}/hr`} />
        <ReviewRow label="Profile" onEdit={() => setStep(4)} value={instructorRow.profile_headline || '(no headline)'} />
        <ReviewRow label="Agreement" onEdit={() => setStep(5)} value={progress?.signature_legal_first ? `Signed as ${progress.signature_legal_first} ${progress.signature_legal_last}` : '(not signed)'} />
      </div>
      {error && <div style={biv2ErrorBox}>{error}</div>}
      <BIV2NavBar onBack={() => setStep(5)} onNext={onSubmit} nextLabel="Submit for review →" busy={busy} />
    </div>
  );
};

const ReviewRow = ({ label, value, onEdit }) => (
  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:14, borderBottom:'1px solid oklch(96% 0.008 265)', paddingBottom:14 }}>
    <div>
      <div style={{ fontSize:12, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.06em', color:'oklch(45% 0.06 265)', marginBottom:4 }}>{label}</div>
      <div style={{ fontSize:14, color:'oklch(28% 0.04 265)' }}>{value}</div>
    </div>
    <button type="button" onClick={onEdit} style={{ background:'none', border:'1px solid oklch(85% 0.02 265)', borderRadius:6, padding:'5px 14px', cursor:'pointer', fontSize:12, fontWeight:600, color:'oklch(45% 0.13 265)' }}>Edit</button>
  </div>
);

// =====================================================================
// STEP 7 — Confirmation (after submit).
// =====================================================================
const BIV2Confirmation = ({ config, setPage, instructorRow, progress, categories, isMobile, setStep }) => {
  const copy = config['step.confirmation'] || {};
  const subjectNames = (categories || []).flatMap(c =>
    c.subjects.filter(s => (progress?.subjects_picked || []).includes(s.id))
              .map(s => `${c.name} → ${s.name}`));
  const submittedAt = progress?.submitted_at ? new Date(progress.submitted_at).toLocaleString() : null;
  return (
    <div style={{ padding: isMobile ? '20px 4px' : '20px 0' }}>
      <div style={{ textAlign:'center', padding:'24px 20px' }}>
        <div style={{ fontSize:60, marginBottom:10 }}>✅</div>
        <h1 style={{ ...biv2H1, textAlign:'center' }}>{copy.title || 'Profile submitted for review'}</h1>
        <p style={{ ...biv2Sub, textAlign:'center', maxWidth:560, margin:'14px auto 18px' }}>{copy.subtitle}</p>
        {submittedAt && (
          <p style={{ fontSize:12, color:'oklch(55% 0.03 265)', margin:'0 0 24px' }}>Submitted {submittedAt}</p>
        )}
      </div>
      <div style={{ background:'#fff', border:'1px solid oklch(94% 0.01 265)', borderRadius:12, padding: isMobile ? 18 : 28, marginBottom:24 }}>
        <div style={{ fontSize:13, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'oklch(45% 0.06 265)', marginBottom:14 }}>What you submitted</div>
        {instructorRow?.photo_url && (
          <img src={instructorRow.photo_url} alt="" style={{ width:80, height:80, borderRadius:'50%', objectFit:'cover', border:'2px solid oklch(90% 0.01 265)', marginBottom:14 }} />
        )}
        <BIV2ConfRow label="Name" value={instructorRow?.full_name} />
        <BIV2ConfRow label="Headline" value={instructorRow?.profile_headline} />
        <BIV2ConfRow label="Free response" value={instructorRow?.free_response || instructorRow?.bio} multiline />
        <BIV2ConfRow label="Subjects" value={subjectNames.length ? subjectNames.join(' · ') : '(none)'} />
        <BIV2ConfRow label="Address" value={[
          instructorRow?.address_line1, instructorRow?.address_line2,
          instructorRow?.address_city, instructorRow?.address_state, instructorRow?.address_zip
        ].filter(Boolean).join(', ')} />
        <BIV2ConfRow label="Phone" value={instructorRow?.phone} />
        <BIV2ConfRow label="Hourly rate" value={instructorRow?.rate ? `$${instructorRow.rate}/hr` : null} />
        <BIV2ConfRow label="Education" value={[
          instructorRow?.undergrad_college && `${instructorRow.undergrad_college}${instructorRow.undergrad_major ? ` (${instructorRow.undergrad_major})` : ''}`,
          instructorRow?.grad_college_1 && `${instructorRow.grad_college_1}${instructorRow.grad_degree_1 ? ` (${instructorRow.grad_degree_1})` : ''}`,
          instructorRow?.grad_college_2 && `${instructorRow.grad_college_2}${instructorRow.grad_degree_2 ? ` (${instructorRow.grad_degree_2})` : ''}`,
          instructorRow?.teaching_certification && `Cert: ${instructorRow.teaching_certification}`,
        ].filter(Boolean).join(' · ')} />
        <BIV2ConfRow label="Agreement signed by"
          value={progress?.signature_legal_first ? `${progress.signature_legal_first} ${progress.signature_legal_last || ''}` : null} last />
      </div>
      <div style={{ textAlign:'center', display:'flex', flexDirection: isMobile ? 'column' : 'row', justifyContent:'center', alignItems:'center', gap:10, flexWrap:'wrap' }}>
        <button onClick={() => setStep && setStep(1)} style={{
          background:'#fff', color:'oklch(28% 0.05 265)', border:'1.5px solid oklch(80% 0.02 265)', borderRadius:10,
          padding:'14px 22px', fontWeight:600, fontSize:14, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif",
        }}>Edit my application</button>
        <button onClick={() => setPage('instructor-portal')} style={{
          background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius:10,
          padding:'14px 28px', fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif",
        }}>Back to dashboard →</button>
      </div>
      <p style={{ fontSize:12, color:'oklch(55% 0.03 265)', textAlign:'center', marginTop:14, lineHeight:1.6 }}>
        You can keep editing your application while it's under review. We'll review the latest version when we get to you.
      </p>
    </div>
  );
};

const BIV2ConfRow = ({ label, value, multiline, last }) => (
  <div style={{ display:'flex', gap:14, padding:'10px 0', borderBottom: last ? 'none' : '1px solid oklch(96% 0.008 265)' }}>
    <div style={{ flex:'0 0 140px', fontSize:12, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.04em', color:'oklch(45% 0.06 265)' }}>{label}</div>
    <div style={{ flex:1, fontSize:14, color:'oklch(22% 0.04 265)', lineHeight:1.55, whiteSpace: multiline ? 'pre-wrap' : 'normal', wordBreak:'break-word' }}>{value || <span style={{ color:'oklch(60% 0.02 265)', fontStyle:'italic' }}>—</span>}</div>
  </div>
);

// =====================================================================
// Shared bits.
// =====================================================================


Object.assign(window, {
  BIV2Subjects, BIV2HowItWorks, BIV2BasicInfo, BIV2Profile, BIV2Agreement,
  BIV2Review, BIV2Confirmation, ReviewRow, BIV2ConfRow,
});


Object.assign(window, {
  BIV2Profile, BIV2Agreement, BIV2Review, ReviewRow,
  BIV2Confirmation, BIV2ConfRow,
});
