function LoginScreen({
  mode,
  user,
  sites,
  activeSiteId,
  onLogin,
  onRegister,
  onDiscoverShops,
  onLinkShopify,
  onConnectWebsite,
  onGoogleLogin,
  onSelect,
  onLogout,
  loading,
  error,
}) {
  const landingIntent = React.useMemo(() => {
    const empty = { signup: false, platform: "" };
    try {
      const p = new URLSearchParams(window.location.search);
      const signup = p.get("signup") === "1";
      const platform = (p.get("platform") || "").toLowerCase();
      if (signup || platform) {
        sessionStorage.setItem("guy_landing_intent", JSON.stringify({ signup, platform }));
      }
      const stored = JSON.parse(sessionStorage.getItem("guy_landing_intent") || "null");
      return {
        signup: signup || !!stored?.signup,
        platform: platform || stored?.platform || "",
      };
    } catch {
      return empty;
    }
  }, []);

  const [authView, setAuthView] = React.useState(landingIntent.signup ? "signup" : "login");
  const [signupType, setSignupType] = React.useState(
    landingIntent.signup && landingIntent.platform === "wordpress" ? "web" : null,
  );
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [passwordConfirm, setPasswordConfirm] = React.useState("");
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const [companyName, setCompanyName] = React.useState("");
  const [siret, setSiret] = React.useState("");
  const [vatNumber, setVatNumber] = React.useState("");
  const [merchantEmail, setMerchantEmail] = React.useState("");
  const [discoveredShops, setDiscoveredShops] = React.useState(null);
  const [localError, setLocalError] = React.useState("");
  const [linkMode, setLinkMode] = React.useState(null);

  React.useEffect(() => {
    if (mode !== "pick-site") return;
    if (landingIntent.platform !== "wordpress") return;
    if (sites.length) return;
    if (linkMode) return;
    setLinkMode("website");
  }, [mode, landingIntent.platform, sites.length, linkMode]);
  const [siteUrl, setSiteUrl] = React.useState("");
  const [siteName, setSiteName] = React.useState("");

  const displayError = error || localError;

  function resetSignup() {
    setSignupType(null);
    setDiscoveredShops(null);
    setLocalError("");
  }

  async function handleLoginSubmit(e) {
    e.preventDefault();
    setLocalError("");
    onLogin({ email: email.trim(), password });
  }

  async function handleDiscover(e) {
    e.preventDefault();
    setLocalError("");
    try {
      const shops = await onDiscoverShops(merchantEmail.trim());
      setDiscoveredShops(shops);
      if (!shops.length) {
        setLocalError(
          "Aucune boutique trouvée pour cet email. Installez d'abord l'app SEO GUY sur Shopify.",
        );
      }
    } catch (err) {
      setLocalError(err.message || "Recherche impossible.");
    }
  }

  async function handleShopifyRegister(e) {
    e.preventDefault();
    setLocalError("");
    onRegister({
      type: "shopify",
      email: merchantEmail.trim(),
      password,
      passwordConfirm,
      firstName: firstName.trim() || undefined,
      lastName: lastName.trim() || undefined,
    });
  }

  async function handleWebRegister(e) {
    e.preventDefault();
    setLocalError("");
    onRegister({
      type: "web",
      email: email.trim(),
      password,
      passwordConfirm,
      firstName: firstName.trim(),
      lastName: lastName.trim(),
      companyName: companyName.trim(),
      siret: siret.trim() || undefined,
      vatNumber: vatNumber.trim() || undefined,
    });
  }

  async function handleLinkWebsite(e) {
    e.preventDefault();
    setLocalError("");
    try {
      await onConnectWebsite({
        siteUrl: siteUrl.trim(),
        siteName: siteName.trim() || undefined,
      });
    } catch (err) {
      setLocalError(err.message || "Rattachement impossible.");
    }
  }

  async function handleLinkShopify(e) {
    e.preventDefault();
    setLocalError("");
    try {
      await onLinkShopify(merchantEmail.trim());
    } catch (err) {
      setLocalError(err.message || "Rattachement impossible.");
    }
  }

  function siteLabel(site) {
    if (site.platform === "WEBSITE") {
      return site.shopName || "Site web";
    }
    return site.shopName || site.shop;
  }

  function siteSubtitle(site) {
    if (site.platform === "WEBSITE") {
      return site.shopDomain || site.shop.replace(/^website:/, "");
    }
    return site.shop;
  }

  if (mode === "auth") {
    if (authView === "signup" && !signupType) {
      return (
        <div className="sg-login">
          <div className="sg-login-card sg-login-card-wide">
            <img src={POSE.avatar} alt="SEO GUY" className="sg-login-logo" />
            <h1>Créer un compte</h1>
            <p className="sg-login-sub">Choisissez votre profil pour démarrer.</p>
            {displayError && <p className="sg-login-error">{displayError}</p>}
            <div className="sg-signup-choices">
              <button
                type="button"
                className="sg-signup-choice"
                disabled={loading}
                onClick={() => setSignupType("shopify")}
              >
                <strong>J'utilise Shopify</strong>
                <span>Email Shopify → boutiques rattachées automatiquement</span>
              </button>
              <button
                type="button"
                className="sg-signup-choice"
                disabled={loading}
                onClick={() => setSignupType("web")}
              >
                <strong>Compte web sans Shopify</strong>
                <span>Société, SIRET, TVA — rattachez Shopify plus tard</span>
              </button>
            </div>
            <button
              type="button"
              className="sg-btn-ghost sg-login-back"
              onClick={() => { setAuthView("login"); resetSignup(); }}
            >
              ← Retour connexion
            </button>
          </div>
        </div>
      );
    }

    if (authView === "signup" && signupType === "shopify") {
      return (
        <div className="sg-login">
          <div className="sg-login-card sg-login-card-wide">
            <h1>Compte marchand Shopify</h1>
            <p className="sg-login-sub">
              Saisissez l'email utilisé sur Shopify. Nous retrouverons vos boutiques
              où l'app SEO GUY est installée.
            </p>
            {displayError && <p className="sg-login-error">{displayError}</p>}
            <form className="sg-login-form" onSubmit={discoveredShops ? handleShopifyRegister : handleDiscover}>
              <label className="sg-login-field">
                <span>Email Shopify</span>
                <input type="email" value={merchantEmail} onChange={(e) => setMerchantEmail(e.target.value)} required disabled={loading} />
              </label>
              {discoveredShops && discoveredShops.length > 0 && (
                <>
                  <div className="sg-discovered-shops">
                    <p><strong>{discoveredShops.length}</strong> boutique(s) trouvée(s) :</p>
                    <ul>
                      {discoveredShops.map((s) => (
                        <li key={s.id}>{s.shopName || s.shop}</li>
                      ))}
                    </ul>
                  </div>
                  <label className="sg-login-field">
                    <span>Prénom (optionnel)</span>
                    <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} disabled={loading} />
                  </label>
                  <label className="sg-login-field">
                    <span>Nom (optionnel)</span>
                    <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} disabled={loading} />
                  </label>
                  <label className="sg-login-field">
                    <span>Mot de passe</span>
                    <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required disabled={loading} minLength={8} />
                  </label>
                  <label className="sg-login-field">
                    <span>Confirmer le mot de passe</span>
                    <input type="password" value={passwordConfirm} onChange={(e) => setPasswordConfirm(e.target.value)} required disabled={loading} minLength={8} />
                  </label>
                </>
              )}
              <button type="submit" className="sg-btn-primary sg-login-submit" disabled={loading}>
                {loading ? "…" : discoveredShops ? "Créer mon compte" : "Rechercher mes boutiques"}
              </button>
            </form>
            <button type="button" className="sg-btn-ghost sg-login-back" onClick={resetSignup}>← Changer de profil</button>
          </div>
        </div>
      );
    }

    if (authView === "signup" && signupType === "web") {
      return (
        <div className="sg-login">
          <div className="sg-login-card sg-login-card-wide">
            <h1>Compte web SEO GUY</h1>
            <p className="sg-login-sub">
              {landingIntent.platform === "wordpress"
                ? "Parcours WordPress : après inscription, rattachez l’URL de votre site puis le plugin Assistant Guy."
                : "Sans boutique Shopify pour l'instant — vous pourrez synchroniser plus tard."}
            </p>
            {displayError && <p className="sg-login-error">{displayError}</p>}
            <form className="sg-login-form" onSubmit={handleWebRegister}>
              <div className="sg-login-row">
                <label className="sg-login-field">
                  <span>Prénom</span>
                  <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} required disabled={loading} />
                </label>
                <label className="sg-login-field">
                  <span>Nom</span>
                  <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} required disabled={loading} />
                </label>
              </div>
              <label className="sg-login-field">
                <span>Société</span>
                <input type="text" value={companyName} onChange={(e) => setCompanyName(e.target.value)} required disabled={loading} />
              </label>
              <div className="sg-login-row">
                <label className="sg-login-field">
                  <span>SIRET</span>
                  <input type="text" value={siret} onChange={(e) => setSiret(e.target.value)} disabled={loading} />
                </label>
                <label className="sg-login-field">
                  <span>N° TVA</span>
                  <input type="text" value={vatNumber} onChange={(e) => setVatNumber(e.target.value)} disabled={loading} />
                </label>
              </div>
              <label className="sg-login-field">
                <span>Email</span>
                <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required disabled={loading} />
              </label>
              <label className="sg-login-field">
                <span>Mot de passe</span>
                <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} required disabled={loading} minLength={8} />
              </label>
              <label className="sg-login-field">
                <span>Confirmer le mot de passe</span>
                <input type="password" value={passwordConfirm} onChange={(e) => setPasswordConfirm(e.target.value)} required disabled={loading} minLength={8} />
              </label>
              <button type="submit" className="sg-btn-primary sg-login-submit" disabled={loading}>
                {loading ? "Création…" : "Créer mon compte"}
              </button>
            </form>
            <button type="button" className="sg-btn-ghost sg-login-back" onClick={resetSignup}>← Changer de profil</button>
          </div>
        </div>
      );
    }

    return (
      <div className="sg-login">
        <div className="sg-login-card">
          <img src={POSE.avatar} alt="SEO GUY" className="sg-login-logo" />
          <h1>SEO GUY — Back-office web</h1>
          <p className="sg-login-sub">Connectez-vous pour accéder à vos boutiques.</p>
          {displayError && <p className="sg-login-error">{displayError}</p>}
          <div className="sg-login-social">
            <button type="button" className="sg-login-social-btn sg-login-social-google sg-login-social-only" disabled={loading} onClick={onGoogleLogin}>
              <span className="sg-login-social-icon" aria-hidden="true">G</span>
              Continuer avec Google
            </button>
          </div>
          <div className="sg-login-divider"><span>ou par email</span></div>
          <form className="sg-login-form" onSubmit={handleLoginSubmit}>
            <label className="sg-login-field">
              <span>Email</span>
              <input type="email" autoComplete="username" value={email} onChange={(e) => setEmail(e.target.value)} disabled={loading} required />
            </label>
            <label className="sg-login-field">
              <span>Mot de passe</span>
              <input type="password" autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} disabled={loading} required />
            </label>
            <button type="submit" className="sg-btn-primary sg-login-submit" disabled={loading}>
              {loading ? "Connexion…" : "Se connecter"}
            </button>
          </form>
          <p className="sg-login-switch">
            Pas encore de compte ?{" "}
            <button type="button" className="sg-link-btn" onClick={() => setAuthView("signup")}>Créer un compte</button>
          </p>
        </div>
      </div>
    );
  }

  const pickerTitle =
    linkMode === "shopify"
      ? "Rattacher Shopify"
      : linkMode === "website"
        ? "Rattacher un site web"
        : "Choisissez un site";

  return (
    <div className="sg-login">
      <div className="sg-login-card sg-login-card-wide">
        <img src={POSE.avatar} alt="SEO GUY" className="sg-login-logo" />
        <h1>{pickerTitle}</h1>
        <p className="sg-login-sub">
          Connecté en tant que <strong>{user?.email || "—"}</strong>
        </p>
        {displayError && <p className="sg-login-error">{displayError}</p>}

        {linkMode === "shopify" ? (
          <form className="sg-login-form" onSubmit={handleLinkShopify}>
            <p className="sg-login-sub">
              Email utilisé sur Shopify — nous synchroniserons les boutiques installées.
            </p>
            <label className="sg-login-field">
              <span>Email Shopify</span>
              <input type="email" value={merchantEmail} onChange={(e) => setMerchantEmail(e.target.value)} required disabled={loading} />
            </label>
            <button type="submit" className="sg-btn-primary sg-login-submit" disabled={loading}>
              {loading ? "Synchronisation…" : "Rattacher mes boutiques"}
            </button>
            <button type="button" className="sg-btn-ghost sg-login-back" onClick={() => setLinkMode(null)}>Annuler</button>
          </form>
        ) : linkMode === "website" ? (
          <form className="sg-login-form" onSubmit={handleLinkWebsite}>
            <p className="sg-login-sub">
              WordPress, site vitrine ou blog — sans boutique Shopify.
              Ensuite, Guy vous demandera d’installer le plugin et de coller le mot de passe d’application.
            </p>
            <label className="sg-login-field">
              <span>Adresse du site</span>
              <input
                type="text"
                placeholder="https://verveineconsulting.com"
                value={siteUrl}
                onChange={(e) => setSiteUrl(e.target.value)}
                required
                disabled={loading}
              />
            </label>
            <label className="sg-login-field">
              <span>Nom affiché (optionnel)</span>
              <input
                type="text"
                placeholder={user?.companyName || "Verveine Consulting"}
                value={siteName}
                onChange={(e) => setSiteName(e.target.value)}
                disabled={loading}
              />
            </label>
            <button type="submit" className="sg-btn-primary sg-login-submit" disabled={loading}>
              {loading ? "Rattachement…" : "Rattacher ce site"}
            </button>
            <button type="button" className="sg-btn-ghost sg-login-back" onClick={() => setLinkMode(null)}>Annuler</button>
          </form>
        ) : (
          <>
            <div className="sg-login-list">
              {sites.map((s) => (
                <button
                  key={s.id}
                  type="button"
                  className={`sg-login-site${s.id === activeSiteId ? " is-active" : ""}`}
                  disabled={loading}
                  onClick={() => onSelect(s.id)}
                >
                  <strong>{siteLabel(s)}</strong>
                  <span>{siteSubtitle(s)}</span>
                </button>
              ))}
            </div>
            {!sites.length && !loading && (
              <p className="sg-login-sub">
                Aucun site rattaché. Connectez votre site web (WordPress) ou une boutique Shopify.
              </p>
            )}
            <button
              type="button"
              className="sg-btn-primary sg-login-submit"
              disabled={loading}
              onClick={() => {
                setLocalError("");
                if (!siteName && user?.companyName) setSiteName(user.companyName);
                setLinkMode("website");
              }}
            >
              Rattacher un site web
            </button>
            <button type="button" className="sg-btn-secondary sg-login-link-shopify" disabled={loading} onClick={() => setLinkMode("shopify")}>
              Rattacher une boutique Shopify
            </button>
          </>
        )}

        {loading && <p className="sg-login-sub">Chargement…</p>}
        <button type="button" className="sg-btn-ghost sg-login-logout" disabled={loading} onClick={onLogout}>
          Se déconnecter
        </button>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
