/* Forgot / reset password flow — matches the Auth shell (login/signup).
   Views: 'request' → 'sent'  (email side)  ·  'reset' → 'done'  (from emailed link, ?token=…).
   Visual only; no real requests are sent. */

function ResetField({ label, type = 'text', placeholder, autoComplete, suffix, value, onChange }) {
  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 var(--border-default)', borderRadius: 'var(--radius-md)', outline: 'none', transition: 'border-color 160ms, box-shadow 160ms, background 160ms' }} />
        {suffix}
      </span>
    </label>
  );
}

function BackToLogin() {
  return (
    <a href="login.html" style={{ alignSelf: 'center', display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-sm)', fontWeight: 600, color: 'var(--text-tertiary)' }}>
      <Icon name="arrow-left" size={15} color="currentColor" /> Back to log in
    </a>
  );
}

function ForgotPassword() {
  const { Button } = window.BunkermeDesignSystem_9754f2;
  const params = new URLSearchParams(window.location.search);
  const hasToken = !!params.get('token');
  const presetEmail = params.get('email') ? decodeURIComponent(params.get('email')) : '';

  const [view, setView] = React.useState(hasToken ? 'reset' : 'request');
  const [email, setEmail] = React.useState(presetEmail);
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [showPw, setShowPw] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [cooldown, setCooldown] = React.useState(0);
  const [resent, setResent] = React.useState(false);

  React.useEffect(() => {
    if (cooldown <= 0) return;
    const t = setTimeout(() => setCooldown((c) => c - 1), 1000);
    return () => clearTimeout(t);
  }, [cooldown]);

  const resend = () => { if (cooldown > 0) return; setResent(true); setCooldown(30); };

  const submitRequest = (e) => { e.preventDefault(); if (!email.trim()) { setErr('Enter your email address.'); return; } setErr(''); setResent(false); setCooldown(30); setView('sent'); };
  const submitReset = (e) => {
    e.preventDefault();
    if (pw.length < 8) { setErr('Use at least 8 characters.'); return; }
    if (pw !== pw2) { setErr('Passwords don’t match.'); return; }
    setErr(''); setView('done');
  };

  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 SuccessRing = ({ name = 'check' }) => (
    <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 52, height: 52, borderRadius: '50%', background: 'var(--success-subtle)', color: 'var(--green-600)', marginBottom: 22 }}>
      <Icon name={name} size={26} color="var(--green-600)" />
    </span>
  );

  let card;
  if (view === 'request') {
    card = (
      <React.Fragment>
        <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 46, height: 46, borderRadius: 'var(--radius-lg)', background: 'var(--accent-subtle)', color: 'var(--blue-600)', marginBottom: 20 }}>
          <Icon name="key-round" size={22} color="var(--blue-600)" />
        </span>
        <h1 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', marginBottom: 6 }}>Reset your password</h1>
        <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', marginBottom: 30 }}>
          Enter the email linked to your account and we’ll send you a link to set a new password.
        </p>
        <form onSubmit={submitRequest} style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>
          <div>
            <ResetField label="Email" type="email" placeholder="you@fleet.com" autoComplete="email" value={email} onChange={(e) => { setEmail(e.target.value); if (err) setErr(''); }} />
            {err && <span style={{ display: 'block', marginTop: 8, fontSize: 'var(--text-sm)', color: 'var(--danger-600, #c0362c)' }}>{err}</span>}
          </div>
          <Button variant="primary" size="lg" type="submit" fullWidth iconRight={<Icon name="arrow-right" size={18} color="#fff" />}>Send reset link</Button>
          <BackToLogin />
        </form>
      </React.Fragment>
    );
  } else if (view === 'sent') {
    card = (
      <div style={{ textAlign: 'center' }}>
        <SuccessRing name="mail-check" />
        <h1 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', marginBottom: 8 }}>Check your email</h1>
        <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)', marginBottom: 6 }}>
          We’ve sent a password reset link to
        </p>
        <p style={{ fontSize: 'var(--text-base)', fontWeight: 600, color: 'var(--text-primary)', marginBottom: 24, wordBreak: 'break-all' }}>{email}</p>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, textAlign: 'left', background: 'var(--neutral-50)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', padding: '14px 16px', marginBottom: 26 }}>
          <span style={{ flexShrink: 0, marginTop: 1, display: 'inline-flex', color: 'var(--text-tertiary)' }}><Icon name="clock" size={16} color="currentColor" /></span>
          <span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)' }}>The link expires in 30 minutes. If it doesn’t arrive, check your spam folder.</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Button variant="secondary" size="lg" fullWidth onClick={() => { setView('request'); setResent(false); setCooldown(0); }}>Use a different email</Button>
          <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-tertiary)' }}>
            {cooldown > 0
              ? <span>{resent ? 'Link sent. ' : ''}You can resend in {cooldown}s</span>
              : <span>Didn’t get it? <a href="#" onClick={(e) => { e.preventDefault(); resend(); }} style={{ color: 'var(--blue-600)', fontWeight: 600 }}>Resend link</a></span>}
          </div>
          <BackToLogin />
        </div>
      </div>
    );
  } else if (view === 'reset') {
    card = (
      <React.Fragment>
        <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 46, height: 46, borderRadius: 'var(--radius-lg)', background: 'var(--accent-subtle)', color: 'var(--blue-600)', marginBottom: 20 }}>
          <Icon name="lock" size={21} color="var(--blue-600)" />
        </span>
        <h1 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', marginBottom: 6 }}>Set a new password</h1>
        <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', marginBottom: 30 }}>
          {email ? <React.Fragment>Choose a new password for <strong style={{ color: 'var(--text-primary)', fontWeight: 600 }}>{email}</strong>.</React.Fragment> : 'Choose a new password for your account.'}
        </p>
        <form onSubmit={submitReset} style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <ResetField label="New password" type={showPw ? 'text' : 'password'} placeholder="At least 8 characters" autoComplete="new-password" value={pw} onChange={(e) => setPw(e.target.value)} suffix={pwToggle} />
          <ResetField label="Repeat new password" type={showPw ? 'text' : 'password'} placeholder="Re-enter your password" autoComplete="new-password" value={pw2} onChange={(e) => setPw2(e.target.value)} />
          {err && <span style={{ marginTop: -8, fontSize: 'var(--text-sm)', color: 'var(--danger-600, #c0362c)' }}>{err}</span>}
          <Button variant="primary" size="lg" type="submit" fullWidth iconRight={<Icon name="arrow-right" size={18} color="#fff" />}>Update password</Button>
          <BackToLogin />
        </form>
      </React.Fragment>
    );
  } else {
    card = (
      <div style={{ textAlign: 'center' }}>
        <SuccessRing name="check" />
        <h1 style={{ fontSize: 'var(--text-h2)', fontWeight: 600, letterSpacing: 'var(--tracking-tight)', marginBottom: 8 }}>Password updated</h1>
        <p style={{ fontSize: 'var(--text-base)', color: 'var(--text-secondary)', lineHeight: 'var(--leading-normal)', marginBottom: 28 }}>
          Your password has been changed. Log in with your new password to continue.
        </p>
        <a href="login.html" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8, width: '100%', height: 52, fontSize: 'var(--text-base)', fontWeight: 600, color: '#fff', background: 'var(--blue-500)', borderRadius: 'var(--radius-md)', boxShadow: '0 1px 0 rgba(255,255,255,0.18) inset, var(--shadow-sm)' }}>
          Log in <Icon name="arrow-right" size={18} color="#fff" />
        </a>
      </div>
    );
  }

  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: '40px 40px 36px' }}>
          {card}
        </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, { ForgotPassword });
