// auth.jsx — Standalone cinematic authentication bundle for Herely.
// Completely self-contained React app featuring custom state engine,
// floating canvas particles, advanced input forms, and clean intern API hooks.

const { useEffect, useRef, useState, useMemo } = React;

/* ─── Helper: Hex to RGBA canvas drawing ─── */
function withAlpha(hex, a) {
  const h = hex.replace("#", "");
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  return `rgba(${r},${g},${b},${a})`;
}

/* ─── Ambient canvas: drifting presence specks ─── */
function HeroAmbient({ midnight }) {
  const wrapRef = useRef(null);
  const canvasRef = useRef(null);
  useEffect(() => {
    const wrap = wrapRef.current, canvas = canvasRef.current;
    if (!wrap || !canvas) return;
    let raf = 0;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    let w = 0, h = 0;
    
    const resize = () => {
      const r = wrap.getBoundingClientRect();
      w = r.width; h = r.height;
      canvas.width = Math.floor(w * dpr);
      canvas.height = Math.floor(h * dpr);
      canvas.style.width = w + "px";
      canvas.style.height = h + "px";
    };
    resize();
    const ro = new ResizeObserver(resize);
    ro.observe(wrap);

    // 24 specks across the field for clean, premium density
    const N = 24;
    const COLORS = ["#3A7FCC", "#F5A623", "#00C49A", "#FF6B6B", "#A8A8A8"];
    const pts = Array.from({ length: N }, () => ({
      x: Math.random(),
      y: Math.random(),
      vx: (Math.random() - 0.5) * 0.008,
      vy: (Math.random() - 0.5) * 0.008,
      phase: Math.random() * Math.PI * 2,
      r: 2.5 + Math.random() * 3,
      c: COLORS[Math.floor(Math.random() * COLORS.length)],
    }));

    let t0 = performance.now();
    const draw = (t) => {
      const dt = Math.min(0.05, (t - t0) / 1000);
      t0 = t;
      const ctx = canvas.getContext("2d");
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx.clearRect(0, 0, w, h);

      // Delicate ambient grid
      ctx.strokeStyle = midnight ? "rgba(255,255,255,0.03)" : "rgba(11,11,13,0.03)";
      ctx.lineWidth = 1;
      const step = 80;
      ctx.beginPath();
      for (let x = 0; x < w; x += step) { ctx.moveTo(x, 0); ctx.lineTo(x, h); }
      for (let y = 0; y < h; y += step) { ctx.moveTo(0, y); ctx.lineTo(w, y); }
      ctx.stroke();

      for (const p of pts) {
        p.x += p.vx * dt; p.y += p.vy * dt;
        if (p.x < 0 || p.x > 1) p.vx *= -1;
        if (p.y < 0 || p.y > 1) p.vy *= -1;
        p.phase += dt * 0.5;
        const pulse = 0.5 + 0.5 * Math.sin(p.phase);
        const px = p.x * w, py = p.y * h;
        const haloR = p.r + 14 + pulse * 8;
        
        const g = ctx.createRadialGradient(px, py, 0, px, py, haloR);
        g.addColorStop(0, withAlpha(p.c, midnight ? 0.18 : 0.12));
        g.addColorStop(1, withAlpha(p.c, 0));
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(px, py, haloR, 0, Math.PI * 2); ctx.fill();
        
        ctx.fillStyle = withAlpha(p.c, midnight ? 0.80 : 0.50);
        ctx.beginPath(); ctx.arc(px, py, p.r, 0, Math.PI * 2); ctx.fill();
      }
      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);
    return () => { cancelAnimationFrame(raf); ro.disconnect(); };
  }, [midnight]);

  return (
    <div className="hero-canvas" ref={wrapRef}>
      <canvas ref={canvasRef}></canvas>
    </div>
  );
}

/* ─── Brand & Form Icon SVGs ─── */
const Arrow = () => (
  <svg className="arrow" viewBox="0 0 14 14" fill="none">
    <path d="M2 7h10M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const SunIcon = () => (
  <svg viewBox="0 0 16 16" width="15" height="15" fill="none">
    <circle cx="8" cy="8" r="3" stroke="currentColor" strokeWidth="1.3"/>
    {[0, 45, 90, 135, 180, 225, 270, 315].map(a => {
      const rad = (a * Math.PI) / 180;
      const x1 = 8 + Math.cos(rad) * 5, y1 = 8 + Math.sin(rad) * 5;
      const x2 = 8 + Math.cos(rad) * 7, y2 = 8 + Math.sin(rad) * 7;
      return <line key={a} x1={x1} y1={y1} x2={x2} y2={y2} stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>;
    })}
  </svg>
);

const MoonIcon = () => (
  <svg viewBox="0 0 16 16" width="15" height="15" fill="none">
    <path d="M12.5 9.5A5 5 0 1 1 6.5 3.5a4 4 0 0 0 6 6Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/>
  </svg>
);

const EyeIcon = () => (
  <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4">
    <path d="M1 8s3-5.5 7-5.5S15 8 15 8s-3 5.5-7 5.5S1 8 1 8Z" strokeLinecap="round" strokeLinejoin="round"/>
    <circle cx="8" cy="8" r="2.5"/>
  </svg>
);

const EyeOffIcon = () => (
  <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.4">
    <path d="M1.5 1.5l13 13M12.2 12.2c-1.2.9-2.7 1.3-4.2 1.3-4 0-7-5.5-7-5.5.8-1.5 2.1-3 3.6-4.1M5.6 5.6C6.3 5.1 7.1 5 8 5c4 0 7 5.5 7 5.5-.6 1.1-1.4 2.1-2.4 2.9M8 8a2.5 2.5 0 01-1.77-.73" strokeLinecap="round" strokeLinejoin="round"/>
  </svg>
);

const GoogleIcon = () => (
  <svg viewBox="0 0 24 24">
    <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
    <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
    <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.06H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.94l2.85-2.22.81-.63z" fill="#FBBC05"/>
    <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.06l3.66 2.84c.87-2.6 3.3-4.52 6.16-4.52z" fill="#EA4335"/>
  </svg>
);

const GithubIcon = () => (
  <svg viewBox="0 0 24 24">
    <path fillRule="evenodd" clipRule="evenodd" d="M12 2C6.477 2 2 6.477 2 12c0 4.42 2.865 8.166 6.839 9.489.5.092.682-.217.682-.482 0-.237-.008-.866-.013-1.7-2.782.603-3.369-1.34-3.369-1.34-.454-1.156-1.11-1.464-1.11-1.464-.908-.62.069-.608.069-.608 1.003.07 1.531 1.03 1.531 1.03.892 1.529 2.341 1.087 2.91.831.092-.646.35-1.086.636-1.336-2.22-.253-4.555-1.11-4.555-4.943 0-1.091.39-1.984 1.029-2.683-.103-.253-.446-1.27.098-2.647 0 0 .84-.269 2.75 1.025A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.294 2.747-1.025 2.747-1.025.546 1.377.203 2.394.1 2.647.64.699 1.028 1.592 1.028 2.683 0 3.842-2.339 4.687-4.566 4.935.359.309.678.919.678 1.852 0 1.336-.012 2.415-.012 2.743 0 .267.18.579.688.481C19.137 20.162 22 16.418 22 12c0-5.523-4.477-10-10-10z"/>
  </svg>
);

const LinkedInIcon = () => (
  <svg viewBox="0 0 24 24">
    <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.225 0z" fill="#0A66C2"/>
  </svg>
);

const CheckIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
    <path d="M20 6L9 17l-5-5"/>
  </svg>
);

/* ─── LIVE API: Real Backend Authentication Endpoints ───
 * Connected to MongoDB backend at http://localhost:3001/api
 * All requests include proper error handling and JSON parsing.
 */
const API_URL = window.API_URL || "http://localhost:3001/api";

const api = {
  /**
   * Log into account
   * @param {string} email
   * @param {string} password
   * @returns {Promise<{user: {name: string, email: string}, token: string}>}
   */
  login: async (email, password) => {
    const res = await fetch(`${API_URL}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'Login failed');
    return data;
  },

  /**
   * Register a new user
   * @param {string} name
   * @param {string} email
   * @param {string} password
   * @returns {Promise<{success: boolean, message: string}>}
   */
  register: async (name, email, password) => {
    const res = await fetch(`${API_URL}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, password })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'Registration failed');
    return data;
  },

  /**
   * Trigger recovery link / OTP code
   * @param {string} email
   * @returns {Promise<{success: boolean}>}
   */
  sendResetEmail: async (email) => {
    const res = await fetch(`${API_URL}/auth/forgot-password`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'Failed to send reset email');
    return data;
  },

  /**
   * Confirm numeric one-time security code
   * @param {string} email
   * @param {string} otpCode 6-digit numeric string
   * @returns {Promise<{success: boolean}>}
   */
  verifyOTP: async (email, otpCode) => {
    const res = await fetch(`${API_URL}/auth/verify-otp`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, otpCode })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'OTP verification failed');
    return data;
  },

  /**
   * Resend security verification code
   * @param {string} email
   * @returns {Promise<{success: boolean}>}
   */
  resendOTP: async (email) => {
    const res = await fetch(`${API_URL}/auth/resend-otp`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email })
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.message || 'Failed to resend OTP');
    return data;
  }
};

/* ─── Main Standalone Auth Application State Engine ─── */
function AuthApp({ onSuccess, initialView = "login", onNavigate } = {}) {
  const [view, setView] = useState(initialView); // "login" | "signup" | "forgot" | "otp" | "success"
  const [animating, setAnimating] = useState(false);
  const [midnight, setMidnight] = useState(true);

  // Form input bindings
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [agreeTerms, setAgreeTerms] = useState(false);
  
  // Multi-box OTP input states
  const [otpValues, setOtpValues] = useState(["", "", "", "", "", ""]);
  
  // Validation, errors, loading
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);
  const [showPass, setShowPass] = useState(false);
  
  // One-time code resend countdown timer (starts at 59s)
  const [countdown, setCountdown] = useState(59);
  const [canResend, setCanResend] = useState(false);

  useEffect(() => {
    if (initialView) {
      setView(initialView);
    }
  }, [initialView]);

  useEffect(() => {
    if (view !== "success") return undefined;
    const timer = setTimeout(() => {
      if (onSuccess) onSuccess();
    }, 700);
    return () => clearTimeout(timer);
  }, [onSuccess, view]);

  const persistSession = (user, token) => {
    localStorage.setItem("herely.session", JSON.stringify({ user, token: token || null }));
  };

  // Sync index.html classes for dynamic theme mapping
  useEffect(() => {
    const root = document.documentElement;
    if (midnight) {
      root.classList.add("midnight");
      document.body.classList.add("midnight");
    } else {
      root.classList.remove("midnight");
      document.body.classList.remove("midnight");
    }
  }, [midnight]);

  // One-Time Password Timer loop
  useEffect(() => {
    let timer;
    if (view === "otp" && countdown > 0) {
      timer = setInterval(() => {
        setCountdown(prev => prev - 1);
      }, 1000);
    } else if (countdown === 0) {
      setCanResend(true);
    }
    return () => clearInterval(timer);
  }, [view, countdown]);

  /* Smooth Premium Switcher: Exit animation triggers, waits, changes state, then slides in */
  const navigateTo = (nextView) => {
    if (animating || view === nextView) return;
    setAnimating(true);
    setError(null);
    setShowPass(false);
    
    if (onNavigate) {
      if (nextView === "login") onNavigate("/sign-in");
      else if (nextView === "signup") onNavigate("/sign-up");
    }

    // Clear forms when switching main flows
    if ((view === "login" && nextView === "signup") || (view === "signup" && nextView === "login")) {
      setEmail("");
      setPassword("");
      setName("");
      setAgreeTerms(false);
    }

    setTimeout(() => {
      setView(nextView);
      setAnimating(false);
      
      // Reset timer if entering OTP screen
      if (nextView === "otp") {
        setCountdown(59);
        setCanResend(false);
        setOtpValues(["", "", "", "", "", ""]);
      }
    }, 400); // syncs with exit timing CSS animations
  };

  /* Regex password strength rating: returns 0-3 score + descriptive state label */
  const pwdStrength = useMemo(() => {
    if (!password) return { score: 0, text: "" };
    let score = 0;
    if (password.length >= 8) score++;
    if (/[A-Z]/.test(password) && /[0-9]/.test(password)) score++;
    if (/[^A-Za-z0-9]/.test(password)) score++;
    
    const labels = ["Weak", "Medium", "Strong"];
    return {
      score,
      text: labels[score - 1] || "Weak"
    };
  }, [password]);

  /* Form submission validators */
  const handleLoginSubmit = async (e) => {
    e.preventDefault();
    if (!email || !password) {
      setError("Please complete all security credentials.");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      const data = await api.login(email, password);
      persistSession(data.user, data.token);
      console.log("Logged In Successfully!", data);
      navigateTo("success");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleRegisterSubmit = async (e) => {
    e.preventDefault();
    if (!name || !email || !password) {
      setError("Please fill out all registration fields.");
      return;
    }
    if (!agreeTerms) {
      setError("Please review and accept Herely's privacy terms.");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      await api.register(name, email, password);
      localStorage.setItem("herely.pendingUser", JSON.stringify({ name, email }));
      console.log("Account Created! Moving to email verification code verification.");
      navigateTo("otp");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleForgotSubmit = async (e) => {
    e.preventDefault();
    if (!email) {
      setError("Please specify the email to receive your link.");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      await api.sendResetEmail(email);
      console.log("OTP code request sent.");
      navigateTo("otp");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  /* OTP Code Grid inputs controllers */
  const handleOtpChange = (index, val) => {
    if (isNaN(val)) return; // numbers only
    const newOtp = [...otpValues];
    newOtp[index] = val.slice(-1); // only keep last typed character
    setOtpValues(newOtp);

    // Auto-advance cursor to next input box
    if (val && index < 5) {
      const nextInput = document.getElementById(`otp-${index + 1}`);
      if (nextInput) nextInput.focus();
    }
  };

  const handleOtpKeyDown = (index, e) => {
    // Backspace: clear current and step focus back
    if (e.key === "Backspace") {
      if (!otpValues[index] && index > 0) {
        const prevInput = document.getElementById(`otp-${index - 1}`);
        if (prevInput) {
          prevInput.focus();
          const newOtp = [...otpValues];
          newOtp[index - 1] = "";
          setOtpValues(newOtp);
        }
      }
    }
  };

  const handleOtpSubmit = async (e) => {
    e.preventDefault();
    const finalCode = otpValues.join("");
    if (finalCode.length < 6) {
      setError("Please enter the complete 6-digit code.");
      return;
    }
    setLoading(true);
    setError(null);
    try {
      await api.verifyOTP(email || " Anya Reyes", finalCode);
      // After OTP verify, auto-login to get the JWT token so socket auth works
      const pending = JSON.parse(localStorage.getItem("herely.pendingUser") || "null");
      let token = null;
      try {
        const loginData = await api.login(email, password);
        token = loginData.token || null;
      } catch (_) {
        // login failed (e.g. password reset flow) — token stays null
      }
      persistSession(pending || { name: name || "Anya Reyes", email: email || "anya@herely.ai" }, token);
      localStorage.removeItem("herely.pendingUser");
      navigateTo("success");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleResendOtp = async () => {
    if (!canResend) return;
    setLoading(true);
    try {
      await api.resendOTP(email || "test@herely.ai");
      setCountdown(59);
      setCanResend(false);
      setError(null);
      setOtpValues(["", "", "", "", "", ""]);
      console.log("One-time security code resent successfully.");
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="auth-viewport">
      
      {/* Dynamic kinetic drift particle simulation */}
      <HeroAmbient midnight={midnight} />
      <div className="hero-vignette"></div>

      {/* Manual Light/Dark Theme Controller */}
      <button 
        className="mode-toggle"
        aria-label={midnight ? "Switch to light mode" : "Switch to midnight mode"}
        title={midnight ? "Light mode" : "Midnight mode"}
        onClick={() => setMidnight(!midnight)}
      >
        {midnight ? <SunIcon /> : <MoonIcon />}
      </button>

      <div className="auth-wrapper">
        
        {/* Brand identity header */}
        <div className="auth-logo">
          <span className="mark"></span>
          Herely
        </div>

        <div className={`auth-card ${animating ? 'fade-out' : 'fade-in'}`}>
          
          {/* ───────────────── SIGN IN VIEW ───────────────── */}
          {view === "login" && (
            <form onSubmit={handleLoginSubmit}>
              <header className="auth-header">
                <div className="eyebrow">A quieter network</div>
                <h1 className="auth-title">Welcome <span className="ed">back</span></h1>
                <p className="auth-subtitle">Quietly reconnect to the physical spaces around you.</p>
              </header>

              {error && <div className="field-error-msg" style={{marginBottom: 16}}>{error}</div>}

              <div className="form-group">
                <label className="form-label" htmlFor="email-login">Email</label>
                <input 
                  type="email" 
                  id="email-login"
                  className="form-control"
                  placeholder="name@herely.ai"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={loading}
                />
              </div>

              <div className="form-group" style={{marginBottom: 16}}>
                <label className="form-label" htmlFor="pass-login">Password</label>
                <div className="form-control-wrap">
                  <input 
                    type={showPass ? "text" : "password"} 
                    id="pass-login"
                    className="form-control"
                    placeholder="••••••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    disabled={loading}
                  />
                  <button 
                    type="button" 
                    className="pass-toggle-btn"
                    onClick={() => setShowPass(!showPass)}
                    disabled={loading}
                  >
                    {showPass ? <EyeOffIcon/> : <EyeIcon/>}
                  </button>
                </div>
              </div>

              <div className="form-options">
                <label className="checkbox-container">
                  <input 
                    type="checkbox" 
                    disabled={loading} 
                    checked={agreeTerms}
                    onChange={(e) => setAgreeTerms(e.target.checked)}
                  />
                  <span className="checkbox-custom"></span>
                  Remember me
                </label>
                <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); navigateTo("forgot"); }}>Forgot password?</a>
              </div>

              <button 
                type="submit" 
                className={`btn btn-primary btn-full ${loading ? 'shimmer' : ''}`}
                disabled={loading}
              >
                {loading ? "Decrypting..." : "Enter the room"} <Arrow/>
              </button>

              <div className="social-divider">Or continue with</div>

              <div className="social-grid">
                <button
                  type="button"
                  className="btn-social"
                  disabled={loading}
                  onClick={() => {
                    window.location.href = `${API_URL}/auth/google`;
                  }}
                >
                  <GoogleIcon/> Google
                </button>
                <button type="button" className="btn-social" disabled={loading}>
                  <GithubIcon/> GitHub
                </button>
                <button 
                  type="button" 
                  className="btn-social" 
                  disabled={loading}
                  onClick={() => {
                    window.location.href = `${API_URL}/auth/linkedin`;
                  }}
                >
                  <LinkedInIcon/> LinkedIn
                </button>
              </div>

              <footer className="auth-footer">
                New to Herely? 
                <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); navigateTo("signup"); }}>Create an account</a>
              </footer>
            </form>
          )}

          {/* ───────────────── SIGN UP VIEW ───────────────── */}
          {view === "signup" && (
            <form onSubmit={handleRegisterSubmit}>
              <header className="auth-header">
                <div className="eyebrow">First Invitation</div>
                <h1 className="auth-title">Create <span className="ed">account</span></h1>
                <p className="auth-subtitle">Secure your presence before joining the active network.</p>
              </header>

              {error && <div className="field-error-msg" style={{marginBottom: 16}}>{error}</div>}

              <div className="form-group">
                <label className="form-label" htmlFor="name-signup">Full name</label>
                <input 
                  type="text" 
                  id="name-signup"
                  className="form-control"
                  placeholder="Anya Reyes"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  disabled={loading}
                />
              </div>

              <div className="form-group">
                <label className="form-label" htmlFor="email-signup">Email</label>
                <input 
                  type="email" 
                  id="email-signup"
                  className="form-control"
                  placeholder="name@herely.ai"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={loading}
                />
              </div>

              <div className="form-group">
                <label className="form-label" htmlFor="pass-signup">Password</label>
                <div className="form-control-wrap">
                  <input 
                    type={showPass ? "text" : "password"} 
                    id="pass-signup"
                    className="form-control"
                    placeholder="••••••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    disabled={loading}
                  />
                  <button 
                    type="button" 
                    className="pass-toggle-btn"
                    onClick={() => setShowPass(!showPass)}
                    disabled={loading}
                  >
                    {showPass ? <EyeOffIcon/> : <EyeIcon/>}
                  </button>
                </div>

                {/* Secure Password Strength Gauge */}
                {password && (
                  <div className="pwd-strength-container">
                    <div className="pwd-strength-bar-grid">
                      <div className={`pwd-strength-segment ${pwdStrength.score >= 1 ? 'active-weak' : ''}`}></div>
                      <div className={`pwd-strength-segment ${pwdStrength.score >= 2 ? 'active-fair' : ''}`}></div>
                      <div className={`pwd-strength-segment ${pwdStrength.score >= 3 ? 'active-strong' : ''}`}></div>
                    </div>
                    <span className="pwd-strength-label">Password density: {pwdStrength.text}</span>
                  </div>
                )}
              </div>

              <div className="form-options" style={{marginBottom: 24}}>
                <label className="checkbox-container" style={{alignItems: 'flex-start'}}>
                  <input 
                    type="checkbox" 
                    disabled={loading} 
                    checked={agreeTerms}
                    onChange={(e) => setAgreeTerms(e.target.checked)}
                  />
                  <span className="checkbox-custom" style={{marginTop: 2}}></span>
                  <span style={{fontSize: 12.5, lineHeight: 1.3}}>
                    I consent to quiet spatial visibility and agree to the Terms of Resonance.
                  </span>
                </label>
              </div>

              <button 
                type="submit" 
                className={`btn btn-primary btn-full ${loading ? 'shimmer' : ''}`}
                disabled={loading}
              >
                {loading ? "Establishing Bridge..." : "Initiate account"} <Arrow/>
              </button>

              <footer className="auth-footer">
                Already registered?
                <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); navigateTo("login"); }}>Sign in</a>
              </footer>
            </form>
          )}

          {/* ───────────────── FORGOT PASSWORD VIEW ───────────────── */}
          {view === "forgot" && (
            <form onSubmit={handleForgotSubmit}>
              <header className="auth-header">
                <div className="eyebrow">Resonance Recovery</div>
                <h1 className="auth-title">Reset <span className="ed">credentials</span></h1>
                <p className="auth-subtitle">We will send a numeric one-time security code to reconstruct your channel.</p>
              </header>

              {error && <div className="field-error-msg" style={{marginBottom: 16}}>{error}</div>}

              <div className="form-group" style={{marginBottom: 28}}>
                <label className="form-label" htmlFor="email-forgot">Registered Email</label>
                <input 
                  type="email" 
                  id="email-forgot"
                  className="form-control"
                  placeholder="name@herely.ai"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={loading}
                />
              </div>

              <button 
                type="submit" 
                className={`btn btn-primary btn-full ${loading ? 'shimmer' : ''}`}
                disabled={loading}
              >
                {loading ? "Generating Code..." : "Transmit security code"} <Arrow/>
              </button>

              <footer className="auth-footer">
                Remember your credentials?
                <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); navigateTo("login"); }}>Go back</a>
              </footer>
            </form>
          )}

          {/* ───────────────── OTP CODE VERIFICATION VIEW ───────────────── */}
          {view === "otp" && (
            <form onSubmit={handleOtpSubmit}>
              <header className="auth-header">
                <div className="eyebrow">Two-factor signal</div>
                <h1 className="auth-title">Verify <span className="ed">identity</span></h1>
                <p className="auth-subtitle">
                  We've transmitted a 6-digit sequence to <strong style={{color: 'var(--ink)'}}>{email || "your address"}</strong>.
                </p>
              </header>

              {error && <div className="field-error-msg" style={{marginBottom: 16}}>{error}</div>}

              {/* 6-box digit array */}
              <div className="otp-input-grid">
                {otpValues.map((digit, idx) => (
                  <input
                    key={idx}
                    type="text"
                    id={`otp-${idx}`}
                    className="otp-box"
                    maxLength={1}
                    value={digit}
                    onChange={(e) => handleOtpChange(idx, e.target.value)}
                    onKeyDown={(e) => handleOtpKeyDown(idx, e)}
                    disabled={loading}
                    autoFocus={idx === 0}
                  />
                ))}
              </div>

              <div className="otp-timer">
                {canResend ? (
                  <span>
                    Didn't receive the signal?{" "}
                    <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); handleResendOtp(); }}>
                      Resend Code
                    </a>
                  </span>
                ) : (
                  <span>
                    Resend code countdown: <span className="time">0:{countdown < 10 ? `0${countdown}` : countdown}</span>
                  </span>
                )}
              </div>

              <button 
                type="submit" 
                className={`btn btn-primary btn-full ${loading ? 'shimmer' : ''}`}
                disabled={loading}
              >
                {loading ? "Validating Signal..." : "Verify presence link"} <Arrow/>
              </button>

              <footer className="auth-footer">
                Need to change email?
                <a href="#" className="text-link" onClick={(e) => { e.preventDefault(); navigateTo("login"); }}>Start over</a>
              </footer>
            </form>
          )}

          {/* ───────────────── SUCCESS STATE OVERLAY ───────────────── */}
          {view === "success" && (
            <div className="success-visual">
              <div className="success-circle">
                <CheckIcon/>
              </div>
              <header className="auth-header" style={{textAlign: 'center', marginBottom: 28}}>
                <div className="eyebrow" style={{color: 'var(--m-teal)'}}>Identity Authenticated</div>
                <h1 className="auth-title">Presence <span className="ed">Active</span></h1>
                <p className="auth-subtitle" style={{maxWidth: '28ch', margin: '8px auto 0'}}>
                  Welcome back Anya. You are now securely visible to nearby presence nodes.
                </p>
              </header>

              <button 
                type="button" 
                className="btn btn-primary btn-full"
                  onClick={() => { if (onSuccess) onSuccess(); }}
              >
                Enter Herely <Arrow/>
              </button>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}
