// Norton-Gauss · Support — passwordless (OTP-only) sign-in
// ─────────────────────────────────────────────────────────────
// Clicking "Support" in the nav routes here. Access is OTP-only:
// the user enters their work email, receives a one-time 6-digit
// code, and verifies it — there is no password option at all.
// Three steps: email → code → verified.

const { useState: sS, useEffect: sE, useRef: sR } = React;

// ── Tiny line icons (brand: stroke-only, ~1.8px) ─────────────────
const MailIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
    <rect x="3" y="5" width="18" height="14" rx="2.5" stroke="currentColor" strokeWidth="1.7" />
    <path d="M4 7l8 6 8-6" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);
const ShieldIcon = ({ size = 18 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
    <path d="M12 3l7 3v5c0 4.4-3 7.6-7 9-4-1.4-7-4.6-7-9V6l7-3z" stroke="currentColor" strokeWidth="1.7" strokeLinejoin="round" />
    <path d="M9 12l2 2 4-4" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);
const CheckIcon = ({ size = 26 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" aria-hidden>
    <path d="M5 12.5l4.5 4.5L19 7" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);
const BackIcon = ({ size = 15 }) => (
  <svg width={size} height={size} viewBox="0 0 16 16" fill="none" aria-hidden>
    <path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
);

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const OTP_LEN = 6;
const RESEND_SECONDS = 30;

function SupportLoginPage({ setRoute }) {
  const [step, setStep] = sS('email');          // email · code · done
  const [email, setEmail] = sS('');
  const [digits, setDigits] = sS(Array(OTP_LEN).fill(''));
  const [sending, setSending] = sS(false);
  const [verifying, setVerifying] = sS(false);
  const [error, setError] = sS('');
  const [resendIn, setResendIn] = sS(0);

  const emailValid = EMAIL_RE.test(email.trim());
  const code = digits.join('');
  const codeComplete = code.length === OTP_LEN && /^\d{6}$/.test(code);

  const inputsRef = sR([]);
  const emailRef = sR(null);
  const meshRef = sR(null);

  // Mount the Three.js neural-mesh hero behind the support panel. Polls for
  // THREE + NGHeroMesh (loaded as plain scripts) then mounts a decorative
  // instance; disposes on unmount.
  sE(() => {
    let dispose = null, mounted = true;
    (function tryMount(retry) {
      if (!mounted) return;
      if (!window.THREE || !window.NGHeroMesh) {
        if (retry > 80) return;
        setTimeout(() => tryMount(retry + 1), 50);
        return;
      }
      if (!meshRef.current) return;
      dispose = window.NGHeroMesh(meshRef.current, { decorative: true, meshScale: 0.96 });
    })(0);
    return () => { mounted = false; if (dispose) dispose(); };
  }, []);

  // Focus email on mount
  sE(() => { if (step === 'email' && emailRef.current) emailRef.current.focus(); }, [step]);
  // Focus first code box when entering the code step
  sE(() => { if (step === 'code') setTimeout(() => inputsRef.current[0]?.focus(), 60); }, [step]);

  // Resend countdown
  sE(() => {
    if (resendIn <= 0) return;
    const id = setTimeout(() => setResendIn((s) => s - 1), 1000);
    return () => clearTimeout(id);
  }, [resendIn]);

  const sendCode = (e) => {
    if (e) e.preventDefault();
    if (!emailValid || sending) return;
    setError('');
    setSending(true);
    // Simulated dispatch — a real backend would POST and email the OTP.
    setTimeout(() => {
      setSending(false);
      setDigits(Array(OTP_LEN).fill(''));
      setStep('code');
      setResendIn(RESEND_SECONDS);
    }, 850);
  };

  const setDigitAt = (i, val) => {
    setDigits((prev) => {
      const next = prev.slice();
      next[i] = val;
      return next;
    });
  };

  const onDigitChange = (i, raw) => {
    const v = raw.replace(/\D/g, '');
    if (error) setError('');
    if (v === '') { setDigitAt(i, ''); return; }
    // If user typed/pasted multiple, distribute across boxes
    if (v.length > 1) {
      setDigits((prev) => {
        const next = prev.slice();
        for (let k = 0; k < v.length && i + k < OTP_LEN; k++) next[i + k] = v[k];
        return next;
      });
      const landing = Math.min(i + v.length, OTP_LEN - 1);
      inputsRef.current[landing]?.focus();
      return;
    }
    setDigitAt(i, v);
    if (i < OTP_LEN - 1) inputsRef.current[i + 1]?.focus();
  };

  const onDigitKey = (i, e) => {
    if (e.key === 'Backspace' && !digits[i] && i > 0) {
      inputsRef.current[i - 1]?.focus();
      setDigitAt(i - 1, '');
    } else if (e.key === 'ArrowLeft' && i > 0) {
      inputsRef.current[i - 1]?.focus();
    } else if (e.key === 'ArrowRight' && i < OTP_LEN - 1) {
      inputsRef.current[i + 1]?.focus();
    }
  };

  const onPaste = (e) => {
    const text = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '').slice(0, OTP_LEN);
    if (!text) return;
    e.preventDefault();
    const next = Array(OTP_LEN).fill('');
    for (let k = 0; k < text.length; k++) next[k] = text[k];
    setDigits(next);
    inputsRef.current[Math.min(text.length, OTP_LEN - 1)]?.focus();
  };

  const verify = (e) => {
    if (e) e.preventDefault();
    if (!codeComplete || verifying) return;
    setVerifying(true);
    setError('');
    // Simulated verification. A real backend validates the OTP server-side.
    setTimeout(() => {
      setVerifying(false);
      setStep('done');
    }, 900);
  };

  const resend = () => {
    if (resendIn > 0) return;
    setDigits(Array(OTP_LEN).fill(''));
    setResendIn(RESEND_SECONDS);
    inputsRef.current[0]?.focus();
  };

  return (
    <div className="auth auth--hero page-enter">
      <aside className="auth-hero">
        <div className="auth-hero-mesh" ref={meshRef} aria-hidden="true"></div>
        <div className="auth-hero-halo" aria-hidden="true"></div>
        <div className="auth-hero-copy">
          <a className="auth-hero-brand" href="#" onClick={(e) => { e.preventDefault(); setRoute('home'); }}>
            <img src={(window.__resources && window.__resources.logoMarkColor) || "assets/logo-mark-color.png"} alt="Norton-Gauss" />
            <span>Norton-Gauss</span>
          </a>
          <h2 className="auth-hero-h">{tr("Support that runs at the ")}<em>{tr("speed of your operations.")}</em></h2>
          <p className="auth-hero-p">{tr("Sign in to reach your engagement team, track active mandates and raise priority issues across automation, AI and cloud-edge systems.")}</p>
          <div className="auth-hero-meta">
            <span><i></i>{tr("Priority response · 24/7")}</span>
            <span><i></i>{tr("Single sign-on · OTP secured")}</span>
          </div>
        </div>
      </aside>
      <div className="auth-shell">
        <div className="auth-card">

          {step === 'email' && (
            <form className="auth-body" onSubmit={sendCode}>
              <span className="auth-eyebrow">{tr("Support · Secure access")}</span>
              <h1 className="auth-title">{tr("Sign in to the ")}<em>{tr("support portal")}</em>{tr(".")}</h1>
              <p className="auth-sub">{tr("Enter your work email and we'll send a one-time code. Norton-Gauss support is passwordless — there's nothing to remember.")}</p>

              <label className="auth-field">
                <span className="auth-label">{tr("Work email")}</span>
                <span className="auth-input-wrap">
                  <span className="auth-input-ico"><MailIcon /></span>
                  <input
                    ref={emailRef}
                    type="email"
                    inputMode="email"
                    autoComplete="email"
                    placeholder={tr("you@company.com")}
                    value={email}
                    onChange={(e) => { setEmail(e.target.value); if (error) setError(''); }}
                  />
                </span>
              </label>

              {error && <div className="auth-error">{error}</div>}

              <button type="submit" className="auth-btn" disabled={!emailValid || sending}>
                {sending ? tr('Sending code…') : tr('Send one-time code')}
              </button>

              <div className="auth-note"><ShieldIcon size={15} /><span>{tr("One-time code only · no passwords stored")}</span></div>
            </form>
          )}

          {step === 'code' && (
            <form className="auth-body" onSubmit={verify}>
              <button type="button" className="auth-back" onClick={() => { setStep('email'); setError(''); }}>
                <BackIcon /> {tr("Use a different email")}
              </button>
              <span className="auth-eyebrow">{tr("Support · Verify")}</span>
              <h1 className="auth-title">{tr("Enter your ")}<em>{tr("code")}</em>{tr(".")}</h1>
              <p className="auth-sub">{tr("We sent a 6-digit code to ")}<strong>{email}</strong>{tr(". It expires in 10 minutes.")}</p>

              <div className="auth-otp" onPaste={onPaste}>
                {digits.map((d, i) => (
                  <input
                    key={i}
                    ref={(el) => (inputsRef.current[i] = el)}
                    className={'auth-otp-box' + (d ? ' is-filled' : '')}
                    type="text"
                    inputMode="numeric"
                    autoComplete={i === 0 ? 'one-time-code' : 'off'}
                    maxLength={1}
                    value={d}
                    onChange={(e) => onDigitChange(i, e.target.value)}
                    onKeyDown={(e) => onDigitKey(i, e)}
                    aria-label={`Digit ${i + 1}`}
                  />
                ))}
              </div>

              {error && <div className="auth-error">{error}</div>}

              <button type="submit" className="auth-btn" disabled={!codeComplete || verifying}>
                {verifying ? tr('Verifying…') : tr('Verify & continue')}
              </button>

              <div className="auth-resend">
                {resendIn > 0
                  ? <span className="auth-resend-wait">{tr("Resend code in ")}{resendIn}{tr("s")}</span>
                  : <button type="button" className="auth-resend-btn" onClick={resend}>{tr("Resend code")}</button>}
              </div>
            </form>
          )}

          {step === 'done' && (
            <div className="auth-body auth-done">
              <div className="auth-check"><CheckIcon /></div>
              <h1 className="auth-title">{tr("You're ")}<em>{tr("verified")}</em>{tr(".")}</h1>
              <p className="auth-sub">{tr("Signed in as ")}<strong>{email}</strong>{tr(". Welcome to Norton-Gauss support.")}</p>
              <button type="button" className="auth-btn" onClick={() => setRoute('home')}>{tr("Enter support portal")}</button>
              <button type="button" className="auth-textlink" onClick={() => { setStep('email'); setEmail(''); setDigits(Array(OTP_LEN).fill('')); }}>{tr("Sign out")}</button>
            </div>
          )}
        </div>

        <p className="auth-foot">
          {tr("Need help signing in? Email ")}<a href="mailto:support@nortongauss.com">support@nortongauss.com</a>
        </p>
      </div>
    </div>
  );
}

Object.assign(window, { SupportLoginPage });
