// Inlinr — Login screen (signed-out state)

const LoginView = ({ onSignIn }) => {
  const { useEffect, useState } = React;
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [keepSignedIn, setKeepSignedIn] = useState(true);
  const [showPwd, setShowPwd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [mode, setMode] = useState("password"); // password | magic | signup | invite | email-link
  const [magicLinkSent, setMagicLinkSent] = useState(false);
  const [inviteInfo, setInviteInfo] = useState(null);
  const [forgotSent, setForgotSent] = useState(false);

  const errorMsg = (code) => {
    const map = {
      "auth/invalid-credential": "Incorrect email or password.",
      "auth/user-not-found": "No account found with this email.",
      "auth/wrong-password": "Incorrect password.",
      "auth/email-already-in-use": "This email is already registered. Sign in instead.",
      "auth/weak-password": "Password must be at least 6 characters.",
      "auth/invalid-email": "Please enter a valid email address.",
      "auth/too-many-requests": "Too many attempts. Please try again later."
    };
    return map[code] || "Something went wrong. Please try again.";
  };

  const setPersistence = () => {
    const persistence = keepSignedIn
      ? firebase.auth.Auth.Persistence.LOCAL
      : firebase.auth.Auth.Persistence.SESSION;
    return fbAuth.setPersistence(persistence);
  };

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const inviteToken = params.get("invite");
    const emailLinkEmail = params.get("email") || window.localStorage.getItem("emailForSignIn") || "";
    if (emailLinkEmail) setEmail(emailLinkEmail);

    if (inviteToken) {
      setInviteInfo({
        inviteToken,
        email: params.get("email") || "",
        firstName: params.get("firstName") || "",
        lastName: params.get("lastName") || "",
        role: params.get("role") || "viewer",
        workspaceName: params.get("workspaceName") || "your workspace"
      });
      setMode("invite");
      setEmail(params.get("email") || "");
      setFirstName(params.get("firstName") || "");
      setLastName(params.get("lastName") || "");
      return;
    }

    if (fbAuth.isSignInWithEmailLink(window.location.href)) {
      setMode("email-link");
    }
  }, []);

  const submit = async (e) => {
    e?.preventDefault();
    setError(null);
    setForgotSent(false);
    setLoading(true);

    try {
      await setPersistence();

      if (mode === "signup") {
        saveProfileDraft(email, { firstName, lastName });
        await fbAuth.createUserWithEmailAndPassword(email, password);
        onSignIn?.();
        return;
      }

      if (mode === "invite") {
        if (!inviteInfo?.inviteToken) {
          throw new Error("missing-invite");
        }
        saveProfileDraft(email, { firstName, lastName });
        setPendingInviteToken(inviteInfo.inviteToken);
        await fbAuth.createUserWithEmailAndPassword(email, password);
        onSignIn?.();
        return;
      }

      if (mode === "email-link") {
        await fbAuth.signInWithEmailLink(email, window.location.href);
        window.localStorage.removeItem("emailForSignIn");
        onSignIn?.();
        return;
      }

      if (mode === "magic") {
        const actionCodeSettings = {
          url: `${window.location.origin}/?email=${encodeURIComponent(normalizeEmail(email))}`,
          handleCodeInApp: true
        };
        await fbAuth.sendSignInLinkToEmail(normalizeEmail(email), actionCodeSettings);
        window.localStorage.setItem("emailForSignIn", normalizeEmail(email));
        setMagicLinkSent(true);
        setLoading(false);
        return;
      }

      await fbAuth.signInWithEmailAndPassword(email, password);
      onSignIn?.();
    } catch (err) {
      setError(err.message === "missing-invite" ? "This invitation is incomplete. Ask the owner to resend it." : errorMsg(err.code));
      setLoading(false);
    }
  };

  const signInWithGoogle = async () => {
    setError(null);
    setLoading(true);
    try {
      await setPersistence();
      const provider = new firebase.auth.GoogleAuthProvider();
      await fbAuth.signInWithPopup(provider);
    } catch (err) {
      setError(errorMsg(err.code));
      setLoading(false);
    }
  };

  const sendPasswordReset = async (e) => {
    e.preventDefault();
    setError(null);
    setForgotSent(false);
    if (!email) {
      setError("Enter your work email first.");
      return;
    }
    try {
      await fbAuth.sendPasswordResetEmail(normalizeEmail(email));
      setForgotSent(true);
    } catch (err) {
      setError(errorMsg(err.code));
    }
  };

  const isInviteMode = mode === "invite";
  const isSignupLike = mode === "signup" || isInviteMode;
  const isEmailLinkMode = mode === "email-link";
  const hideThirdPartyAuth = isInviteMode || isEmailLinkMode;
  const formTitle = isInviteMode
    ? "Accept your invitation"
    : mode === "signup"
      ? "Get started"
      : isEmailLinkMode
        ? "Complete sign in"
        : "Welcome back";
  const formEyebrow = isInviteMode
    ? "Join your workspace"
    : mode === "signup"
      ? "Create your account"
      : isEmailLinkMode
        ? "Confirm your email"
        : "Sign in to Inlinr";
  const formSub = isInviteMode
    ? `You were invited to ${inviteInfo?.workspaceName || "this workspace"} as ${INLINR_ROLE_META[inviteInfo?.role || "viewer"]?.label || "Viewer"}.`
    : mode === "signup"
      ? "Create an account with your work email."
      : isEmailLinkMode
        ? "Confirm the email address that received the sign-in link."
        : "Sign in with your work email or continue with SSO.";

  return (
    <div className="auth">
      <div className="auth-orbs">
        <span className="orb orb--1" />
        <span className="orb orb--2" />
        <span className="orb orb--3" />
        <span className="orb orb--4" />
      </div>

      <div className="auth-shell">
        <aside className="auth-brand">
          <div className="auth-brand-top">
            <div className="auth-logo">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
                <rect x="4" y="6" width="14" height="2.4" rx="1.2" fill="#fff" />
                <rect x="4" y="11" width="9" height="2.4" rx="1.2" fill="#fff" opacity="0.55" />
                <rect x="4" y="16" width="12" height="2.4" rx="1.2" fill="#fff" opacity="0.30" />
                <circle cx="20" cy="7.2" r="1.5" fill="#608cff" />
              </svg>
              <span className="auth-logo-wm">inlinr<span>.</span></span>
            </div>
            <button className="auth-pill">
              <span className="auth-pill-dot" />
              All systems operational
            </button>
          </div>

          <div className="auth-brand-body">
            <div className="auth-eyebrow">Production-grade email composition</div>
            <h1 className="auth-h1">Author once.<br />Ship everywhere.</h1>
            <p className="auth-lede">Multilingual templates with inline CSS, drag-and-drop authoring, native dark mode, and one-click ZIP export — built for teams that ship real email.</p>

            <div className="auth-points">
              <div className="auth-point">
                <span className="ap-num">01</span>
                <div>
                  <div className="ap-t">Inline CSS, every block</div>
                  <div className="ap-s">No render surprises across Gmail, Outlook, Apple Mail.</div>
                </div>
              </div>
              <div className="auth-point">
                <span className="ap-num">02</span>
                <div>
                  <div className="ap-t">Side-by-side translations</div>
                  <div className="ap-s">Author EN once; spin up 18 locales in the same canvas.</div>
                </div>
              </div>
              <div className="auth-point">
                <span className="ap-num">03</span>
                <div>
                  <div className="ap-t">Live preview links</div>
                  <div className="ap-s">Share a real URL for review — no screenshots, no PDFs.</div>
                </div>
              </div>
            </div>
          </div>

          <div className="auth-brand-foot">
            <div className="auth-quote">
              <div className="auth-quote-body">"We cut our email QA time from days to an afternoon. The locale switcher alone paid for the seat."</div>
              <div className="auth-quote-by">
                <div className="auth-quote-av">JR</div>
                <div>
                  <div className="auth-quote-name">Julia Reinhardt</div>
                  <div className="auth-quote-role">VP Lifecycle, Northwind</div>
                </div>
              </div>
            </div>
          </div>
        </aside>

        <div className="auth-form-wrap">
          <div className="auth-form-card">
            <div className="auth-form-head">
              <div className="auth-form-eyebrow">{formEyebrow}</div>
              <h2 className="auth-form-h">{formTitle}</h2>
              <div className="auth-form-sub">{formSub}</div>
            </div>

            {inviteInfo && (
              <div className="auth-invite-card">
                <div className="auth-invite-card-top">
                  <span className={`role-badge role-${INLINR_ROLE_META[inviteInfo.role || "viewer"]?.tone || "viewer"}`}>
                    {INLINR_ROLE_META[inviteInfo.role || "viewer"]?.label || "Viewer"}
                  </span>
                  <span className="auth-invite-workspace">{inviteInfo.workspaceName || "Workspace"}</span>
                </div>
                <div className="auth-invite-copy">Your owner has already prepared your seat. You can update your first and last name before the account is created.</div>
              </div>
            )}

            {!hideThirdPartyAuth && (
              <>
                <div className="auth-sso-row">
                  <button className="auth-sso" onClick={signInWithGoogle}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 12.2c0-.7-.06-1.4-.18-2.06H12.2v3.9h4.95a4.23 4.23 0 0 1-1.83 2.78v2.3h2.96c1.74-1.6 2.73-3.96 2.73-6.92z" fill="#4285F4" /><path d="M12.2 21c2.46 0 4.52-.82 6.03-2.22l-2.96-2.3c-.82.55-1.87.87-3.07.87-2.36 0-4.36-1.6-5.08-3.74H4.06v2.36A9 9 0 0 0 12.2 21z" fill="#34A853" /><path d="M7.12 13.6a5.42 5.42 0 0 1 0-3.45V7.8H4.06a9 9 0 0 0 0 8.14l3.06-2.36z" fill="#FBBC04" /><path d="M12.2 6.4c1.33 0 2.53.46 3.47 1.36l2.6-2.6C16.72 3.74 14.66 3 12.2 3a9 9 0 0 0-8.14 4.8l3.06 2.36C7.84 8 9.84 6.4 12.2 6.4z" fill="#EA4335" /></svg>
                    Continue with Google
                  </button>
                  <button className="auth-sso" disabled style={{ opacity: 0.4, cursor: "default" }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="#0c0c0e"><path d="M17.05 20.28c-.98.95-2.05.94-3.08.42-1.09-.53-2.08-.5-3.21 0-1.4.62-2.18.43-3.05-.42C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.81 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.53 4.07zM12 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z" /></svg>
                    Continue with Apple
                  </button>
                  <button className="auth-sso auth-sso--sso" disabled style={{ opacity: 0.4, cursor: "default" }}>
                    <Icon name="shield" size={14} />
                    SAML SSO
                  </button>
                </div>

                <div className="auth-divider"><span>or sign in with email</span></div>
              </>
            )}

            <form className="auth-form" onSubmit={submit}>
              {isSignupLike && (
                <div className="auth-name-grid">
                  <label className="auth-field">
                    <span className="auth-field-label">First name</span>
                    <div className="auth-input-wrap">
                      <Icon name="users" size={13} className="auth-input-icon" />
                      <input
                        type="text"
                        value={firstName}
                        onChange={e => setFirstName(e.target.value)}
                        placeholder="Jane"
                        autoComplete="given-name"
                      />
                    </div>
                  </label>

                  <label className="auth-field">
                    <span className="auth-field-label">Last name</span>
                    <div className="auth-input-wrap">
                      <Icon name="users" size={13} className="auth-input-icon" />
                      <input
                        type="text"
                        value={lastName}
                        onChange={e => setLastName(e.target.value)}
                        placeholder="Doe"
                        autoComplete="family-name"
                      />
                    </div>
                  </label>
                </div>
              )}

              <label className="auth-field">
                <span className="auth-field-label">Work email</span>
                <div className="auth-input-wrap">
                  <Icon name="mail" size={13} className="auth-input-icon" />
                  <input
                    type="email"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    placeholder="you@company.com"
                    autoComplete="email"
                    readOnly={isInviteMode}
                  />
                </div>
              </label>

              {(mode === "password" || isSignupLike) && (
                <label className="auth-field">
                  <span className="auth-field-label">
                    Password
                    {mode === "password" && (
                      <button type="button" className="auth-field-link" onClick={() => { setMode("magic"); setMagicLinkSent(false); }}>
                        Use a magic link instead
                      </button>
                    )}
                  </span>
                  <div className="auth-input-wrap">
                    <Icon name="lock" size={13} className="auth-input-icon" />
                    <input
                      type={showPwd ? "text" : "password"}
                      value={password}
                      onChange={e => setPassword(e.target.value)}
                      placeholder="••••••••••••"
                      autoComplete={isSignupLike ? "new-password" : "current-password"}
                    />
                    <button type="button" className="auth-input-action" onClick={() => setShowPwd(s => !s)}>
                      <Icon name="eye" size={13} />
                    </button>
                  </div>
                </label>
              )}

              {mode === "magic" && (
                <div className="auth-magic-note">
                  <Icon name="info" size={14} />
                  <div>
                    <div className="amn-t">{magicLinkSent ? "Magic link sent." : "We'll email a one-time sign-in link."}</div>
                    <div className="amn-s">{magicLinkSent ? "Open the link from your inbox on this same browser if possible." : "No password needed. Link expires in 15 minutes."}</div>
                  </div>
                  <button type="button" className="auth-field-link" onClick={() => setMode("password")}>
                    Use password
                  </button>
                </div>
              )}

              {isEmailLinkMode && (
                <div className="auth-magic-note">
                  <Icon name="mail" size={14} />
                  <div>
                    <div className="amn-t">Confirm the email that received this link.</div>
                    <div className="amn-s">We use it to complete the sign-in securely.</div>
                  </div>
                </div>
              )}

              <div className="auth-options">
                <label className="auth-check">
                  <input type="checkbox" checked={keepSignedIn} onChange={e => setKeepSignedIn(e.target.checked)} />
                  <span className="auth-check-box"><Icon name="check" size={10} /></span>
                  <span>Keep me signed in for 30 days</span>
                </label>
                {!isSignupLike && !isEmailLinkMode && (
                  <a href="#" className="auth-link" onClick={sendPasswordReset}>Forgot password?</a>
                )}
              </div>

              {forgotSent && (
                <div className="auth-success">
                  <Icon name="check" size={13} />
                  <span>Password reset email sent.</span>
                </div>
              )}

              {error && (
                <div className="auth-error">
                  <Icon name="warn" size={13} />
                  <span>{error}</span>
                </div>
              )}

              <button type="submit" className={`auth-submit${loading ? " is-loading" : ""}`} disabled={loading}>
                {loading
                  ? <><span className="auth-spinner" /> {isSignupLike ? "Creating account…" : isEmailLinkMode ? "Signing you in…" : "Signing in…"}</>
                  : <>{isInviteMode ? "Accept invitation" : mode === "signup" ? "Create account" : mode === "magic" ? "Send magic link" : isEmailLinkMode ? "Complete sign in" : "Sign in"} <Icon name="arrowRight" size={13} /></>}
              </button>
            </form>

            <div className="auth-form-foot">
              {isInviteMode ? (
                <>
                  <span>Already have an account for this email?</span>
                  <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); setMode("password"); setError(null); }}>
                    Sign in instead
                  </a>
                </>
              ) : mode === "signup" ? (
                <>
                  <span>Already have an account?</span>
                  <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); setMode("password"); setError(null); }}>
                    Sign in
                  </a>
                </>
              ) : (
                <>
                  <span>New to Inlinr?</span>
                  <a href="#" className="auth-link" onClick={(e) => { e.preventDefault(); setMode("signup"); setError(null); setForgotSent(false); }}>
                    Create an account
                  </a>
                </>
              )}
            </div>
          </div>

          <div className="auth-form-legal">
            <span>© 2026 Inlinr</span>
            <span className="sep" />
            <a href="#" onClick={e => e.preventDefault()}>Terms</a>
            <span className="sep" />
            <a href="#" onClick={e => e.preventDefault()}>Privacy</a>
            <span className="sep" />
            <a href="#" onClick={e => e.preventDefault()}>Security</a>
            <span className="sep" />
            <a href="#" onClick={e => e.preventDefault()}>Status</a>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LoginView });
