// instructor-verify.jsx — Admin-triggered tutor identity / payouts verification.
//
// Page entry: ?page=verify (handled by app.jsx). Renders one of:
//   - "not requested" placeholder        (status='not_requested' / no row)
//   - the multi-step wizard              (status='requested'/'in_progress')
//   - "submitted, awaiting review"       (status='submitted')
//   - "rejected — please fix and resubmit" (status='rejected')
//   - "verified ✓"                       (status='approved')
//
// The wizard walks the subset of sections the admin requested (any of
// identity / gov_id / address / bank). Each section calls its RPC on
// "Continue", so partial progress is never lost. Final submission is a
// separate RPC (submit_verification_final) that flips status='submitted'
// and emails the admin.

// Style consts + reusable bits live in instructor-verify-helpers.jsx
// (loaded immediately before this file in index.html). Re-read them
// off window so this file's closures can use them as bare names.
const {
  IV_FIELD_META, IV_NAVY, IV_GOLD, IV_PAPER, IV_BORDER, IV_MUTED, IV_INK,
  IV_INPUT_STYLE,
  IVStepRail,
} = window;


const InstructorVerifyPage = ({ setPage }) => {
  const auth = window.useAuth();
  const isMobile = window.useIsMobile();
  const [iv, setIv]         = React.useState(null);
  const [loading, setLoad]  = React.useState(true);
  const [stepKey, setStep]  = React.useState('welcome');  // 'welcome' | 'identity' | 'gov_id' | 'address' | 'bank' | 'review'
  const [busy, setBusy]     = React.useState(false);
  const [error, setError]   = React.useState(null);

  // Resolve instructor row + verification record.
  const reload = React.useCallback(async () => {
    if (!auth.user) return;
    setLoad(true);
    try {
      const { data: inst } = await window.supa.from('instructors').select('id').eq('user_id', auth.user.id).maybeSingle();
      if (!inst) { setIv(null); return; }
      const { data: row } = await window.supa.from('instructor_verifications')
        .select('instructor_id, status, requested_fields, admin_message, submitted_at, reviewed_at, rejection_reason, legal_first_name, legal_middle_name, legal_last_name, ssn_last_four, gov_id_type, gov_id_storage_path, address_line1, address_line2, address_city, address_state, address_zip, bank_account_holder_name, bank_account_type, bank_account_last_four, identity_completed_at, gov_id_completed_at, address_completed_at, bank_completed_at')
        .eq('instructor_id', inst.id)
        .maybeSingle();
      setIv(row || { instructor_id: inst.id, status:'not_requested', requested_fields:[] });
    } finally {
      setLoad(false);
    }
  }, [auth.user?.id]);

  React.useEffect(() => { reload(); }, [reload]);

  // Bounce non-instructors to home.
  React.useEffect(() => {
    if (auth.loading) return;
    if (!auth.user) { setPage('home'); return; }
    if (auth.profile && auth.profile.role !== 'instructor' && !auth.isAdmin) { setPage('home'); }
  }, [auth.loading, auth.user?.id, auth.profile?.role, auth.isAdmin, setPage]);

  // Auto-jump to the first incomplete section once iv loads (skips Welcome on return visits).
  const requestedFields = iv?.requested_fields || [];
  const completion = {
    identity: !!iv?.identity_completed_at,
    gov_id:   !!iv?.gov_id_completed_at,
    address:  !!iv?.address_completed_at,
    bank:     !!iv?.bank_completed_at,
  };
  const orderedSections = ['identity','gov_id','address','bank'].filter(f => requestedFields.includes(f));
  const firstIncomplete = orderedSections.find(s => !completion[s]);

  React.useEffect(() => {
    if (loading || !iv) return;
    if (iv.status === 'in_progress' && stepKey === 'welcome') {
      setStep(firstIncomplete || 'review');
    }
  }, [loading, iv?.status]);

  // Save handlers — each calls the matching RPC and refreshes iv.
  const callRpc = async (fn, args, advance) => {
    setBusy(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc(fn, args);
      if (e) throw e;
      await reload();
      if (advance) setStep(advance);
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e) : (e.message || 'Could not save.'));
    } finally { setBusy(false); }
  };

  const nextAfter = (key) => {
    const idx = orderedSections.indexOf(key);
    if (idx === -1) return 'review';
    const next = orderedSections.slice(idx + 1).find(s => !completion[s]);
    return next || 'review';
  };

  const submitIdentity = (v) =>
    callRpc('submit_verification_identity', {
      p_legal_first: v.first, p_legal_middle: v.mid || null, p_legal_last: v.last,
      p_dob: v.dob, p_ssn: v.ssn,
    }, nextAfter('identity'));
  const submitGovId = (v) =>
    callRpc('submit_verification_gov_id', { p_gov_id_type: v.idType, p_storage_path: v.storagePath }, nextAfter('gov_id'));
  const submitAddress = (v) =>
    callRpc('submit_verification_address', { p_line1: v.l1, p_line2: v.l2 || null, p_city: v.city, p_state: v.st, p_zip: v.zip }, nextAfter('address'));
  const submitBank = (v) =>
    callRpc('submit_verification_bank', { p_holder: v.holder, p_account_type: v.acctType, p_routing: v.routing, p_account: v.acct }, nextAfter('bank'));
  const submitFinal = async () => {
    setBusy(true); setError(null);
    try {
      const { error: e } = await window.supa.rpc('submit_verification_final');
      if (e) throw e;
      await reload();
    } catch (e) {
      setError(window.friendlyError ? window.friendlyError(e) : (e.message || 'Could not submit.'));
    } finally { setBusy(false); }
  };

  // ── Render ────────────────────────────────────────────────────────────────
  const goDashboard = () => setPage('dashboard');

  if (loading) {
    return (
      <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background:IV_PAPER, color:IV_MUTED, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        Loading…
      </div>
    );
  }

  // Header (logo + Save & exit) — same for every state.
  const Header = () => (
    <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:isMobile?'14px 18px':'18px 28px', background:'#fff', borderBottom:`1px solid ${IV_BORDER}`, position:'sticky', top:0, zIndex:10 }}>
      <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:18, fontWeight:700, letterSpacing:'0.12em', color:IV_NAVY }}>
        COACHING
      </div>
      <button onClick={goDashboard}
        style={{ background:'none', border:'none', fontSize:13, color:IV_MUTED, cursor:'pointer', fontWeight:600, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        Save & exit ✕
      </button>
    </div>
  );

  // No verification on file yet — admin hasn't triggered.
  if (!iv || iv.status === 'not_requested') {
    return (
      <div style={{ minHeight:'100vh', background:IV_PAPER, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <Header />
        <window.IVEndState
          icon="✓"
          title="You're all set."
          subtitle="There's no verification step pending for your account right now. Coaching will let you know if anything is needed."
          ctaLabel="Back to dashboard"
          onCta={goDashboard}
        />
      </div>
    );
  }

  // Submitted — waiting for admin review.
  if (iv.status === 'submitted') {
    return (
      <div style={{ minHeight:'100vh', background:IV_PAPER, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <Header />
        <window.IVEndState
          icon="⏳"
          title="You're all set."
          subtitle="We'll review your information and confirm within 1–2 business days. We'll email you the moment it's done."
          body={
            <div style={{ textAlign:'left', maxWidth:380, margin:'0 auto', background:'#fff', border:`1px solid ${IV_BORDER}`, borderRadius:12, padding:'18px 20px' }}>
              <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:IV_GOLD, marginBottom:8 }}>What happens next</div>
              <ol style={{ paddingLeft:20, margin:0, fontSize:13, color:'oklch(34% 0.04 265)', lineHeight:1.7 }}>
                <li>Coaching reviews your information (1–2 business days)</li>
                <li>Your verified badge appears on your public profile</li>
                <li>Your first payout is queued for the next pay cycle</li>
              </ol>
            </div>
          }
          ctaLabel="Back to dashboard"
          onCta={goDashboard}
        />
      </div>
    );
  }

  // Approved — show the celebration screen.
  if (iv.status === 'approved') {
    return (
      <div style={{ minHeight:'100vh', background:IV_PAPER, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <Header />
        <window.IVEndState
          icon="✅"
          title="You're verified."
          subtitle="Your Coaching profile is verified — your earnings will be released on the next payout cycle."
          ctaLabel="Open dashboard"
          onCta={goDashboard}
        />
      </div>
    );
  }

  // Rejected — show reason + allow re-edit. We treat 'rejected' similar to
  // 'in_progress' but display the rejection banner up top.
  // The user can click "Continue" which jumps to the first section.
  if (iv.status === 'rejected') {
    return (
      <div style={{ minHeight:'100vh', background:IV_PAPER, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <Header />
        <window.IVEndState
          icon="✏️"
          title="A small fix is needed"
          subtitle={iv.rejection_reason || 'Please review your information and submit again.'}
          body={
            <div style={{ marginTop:10, fontSize:13, color:IV_MUTED }}>
              Nothing on your profile has changed in the meantime. Open the relevant section, fix the issue, and resubmit.
            </div>
          }
          ctaLabel="Update verification →"
          onCta={() => { setStep(firstIncomplete || orderedSections[0] || 'review'); setIv({ ...iv, status:'in_progress' }); }}
        />
      </div>
    );
  }

  // requested / in_progress — wizard.
  const sectionsForRail = orderedSections.map(k => IV_FIELD_META[k]);
  const currentIdx = Math.max(0, orderedSections.indexOf(stepKey));

  const renderStep = () => {
    if (stepKey === 'welcome') {
      return <window.IVWelcomeStep
        requestedFields={requestedFields}
        adminMessage={iv.admin_message}
        onStart={() => setStep(firstIncomplete || orderedSections[0] || 'review')} />;
    }
    if (stepKey === 'identity') {
      return <window.IVIdentityStep initial={iv} onSubmit={submitIdentity}
        onBack={() => setStep('welcome')} busy={busy} error={error} />;
    }
    if (stepKey === 'gov_id') {
      return <window.IVGovIdStep initial={iv} userId={auth.user.id} onSubmit={submitGovId}
        onBack={() => setStep(orderedSections[orderedSections.indexOf('gov_id') - 1] || 'welcome')} busy={busy} error={error} />;
    }
    if (stepKey === 'address') {
      return <window.IVAddressStep initial={iv} onSubmit={submitAddress}
        onBack={() => setStep(orderedSections[orderedSections.indexOf('address') - 1] || 'welcome')} busy={busy} error={error} />;
    }
    if (stepKey === 'bank') {
      return <window.IVBankStep initial={iv} onSubmit={submitBank}
        onBack={() => setStep(orderedSections[orderedSections.indexOf('bank') - 1] || 'welcome')} busy={busy} error={error} />;
    }
    if (stepKey === 'review') {
      return <window.IVReviewStep iv={iv} requestedFields={requestedFields}
        onEdit={(k) => setStep(k)}
        onBack={() => setStep(orderedSections[orderedSections.length - 1] || 'welcome')}
        onSubmit={submitFinal} busy={busy} error={error} />;
    }
    return null;
  };

  // Welcome step has its own layout (no rail) so it can have a hero feel.
  if (stepKey === 'welcome') {
    return (
      <div style={{ minHeight:'100vh', background:IV_PAPER, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <Header />
        <div style={{ maxWidth:560, margin:'0 auto', padding:isMobile?'30px 20px 60px':'56px 20px 80px' }}>
          {renderStep()}
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight:'100vh', background:IV_PAPER, fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
      <Header />
      <div style={{ display:'flex', flexDirection: isMobile ? 'column' : 'row', maxWidth:980, margin:'0 auto', minHeight:'calc(100vh - 60px)', background:'transparent' }}>
        <IVStepRail sections={sectionsForRail} currentIdx={currentIdx} completed={completion} />
        <div style={{ flex:1, padding: isMobile ? '24px 20px 60px' : '40px 48px 60px', maxWidth:640 }}>
          {renderStep()}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { InstructorVerifyPage });
// All helpers + style consts are now published by
// instructor-verify-helpers.jsx (which loads before this file).
