// src/features/instructor/ui/become-instructor-v2-account.jsx
//
// The account-create step that runs before the multi-step wizard, PLUS the
// instructor login — both presented as two cards behind one persistent
// [Create account | Log in] toggle so a returning instructor can flip between
// them with a single click (login no longer routes off to a different-looking
// full-page screen).
//
// Public on window: BIV2AccountCreate.
// Depends on (via window): BIV2Field, biv2Input, biv2ErrorBox.

const { BIV2Field, biv2Input, biv2ErrorBox } = window;

const BIV2AccountCreate = ({ setPage }) => {
  const isMobile = window.useIsMobile();
  const captcha = window.useCaptcha ? window.useCaptcha() : { token: null, widget: null, required: false };

  // Which card is showing. Initial view honors (in order): a one-shot window
  // flag set by the hero "I already teach here" button; ?view=login; or the
  // /instructor-login clean URL. Defaults to the create-account form.
  const [view, setView] = React.useState(() => {
    try {
      if (window.__BIV2_INITIAL_VIEW === 'login') { window.__BIV2_INITIAL_VIEW = null; return 'login'; }
      const sp = new URLSearchParams(window.location.search);
      if (sp.get('view') === 'login') return 'login';
      if ((window.location.pathname || '').replace(/\/+$/, '') === '/instructor-login') return 'login';
    } catch (_) {}
    return 'create';
  });

  // Create-account form
  const [firstName, setFirstName] = React.useState('');
  const [lastName,  setLastName]  = React.useState('');
  const [email, setEmail]         = React.useState('');
  const [password, setPassword]   = React.useState('');
  const [zip, setZip]             = React.useState('');
  const [attest, setAttest]       = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  // Once signup succeeds we show a "check your email" screen instead of
  // letting the form submit again. Without this the form silently stays
  // in place (auth.user doesn't populate until they click the email
  // link), the user clicks Submit again, and the now-consumed captcha
  // token triggers "already-seen-response".
  const [submittedEmail, setSubmittedEmail] = React.useState(null);

  // Login form (magic link — same flow as the standalone instructor login)
  const [loginEmail, setLoginEmail] = React.useState('');
  const [loginErr,   setLoginErr]   = React.useState('');
  const [loginBusy,  setLoginBusy]  = React.useState(false);
  const [loginSent,  setLoginSent]  = React.useState(false);

  // Keep the URL shareable: /for-instructors for create, /instructor-login for
  // login (both single-segment so the relative .jsx script tags still resolve
  // from root). Best-effort only — never let a history hiccup break the page.
  const syncUrl = (v) => {
    try { window.history.replaceState({}, '', (v === 'login' ? '/instructor-login' : '/for-instructors') + (window.location.hash || '')); }
    catch (_) {}
  };
  const switchView = (v) => { setView(v); setError(null); setLoginErr(''); syncUrl(v); };
  // If we mounted straight into login (hero deep-link / clean URL), reflect that
  // in the address bar so the link a teacher copies points back to login.
  React.useEffect(() => { if (view === 'login') syncUrl('login'); }, []); // eslint-disable-line react-hooks/exhaustive-deps

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!firstName || !lastName || !email || !password || !zip) {
      setError('Please fill in every field to continue.');
      return;
    }
    if (password.length < 6) {
      setError('Password must be at least 6 characters.');
      return;
    }
    if (!/^\d{5}$/.test(zip)) {
      setError('Please enter a 5-digit ZIP code.');
      return;
    }
    if (!attest) {
      setError('Please confirm you have a Social Security Number and reside in the United States.');
      return;
    }
    if (captcha.required) { setError('Please complete the captcha.'); return; }

    setBusy(true);
    try {
      const fullName = `${firstName.trim()} ${lastName.trim()}`;
      const { error: e2, pendingEmailConfirm } = await window.AUTH.signUpInstructor({
        email, password, fullName,
        city: 'New York', state: 'NY',             // placeholders, overridden in step 3
        subject: 'Piano',                          // legacy placeholder, overridden in step 1
        topics: [],
        category: 'music',
        specialties: [],
        bio: '',
        rate: 0,
        experience: 0,
        badges: [],
        captchaToken: captcha.token,
      });
      // Whatever happened, the captcha token has now been consumed by
      // Supabase Auth. Reset the widget so any retry uses a fresh one.
      captcha.reset && captcha.reset();
      if (e2) {
        const code = e2.code || e2.statusCode || '';
        const raw  = e2.message || String(e2);
        const friendly = window.friendlyError ? window.friendlyError(e2, 'Could not create account') : raw;
        setError(`${friendly}${code ? ` (code ${code})` : ''}`);
        return;
      }
      // With mailer_autoconfirm = true on Supabase, signUp returns a
      // session immediately — auth.user populates, this component
      // re-renders, and the BIV2 wizard mounts. No "check your email"
      // screen needed. We still handle pendingEmailConfirm as a
      // belt-and-suspenders fallback in case admin ever flips
      // confirmation back on.
      await window.SITE_DATA?.refresh?.();
      if (pendingEmailConfirm) setSubmittedEmail(email);
      // Otherwise: do nothing — the page rerenders into the wizard.
    } catch (e) {
      captcha.reset && captcha.reset();
      const code = e.code || e.statusCode || '';
      setError((window.friendlyError ? window.friendlyError(e, 'Could not create account') : (e.message || String(e))) + (code ? ` (code ${code})` : ''));
    } finally {
      setBusy(false);
    }
  };

  const loginSubmit = async (e) => {
    e.preventDefault();
    if (captcha.required) { setLoginErr('Please complete the captcha.'); return; }
    setLoginErr(''); setLoginBusy(true);
    try {
      const { error } = await window.AUTH.sendMagicLink({ email: loginEmail.trim(), captchaToken: captcha.token });
      // hCaptcha tokens are single-use — refresh after each attempt so a retry
      // (e.g. after a typo'd email) gets a fresh challenge.
      captcha.reset && captcha.reset();
      if (error) { setLoginErr(error.message || "Couldn't send the login link."); return; }
      setLoginSent(true);
    } catch (err) {
      captcha.reset && captcha.reset();
      setLoginErr(err.message || String(err));
    } finally { setLoginBusy(false); }
  };

  // Fallback "Check your email" screen — only used if Supabase email
  // confirmation gets flipped back on later. With the current
  // mailer_autoconfirm = true setting this branch never fires.
  if (submittedEmail) {
    return (
      <div style={{ background:'oklch(98% 0.008 60)', minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', padding:'40px 24px', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
        <div style={{ maxWidth: 480, width:'100%', textAlign:'center', background:'#fff', border:'1px solid oklch(90% 0.01 265)', borderRadius:18, padding:'48px 36px', boxShadow:'0 4px 24px rgba(0,0,0,0.06)' }}>
          <div style={{ fontSize: 44, marginBottom: 18 }}>📧</div>
          <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize: 28, fontWeight: 700, color:'oklch(20% 0.04 265)', marginBottom: 12 }}>Check your email</h2>
          <p style={{ fontSize: 15, color:'oklch(40% 0.04 265)', lineHeight: 1.6, marginBottom: 24 }}>
            We sent a confirmation link to <strong>{submittedEmail}</strong>. Click it to log in and finish setting up your instructor profile.
          </p>
          <button onClick={() => setPage('home')}
            style={{ background:'oklch(22% 0.06 265)', color:'#fff', border:'none', borderRadius: 10, padding: '12px 28px', fontWeight: 600, fontSize: 14, cursor:'pointer', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
            Back to home
          </button>
        </div>
      </div>
    );
  }

  const tabBtn = (active) => ({
    flex:1, padding:'11px 10px', borderRadius:8, border:'none',
    background: active ? '#fff' : 'none',
    color: active ? 'oklch(22% 0.06 265)' : 'oklch(42% 0.05 265)',
    fontWeight: active ? 700 : 600, fontSize:14, cursor: active ? 'default' : 'pointer',
    boxShadow: active ? '0 1px 5px rgba(0,0,0,0.07)' : 'none',
    fontFamily:"'Plus Jakarta Sans', sans-serif",
  });

  return (
    <div style={{ background:'oklch(98% 0.008 60)', minHeight:'100vh' }}>
      <button onClick={() => setPage('home')} aria-label="Close"
        style={{ position:'fixed', top:18, right:18, width:42, height:42, borderRadius:'50%', background:'rgba(255,255,255,0.92)', border:'1px solid oklch(88% 0.02 265)', cursor:'pointer', fontSize:20, color:'oklch(28% 0.05 265)', zIndex:100, boxShadow:'0 2px 10px rgba(0,0,0,0.08)' }}>×</button>

      <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1.05fr 1fr', minHeight:'100vh' }}>
        <section style={{ background:'oklch(20% 0.065 265)', color:'#fff', padding: isMobile ? '60px 22px 40px' : '90px 80px' }}>
          <p style={{ fontSize:12, fontWeight:700, letterSpacing:'0.14em', color:'oklch(72% 0.17 80)', textTransform:'uppercase', marginBottom:14 }}>For Instructors</p>
          <h1 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize: isMobile ? 34 : 48, fontWeight:600, lineHeight:1.05, marginBottom:18 }}>
            Coaching Connects Experts with Students Looking for 1-to-1 Instruction
          </h1>
          <p style={{ fontSize: isMobile ? 15 : 16, color:'rgba(255,255,255,0.75)', lineHeight:1.6, marginBottom:30 }}>
            Set your own schedule, your own rate, and connect with students who genuinely want to learn from you.
          </p>
          <ul style={{ listStyle:'none', padding:0, margin:0, display:'grid', gap:18 }}>
            {[
              ['Select Your Students', 'Find the best fit for your location and schedule, in person or online.'],
              ['Set Your Rate', 'Earn what you deserve for your qualifications and experience.'],
              ['Get Paid, Hassle-Free', 'Set up direct deposit for quick and secure payment.'],
            ].map(([t, d]) => (
              <li key={t} style={{ display:'flex', gap:14 }}>
                <span style={{ width:34, height:34, borderRadius:8, background:'rgba(255,255,255,0.1)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>✓</span>
                <div>
                  <div style={{ fontWeight:700, marginBottom:3 }}>{t}</div>
                  <div style={{ fontSize:13, color:'rgba(255,255,255,0.65)', lineHeight:1.5 }}>{d}</div>
                </div>
              </li>
            ))}
          </ul>
        </section>

        <section style={{ background:'#fff', padding: isMobile ? '34px 22px' : '70px 56px', display:'flex', flexDirection:'column', justifyContent:'center' }}>
          {/* One persistent toggle for both cards. Whichever is active shows its
              card below; the other is a single click away — so a returning
              instructor never gets stranded on a separate login page. */}
          <div style={{ display:'flex', gap:6, background:'oklch(96% 0.008 265)', border:'1px solid oklch(90% 0.012 265)', borderRadius:12, padding:5, marginBottom:26, width:'100%', maxWidth:420, marginLeft:'auto', marginRight:'auto' }}>
            <button type="button" aria-pressed={view === 'create'} onClick={() => switchView('create')} style={tabBtn(view === 'create')}>
              Create account
            </button>
            <button type="button" aria-pressed={view === 'login'} onClick={() => switchView('login')} style={tabBtn(view === 'login')}>
              Log in
            </button>
          </div>

          {view === 'create' ? (
            <>
              <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize: isMobile ? 28 : 32, fontWeight:600, color:'oklch(22% 0.06 265)', marginBottom:6, textAlign:'center' }}>Create a new account</h2>
              <p style={{ textAlign:'center', fontSize:14, color:'oklch(50% 0.03 265)', marginBottom:28 }}>Apply to be listed on Coaching and start finding students looking for help in your subjects.</p>
              <form onSubmit={submit}>
                <BIV2Field label="First Name (visible publicly)">
                  <input value={firstName} onChange={e=>setFirstName(e.target.value)} style={biv2Input} required autoComplete="given-name" />
                </BIV2Field>
                <BIV2Field label="Last Name">
                  <input value={lastName} onChange={e=>setLastName(e.target.value)} style={biv2Input} required autoComplete="family-name" />
                </BIV2Field>
                <BIV2Field label="Email Address">
                  <input type="email" value={email} onChange={e=>setEmail(e.target.value)} style={biv2Input} required autoComplete="email" />
                </BIV2Field>
                <BIV2Field label="Create Password">
                  <input type="password" minLength={6} value={password} onChange={e=>setPassword(e.target.value)} style={biv2Input} required autoComplete="new-password" />
                </BIV2Field>
                <BIV2Field label="ZIP Code">
                  <input value={zip} onChange={e=>setZip(e.target.value.replace(/\D/g,'').slice(0,5))} style={{...biv2Input, maxWidth:160}} inputMode="numeric" required />
                </BIV2Field>

                <p style={{ fontSize:12.5, color:'oklch(40% 0.03 265)', margin:'14px 0 10px', lineHeight:1.55 }}>
                  <strong>Important:</strong> Tutors listed on Coaching must reside within the United States and have a valid Social Security Number, per the Site's Terms of Use.
                </p>
                <label style={{ display:'flex', alignItems:'flex-start', gap:10, fontSize:13.5, color:'oklch(28% 0.04 265)', cursor:'pointer', padding:'10px 12px', background:'oklch(98% 0.005 265)', border:'1px solid oklch(90% 0.01 265)', borderRadius:8, marginBottom:14, lineHeight:1.5 }}>
                  <input type="checkbox" checked={attest} onChange={e=>setAttest(e.target.checked)} style={{ marginTop:2 }} />
                  <span>I have a Social Security Number and I reside within the United States.</span>
                </label>

                {captcha.widget}
                {error && <div style={biv2ErrorBox}>{error}</div>}

                <button type="submit" disabled={busy || captcha.required} style={{
                  width:'100%', background:'oklch(72% 0.17 80)', color:'#000', border:'none', borderRadius:10,
                  padding:'14px 0', fontWeight:700, fontSize:15, cursor: busy ? 'wait' : 'pointer',
                  fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: busy ? 0.7 : 1,
                }}>{busy ? 'Creating account…' : 'Next →'}</button>
              </form>
            </>
          ) : (
            <>
              <h2 style={{ fontFamily:"'Cormorant Garamond', serif", fontSize: isMobile ? 28 : 32, fontWeight:600, color:'oklch(22% 0.06 265)', marginBottom:6, textAlign:'center' }}>Log in to your account</h2>
              <p style={{ textAlign:'center', fontSize:14, color:'oklch(50% 0.03 265)', marginBottom:28 }}>Welcome back. We'll email you a secure link to sign in — no password needed.</p>
              {loginSent ? (
                <div style={{ textAlign:'center', padding:'12px 4px' }}>
                  <div style={{ fontSize:40, marginBottom:14 }}>📧</div>
                  <p style={{ fontSize:14.5, color:'oklch(38% 0.04 265)', lineHeight:1.7, marginBottom:20 }}>
                    Check your inbox at <strong>{loginEmail}</strong>. Click the link to sign in — this tab will update automatically.
                  </p>
                  <button type="button" onClick={() => { setLoginSent(false); setLoginErr(''); }}
                    style={{ background:'none', border:'none', color:'oklch(48% 0.18 265)', fontWeight:700, fontSize:13.5, cursor:'pointer', textDecoration:'underline', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
                    Use a different email
                  </button>
                </div>
              ) : (
                <form onSubmit={loginSubmit}>
                  <BIV2Field label="Email Address">
                    <input type="email" value={loginEmail} onChange={e=>{ setLoginEmail(e.target.value); setLoginErr(''); }} style={biv2Input} required autoComplete="email" autoFocus />
                  </BIV2Field>

                  {captcha.widget}
                  {loginErr && <div style={biv2ErrorBox}>{loginErr}</div>}

                  <button type="submit" disabled={loginBusy || !loginEmail.includes('@') || captcha.required} style={{
                    width:'100%', background:'oklch(72% 0.17 80)', color:'#000', border:'none', borderRadius:10,
                    padding:'14px 0', fontWeight:700, fontSize:15, cursor: loginBusy ? 'wait' : 'pointer',
                    fontFamily:"'Plus Jakarta Sans', sans-serif", opacity: (loginBusy || captcha.required) ? 0.7 : 1,
                  }}>{loginBusy ? 'Sending…' : '📧 Send magic link'}</button>

                  <p style={{ textAlign:'center', fontSize:13, color:'oklch(52% 0.03 265)', marginTop:16 }}>
                    New here?{' '}
                    <button type="button" onClick={() => switchView('create')}
                      style={{ background:'none', border:'none', padding:0, color:'oklch(48% 0.18 265)', cursor:'pointer', fontWeight:700, fontSize:13, textDecoration:'underline', fontFamily:"'Plus Jakarta Sans', sans-serif" }}>
                      Create an account
                    </button>
                  </p>
                </form>
              )}
            </>
          )}
        </section>
      </div>
    </div>
  );
};

// =====================================================================
// Wizard frame: top progress bar + body + sticky footer with nav.
// =====================================================================

window.BIV2AccountCreate = BIV2AccountCreate;
