/* Multi-step signup:
   1) Credentials (email, password, repeat, agree to terms)
   2) Email verification code
   3) Application form (markup provided later — placeholder for now)
   Visual only; advancing is client-side. */

function SignupField({ label, type = 'text', placeholder, autoComplete, value, onChange, suffix, error }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ fontSize: 'var(--text-sm)', fontWeight: 500, color: 'var(--text-primary)' }}>{label}</span>
      <span style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
        <input type={type} placeholder={placeholder} autoComplete={autoComplete} value={value} onChange={onChange} className="bm-input"
          style={{ width: '100%', height: 48, padding: suffix ? '0 48px 0 14px' : '0 14px', fontSize: 'var(--text-base)', fontFamily: 'var(--font-sans)', color: 'var(--text-primary)', background: 'var(--neutral-25)', border: `1px solid ${error ? 'var(--border-error, #e5484d)' : 'var(--border-default)'}`, borderRadius: 'var(--radius-md)', outline: 'none', transition: 'border-color 160ms, box-shadow 160ms, background 160ms' }} />
        {suffix}
      </span>
      {error && <span style={{ fontSize: 'var(--text-xs)', color: 'var(--red-500, #e5484d)' }}>{error}</span>}
    </label>
  );
}

function Stepper({ step }) {
  const labels = ['Account', 'Verify', 'Application'];
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 28 }}>
      {labels.map((l, i) => {
        const done = i < step, active = i === step;
        return (
          <React.Fragment key={l}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
              <span className="tnum mono" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 24, height: 24, borderRadius: '50%', fontSize: 'var(--text-2xs)', fontWeight: 600, background: done ? 'var(--blue-500)' : active ? 'var(--accent-subtle)' : 'var(--neutral-100)', color: done ? '#fff' : active ? 'var(--blue-600)' : 'var(--text-tertiary)', border: active ? '1px solid var(--accent-border)' : 'none' }}>
                {done ? <Icon name="check" size={13} color="#fff" /> : i + 1}
              </span>
              <span style={{ fontSize: 'var(--text-xs)', fontWeight: 600, color: active ? 'var(--text-primary)' : 'var(--text-tertiary)' }}>{l}</span>
            </span>
            {i < labels.length - 1 && <span style={{ flex: 1, height: 1, background: 'var(--border-subtle)', minWidth: 14 }} />}
          </React.Fragment>
        );
      })}
    </div>
  );
}

function VerifyCode({ email, onBack, onDone }) {
  const { Button } = window.BunkermeDesignSystem_9754f2;
  const [code, setCode] = React.useState(Array(6).fill(''));
  const refs = React.useRef([]);
  const set = (i, v) => {
    if (!/^\d?$/.test(v)) return;
    const next = [...code]; next[i] = v; setCode(next);
    if (v && i < 5) refs.current[i + 1] && refs.current[i + 1].focus();
  };
  const onKey = (i, e) => { if (e.key === 'Backspace' && !code[i] && i > 0) refs.current[i - 1] && refs.current[i - 1].focus(); };
  const complete = code.every((c) => c !== '');
  return (
    <form onSubmit={(e) => { e.preventDefault(); onDone(); }} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
      <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)' }}>
        We sent a 6-digit code to <span style={{ color: 'var(--text-primary)', fontWeight: 600 }}>{email || 'your email'}</span>. Enter it below to verify.
      </p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10 }}>
        {code.map((c, i) => (
          <input key={i} ref={(el) => { refs.current[i] = el; }} value={c} inputMode="numeric" maxLength={1}
            onChange={(e) => set(i, e.target.value)} onKeyDown={(e) => onKey(i, e)} className="bm-input"
            style={{ width: '100%', minWidth: 0, height: 56, textAlign: 'center', fontSize: 'var(--text-h4)', fontWeight: 600, fontFamily: 'var(--font-mono)', color: 'var(--text-primary)', background: 'var(--neutral-25)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', outline: 'none', transition: 'border-color 160ms, box-shadow 160ms' }} />
        ))}
      </div>
      <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-tertiary)' }}>
        Didn’t get it? <a href="#" onClick={(e) => e.preventDefault()} style={{ color: 'var(--blue-600)', fontWeight: 600 }}>Resend code</a>
      </div>
      <Button variant="primary" size="lg" type="submit" fullWidth disabled={!complete} iconRight={<Icon name="arrow-right" size={18} color="#fff" />}>Verify email</Button>
      <button type="button" onClick={onBack} style={{ alignSelf: 'center', background: 'none', border: 'none', cursor: 'pointer', fontSize: 'var(--text-sm)', color: 'var(--text-tertiary)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <Icon name="arrow-left" size={15} color="currentColor" /> Back
      </button>
    </form>
  );
}

function ApplicationPlaceholder() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 16, padding: '20px 0 8px' }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 56, height: 56, borderRadius: '50%', background: 'var(--success-subtle)', color: 'var(--green-600)' }}>
        <Icon name="check" size={26} color="var(--green-600)" />
      </span>
      <h2 style={{ fontSize: 'var(--text-h3)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)' }}>Email verified</h2>
      <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)', maxWidth: 340 }}>
        Next, complete your fleet application so we can set up credit and delivery — about 10 minutes, and you can resume anytime.
      </p>
      <a href="application.html" style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 'var(--text-sm)', fontWeight: 600, color: '#fff', background: 'var(--blue-500)', borderRadius: 'var(--radius-md)', padding: '12px 22px', marginTop: 4 }}>
        Start application <Icon name="arrow-right" size={16} color="#fff" />
      </a>
    </div>
  );
}

function Signup() {
  const { Button, Checkbox } = window.BunkermeDesignSystem_9754f2;
  const [step, setStep] = React.useState(0);
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [agree, setAgree] = React.useState(false);
  const [showPw, setShowPw] = React.useState(false);
  const [err, setErr] = React.useState('');

  const submitCreds = async (e) => {
    e.preventDefault();
    if (pw.length < 8) { setErr('Password must be at least 8 characters.'); return; }
    if (pw !== pw2) { setErr('Passwords don’t match.'); return; }
    try { localStorage.setItem('bm_signup_email', email); } catch (_) {}
    try { if (window.BunkermeAuth) await window.BunkermeAuth.register(email, pw); } catch (_) {}
    setErr(''); setStep(1);
  };

  const pwToggle = (
    <button type="button" onClick={() => setShowPw((s) => !s)} aria-label="Toggle password visibility"
      style={{ position: 'absolute', right: 6, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 36, height: 36, border: 'none', background: 'transparent', color: 'var(--text-tertiary)', cursor: 'pointer', borderRadius: 'var(--radius-sm)' }}>
      <Icon name={showPw ? 'eye-off' : 'eye'} size={18} color="currentColor" />
    </button>
  );

  const titles = [['Open your account', 'Start ordering bunkers and unlock flexible credit.'], ['Verify your email', 'One quick check to secure your account.'], ['You’re verified', 'Let’s finish your application.']];

  return (
    <div style={{ position: 'relative', minHeight: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--surface-page)' }}>
      <div aria-hidden="true" style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 360, pointerEvents: 'none', background: 'radial-gradient(720px 320px at 50% -10%, rgba(12,41,241,0.07), transparent 70%)' }} />

      <header style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '26px 32px' }}>
        <a href="index.html" aria-label="bunkerme home" style={{ display: 'inline-flex' }}><Logo size={28} /></a>
        <a href="login.html" style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-sm)', fontWeight: 600, color: 'var(--text-secondary)', whiteSpace: 'nowrap' }}>
          Log in <Icon name="chevron-right" size={16} color="currentColor" />
        </a>
      </header>

      <div style={{ position: 'relative', flex: 1, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '40px 24px 72px' }}>
        <div style={{ width: '100%', maxWidth: 452, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-2xl)', boxShadow: 'var(--shadow-lg)', padding: '36px 40px 36px' }}>
          <Stepper step={step} />
          <h1 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', marginBottom: 6 }}>{titles[step][0]}</h1>
          <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', marginBottom: 28 }}>{titles[step][1]}</p>

          {step === 0 && (
            <form onSubmit={submitCreds} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
              <SignupField label="Email" type="email" placeholder="you@fleet.com" autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} />
              <SignupField label="Password" type={showPw ? 'text' : 'password'} placeholder="At least 8 characters" autoComplete="new-password" value={pw} onChange={(e) => setPw(e.target.value)} suffix={pwToggle} />
              <SignupField label="Repeat password" type={showPw ? 'text' : 'password'} placeholder="Re-enter your password" autoComplete="new-password" value={pw2} onChange={(e) => setPw2(e.target.value)} error={err} />
              <div style={{ marginTop: 2 }}>
                <Checkbox checked={agree} onChange={(e) => setAgree(e.target.checked ?? !agree)}
                  label={<span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>I agree to the <a href="#" style={{ color: 'var(--blue-600)' }}>Terms</a> and <a href="#" style={{ color: 'var(--blue-600)' }}>Privacy Policy</a>.</span>} />
              </div>
              <Button variant="primary" size="lg" type="submit" fullWidth disabled={!agree} iconRight={<Icon name="arrow-right" size={18} color="#fff" />}>Continue</Button>
            </form>
          )}

          {step === 1 && <VerifyCode email={email} onBack={() => setStep(0)} onDone={() => setStep(2)} />}
          {step === 2 && <ApplicationPlaceholder />}
        </div>
      </div>

      <style>{`
        .bm-input:focus{ border-color: var(--border-focus); box-shadow: var(--ring-accent); background: var(--surface-card); }
        .bm-input::placeholder{ color: var(--text-tertiary); }
      `}</style>
    </div>
  );
}

Object.assign(window, { Signup });
