/* global React, Icon, Button */
// ============================================================
// Login — dark, pro
// ============================================================
function Login({ onLogin }) {
  const { useState, useEffect, useRef } = React;
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [wa, setWa] = useState("");
  const [tg, setTg] = useState("");
  const [name, setName] = useState("");
  const [signup, setSignup] = useState(false);
  const [show, setShow] = useState(false);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");
  const [registered, setRegistered] = useState(false);  // popup "inscription prise en compte"
  const gBtn = useRef(null);

  // accès démo (sans compte)
  const go = (role, e) => {
    if (e) e.preventDefault();
    setLoading(true);
    setTimeout(() => onLogin(role), 650);
  };

  // connexion / inscription RÉELLE (compte backend)
  const submit = async (e) => {
    e.preventDefault();
    setErr(""); setLoading(true);
    const r = signup
      ? await window.Backend.register({ name, email, password: pw, whatsapp: wa, telegram: tg })
      : await window.Backend.login(email, pw);
    setLoading(false);
    if (r && r.token && r.user) {
      // inscription d'un NOUVEAU compte -> en attente : on ne connecte PAS, on affiche le popup.
      if (signup && r.user.status === "pending") { setRegistered(true); return; }
      // login normal, OU compte pré-créé par l'Owner "réclamé" (actif) -> accès direct
      window.Backend.setToken(r.token);
      onLogin({ user: r.user });
    } else {
      setErr((r && r.error) || "échec — backend joignable ?");
    }
  };

  // bouton "Continuer avec Google" (si FARM_GOOGLE_CLIENT_ID configuré)
  const gid = window.FARM_GOOGLE_CLIENT_ID || "";
  useEffect(() => {
    if (!gid || !gBtn.current) return;
    const init = () => {
      try {
        window.google.accounts.id.initialize({
          client_id: gid,
          callback: async (resp) => {
            setErr(""); setLoading(true);
            const r = await window.Backend.loginGoogle(resp.credential);
            setLoading(false);
            if (r && r.token && r.user) {
              if (r.user.status === "pending") { setRegistered(true); return; }   // nouveau -> popup d'attente
              window.Backend.setToken(r.token); onLogin({ user: r.user });          // existant validé -> direct
            } else setErr((r && r.error) || "échec Google");
          },
        });
        window.google.accounts.id.renderButton(gBtn.current, { theme: "filled_black", size: "large", width: 320, text: "continue_with" });
      } catch (e) {}
    };
    if (window.google && window.google.accounts) { init(); return; }
    const s = document.createElement("script");
    s.src = "https://accounts.google.com/gsi/client"; s.async = true; s.onload = init;
    document.head.appendChild(s);
  }, [gid]);

  const field = {
    width: "100%", padding: "13px 14px", background: "var(--bg-2)", border: "1px solid var(--border-2)",
    borderRadius: "var(--r-sm)", color: "var(--text)", fontSize: 14.5, outline: "none",
  };

  if (registered) return (
    <div style={{ minHeight: "100%", display: "grid", placeItems: "center", background: "var(--bg)", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 430, textAlign: "center", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: "38px 30px" }} className="app-fade">
        <div style={{ marginBottom: 20, display: "grid", placeItems: "center" }}><Logo /></div>
        <div style={{ width: 58, height: 58, margin: "0 auto 18px", borderRadius: 16, display: "grid", placeItems: "center", background: "var(--accent-soft)", border: "1px solid var(--accent-line)", color: "var(--accent)" }}>
          {React.createElement(Icon.check, { size: 28 })}
        </div>
        <h1 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 10px" }}>Inscription prise en compte ✓</h1>
        <p style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.6, margin: "0 0 24px" }}>
          Votre inscription a bien été enregistrée. <b>Le manager vous acceptera d'ici peu.</b><br />
          Vous pourrez vous connecter dès que votre compte sera validé.
        </p>
        <Button variant="primary" full onClick={() => { setRegistered(false); setSignup(false); setPw(""); }}>Compris</Button>
      </div>
    </div>
  );

  return (
    <div style={{ minHeight: "100%", display: "grid", gridTemplateColumns: "1.1fr 1fr", background: "var(--bg)" }}>
      {/* left — brand / régie */}
      <div style={{ position: "relative", overflow: "hidden", display: "none", borderRight: "1px solid var(--border)" }} className="login-aside">
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(1200px 600px at 20% 10%, rgba(0,224,138,.10), transparent 55%), radial-gradient(900px 500px at 90% 90%, rgba(34,211,238,.10), transparent 50%)" }} />
        <div style={{ position: "absolute", inset: 0, backgroundImage: "linear-gradient(var(--border) 1px,transparent 1px),linear-gradient(90deg,var(--border) 1px,transparent 1px)", backgroundSize: "46px 46px", opacity: .35, maskImage: "radial-gradient(80% 80% at 50% 40%, #000, transparent)" }} />
        <div style={{ position: "relative", height: "100%", padding: 54, display: "flex", flexDirection: "column", justifyContent: "space-between" }}>
          <Logo />
          <div>
            <div className="mono" style={{ color: "var(--accent)", fontSize: 12.5, letterSpacing: ".12em", marginBottom: 16 }}>RÉGIE · CONTRÔLE À DISTANCE</div>
            <h2 style={{ fontSize: 30, lineHeight: 1.18, margin: 0, fontWeight: 700, letterSpacing: "-.02em", maxWidth: 420 }}>
              Pilotez votre parc d'iPhones<br />depuis un seul écran.
            </h2>
            <p style={{ color: "var(--muted)", marginTop: 16, maxWidth: 380, fontSize: 14.5, lineHeight: 1.6 }}>
              Multi-devices, multi-opérateurs. Stream live, télécommande tactile, tâches & audit — en temps réel.
            </p>
            <div style={{ display: "flex", gap: 22, marginTop: 30 }}>
              {[["20", "iPhones connectés"], ["4", "opérateurs actifs"], ["99.2%", "uptime tunnel"]].map(([n, l]) => (
                <div key={l}>
                  <div className="num" style={{ fontSize: 26, fontWeight: 700, color: "var(--text)" }}>{n}</div>
                  <div style={{ fontSize: 11.5, color: "var(--faint)" }}>{l}</div>
                </div>
              ))}
            </div>
          </div>
          <div className="mono" style={{ fontSize: 11.5, color: "var(--faint)" }}>● tunnel chiffré · port de contrôle local jamais exposé</div>
        </div>
      </div>

      {/* right — form */}
      <div style={{ display: "grid", placeItems: "center", padding: 28 }}>
        <form onSubmit={submit} style={{ width: "100%", maxWidth: 360 }} className="app-fade">
          <div style={{ marginBottom: 26 }} className="login-mobile-logo"><Logo /></div>
          <h1 style={{ fontSize: 23, margin: "0 0 6px", fontWeight: 700 }}>{signup ? "Inscription" : "Connexion"}</h1>
          <p style={{ color: "var(--muted)", margin: "0 0 26px", fontSize: 13.5 }}>{signup ? "Créez votre compte opérateur Tempro-Corp." : "Accédez à votre console Tempro-Corp."}</p>

          {signup && (<>
            <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--muted)" }}>Nom complet</label>
            <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Prénom Nom" style={{ ...field, margin: "7px 0 16px" }} autoFocus />
          </>)}

          <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--muted)" }}>Email</label>
          <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="vous@agence.io" style={{ ...field, margin: "7px 0 16px" }} autoFocus={!signup} />

          {signup && (<>
            <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--muted)", display: "flex", alignItems: "center", gap: 7 }}>
              <span style={{ color: "#25D366", display: "grid" }}>{React.createElement(Icon.whatsapp, { size: 16 })}</span>
              Numéro WhatsApp
            </label>
            <input value={wa} onChange={(e) => setWa(e.target.value)} placeholder="+33 6 12 34 56 78" inputMode="tel" style={{ ...field, margin: "7px 0 6px" }} />
            <p style={{ margin: "0 0 16px", fontSize: 11.5, color: "var(--faint)", lineHeight: 1.5 }}>
              Demandé une seule fois, à l'inscription. Permet à votre manager de vous joindre en un clic.
            </p>

            <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--muted)", display: "flex", alignItems: "center", gap: 7 }}>
              <span style={{ color: "#2AABEE", display: "grid" }}>{React.createElement(Icon.telegram, { size: 16 })}</span>
              Pseudo Telegram
            </label>
            <input value={tg} onChange={(e) => setTg(e.target.value)} placeholder="@votrepseudo" style={{ ...field, margin: "7px 0 6px" }} />
            <p style={{ margin: "0 0 16px", fontSize: 11.5, color: "var(--faint)", lineHeight: 1.5 }}>
              On vous contactera via WhatsApp <b>ou</b> Telegram — on est sûrs de pouvoir vous joindre.
            </p>
          </>)}

          <label style={{ fontSize: 12.5, fontWeight: 600, color: "var(--muted)" }}>Mot de passe</label>
          <div style={{ position: "relative", margin: "7px 0 10px" }}>
            <input type={show ? "text" : "password"} value={pw} onChange={(e) => setPw(e.target.value)} placeholder="••••••••" style={field} />
            <button type="button" onClick={() => setShow(s => !s)} style={{ position: "absolute", right: 8, top: "50%", transform: "translateY(-50%)", background: "none", border: "none", color: "var(--faint)", padding: 6, display: "grid" }}>
              {React.createElement(Icon.eye, { size: 18 })}
            </button>
          </div>

          {!signup ? (
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
              <label style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 12.5, color: "var(--muted)" }}>
                <input type="checkbox" defaultChecked style={{ accentColor: "var(--accent)" }} /> Rester connecté
              </label>
              <a style={{ fontSize: 12.5, color: "var(--accent-2)" }}>Mot de passe oublié ?</a>
            </div>
          ) : <div style={{ height: 10 }} />}

          {err && <div style={{ marginBottom: 12, padding: "9px 12px", borderRadius: 9, background: "rgba(255,92,108,.1)", border: "1px solid rgba(255,92,108,.32)", color: "var(--danger)", fontSize: 12.5 }}>{err}</div>}

          <Button type="submit" variant="primary" size="lg" full disabled={loading}>
            {loading ? <span className="spin" style={{ display: "grid" }}>{React.createElement(Icon.refresh, { size: 17 })}</span> : (signup ? "Créer mon compte" : "Se connecter")}
          </Button>

          {gid && <div ref={gBtn} style={{ marginTop: 12, display: "grid", justifyContent: "center" }} />}

          <p style={{ textAlign: "center", fontSize: 12.5, color: "var(--muted)", marginTop: 16 }}>
            {signup ? "Déjà un compte ? " : "Pas encore de compte ? "}
            <a onClick={() => { setSignup(s => !s); setErr(""); }} style={{ color: "var(--accent)", fontWeight: 600, cursor: "pointer" }}>{signup ? "Se connecter" : "S'inscrire"}</a>
          </p>

          <p className="mono" style={{ textAlign: "center", color: "var(--faint)", fontSize: 11, marginTop: 22 }}>session sécurisée · TLS 1.3</p>
        </form>
      </div>
    </div>
  );
}

function Logo({ small }) {
  const { useState, useEffect } = React;
  const [broken, setBroken] = useState(false);
  // thème détecté en direct (body.light) + suivi des changements de thème
  const [light, setLight] = useState(() => { try { return document.body.classList.contains("light"); } catch (e) { return false; } });
  useEffect(() => {
    const obs = new MutationObserver(() => setLight(document.body.classList.contains("light")));
    obs.observe(document.body, { attributes: true, attributeFilter: ["class"] });
    return () => obs.disconnect();
  }, []);
  const h = small ? 40 : 88;
  if (broken) return (
    <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
      <div style={{ width: small ? 28 : 36, height: small ? 28 : 36, borderRadius: 10, position: "relative",
        background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "grid", placeItems: "center",
        boxShadow: "0 6px 18px rgba(0,224,138,.28)" }}>
        <div style={{ width: small ? 11 : 14, height: small ? 15 : 19, borderRadius: 4, border: "2.2px solid #06281c" }} />
      </div>
      <div style={{ fontWeight: 800, fontSize: small ? 15 : 17, letterSpacing: "-.02em" }}>phone labs</div>
    </div>
  );
  // thème SOMBRE -> logo BLANC · thème CLAIR -> logo NOIR (un seul à la fois)
  const src = light ? "assets/phonelabs-dark.png" : "assets/phonelabs-light.png";
  // alignSelf/flex/objectFit -> jamais étiré par un parent flex (panneau de login en colonne)
  return <img key={src} src={src} alt="phone labs" style={{ height: h, width: h, objectFit: "contain", display: "block", alignSelf: "flex-start", flex: "0 0 auto" }} onError={() => setBroken(true)} />;
}

// Écran "compte en attente / refusé" — affiché après login tant que l'Owner n'a pas validé
function PendingScreen({ user, onLogout, rejected }) {
  return (
    <div style={{ minHeight: "100%", display: "grid", placeItems: "center", background: "var(--bg)", padding: 24 }}>
      <div style={{ width: "100%", maxWidth: 440, textAlign: "center", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: "38px 30px" }} className="app-fade">
        <div style={{ marginBottom: 22, display: "grid", placeItems: "center" }}><Logo /></div>
        <div style={{ width: 60, height: 60, margin: "0 auto 18px", borderRadius: 17, display: "grid", placeItems: "center",
          background: rejected ? "rgba(255,92,108,.12)" : "var(--accent-soft)", border: "1px solid " + (rejected ? "rgba(255,92,108,.3)" : "var(--accent-line)"),
          color: rejected ? "var(--danger)" : "var(--accent)" }}>
          {React.createElement(Icon[rejected ? "x" : "clock"], { size: 28 })}
        </div>
        <h1 style={{ fontSize: 20, fontWeight: 700, margin: "0 0 10px" }}>{rejected ? "Accès refusé" : "Compte en attente de validation"}</h1>
        <p style={{ color: "var(--muted)", fontSize: 13.5, lineHeight: 1.6, margin: "0 0 8px" }}>
          {rejected
            ? "Ton accès n'a pas été accordé. Contacte le propriétaire de l'agence si tu penses que c'est une erreur."
            : "Ton inscription est bien enregistrée. Le propriétaire doit valider ton compte et t'attribuer un rôle avant que tu puisses accéder à la console."}
        </p>
        {!rejected && <p className="mono" style={{ fontSize: 11.5, color: "var(--faint)", margin: "0 0 22px" }}>Cette page se débloquera automatiquement dès l'acceptation — pas besoin de recharger.</p>}
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", borderRadius: 11, background: "var(--surface-2)", border: "1px solid var(--border)", marginBottom: 18, textAlign: "left" }}>
          <Avatar user={user} size={34} />
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600 }}>{user.name}</div>
            <div className="mono" style={{ fontSize: 11, color: "var(--faint)", overflow: "hidden", textOverflow: "ellipsis" }}>{user.email}</div>
          </div>
        </div>
        <Button variant="outline" icon="logout" full onClick={onLogout}>Se déconnecter</Button>
      </div>
    </div>
  );
}

Object.assign(window, { Login, Logo, PendingScreen });
