// Login screen — 2 users, password = username

const USERS = {
  baptiste: { name: "Baptiste", color: "#C2603F", avatar: "B" },
  imelda:   { name: "Imelda",   color: "#8E5A8A", avatar: "I" },
};

function useAuth() {
  const [user, setUser] = React.useState(() => {
    try { return localStorage.getItem("maisonnee:user") || null; } catch { return null; }
  });
  const login = (u) => { setUser(u); try { localStorage.setItem("maisonnee:user", u); } catch {} };
  const logout = () => { setUser(null); try { localStorage.removeItem("maisonnee:user"); } catch {} };
  return { user, login, logout };
}

function LoginScreen({ onLogin }) {
  const [pickedUser, setPickedUser] = React.useState(null);
  const [pwd, setPwd] = React.useState("");
  const [err, setErr] = React.useState("");
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (pickedUser && inputRef.current) inputRef.current.focus();
  }, [pickedUser]);

  const [busy, setBusy] = React.useState(false);
  const submit = async (e) => {
    e?.preventDefault?.();
    if (!pickedUser || busy) return;
    if (pwd.trim().toLowerCase() !== pickedUser) {
      setErr("Mot de passe incorrect");
      setTimeout(() => setErr(""), 1800);
      return;
    }
    setBusy(true);
    try {
      await onLogin(pickedUser);
    } catch (e) {
      setErr(e?.message || "Connexion impossible");
    } finally {
      setBusy(false);
    }
  };

  return (
    <div style={{
      minHeight: "100vh",
      display: "flex", alignItems: "center", justifyContent: "center",
      padding: 24,
      background:
        "radial-gradient(900px 500px at 80% 10%, #F9E2CC 0%, transparent 60%)," +
        "radial-gradient(800px 500px at 10% 90%, #EFD6B7 0%, transparent 60%)," +
        "var(--bg)",
    }}>
      <div style={{
        width: "100%", maxWidth: 420,
        background: "var(--surface)",
        border: "1px solid var(--line)",
        borderRadius: 22,
        boxShadow: "var(--shadow-lg)",
        padding: 32,
        position: "relative", overflow: "hidden",
      }}>
        {/* Decorative arcs */}
        <svg width="220" height="220" viewBox="0 0 220 220" style={{ position: "absolute", right: -60, top: -60, opacity: 0.18, pointerEvents: "none" }}>
          <circle cx="110" cy="110" r="90" stroke="#C2603F" strokeWidth="1" fill="none" />
          <circle cx="110" cy="110" r="60" stroke="#C2603F" strokeWidth="1" fill="none" />
          <circle cx="110" cy="110" r="30" stroke="#C2603F" strokeWidth="1" fill="none" />
        </svg>

        <div className="col gap-1" style={{ position: "relative" }}>
          <div className="row gap-2" style={{ alignItems: "center" }}>
            <div style={{
              width: 36, height: 36, borderRadius: 10,
              background: "var(--terracotta)", color: "#FFF8F0",
              display: "flex", alignItems: "center", justifyContent: "center",
              fontFamily: "var(--font-display)", fontSize: 24, fontStyle: "italic",
            }}>m</div>
            <div style={{ fontFamily: "var(--font-display)", fontSize: 26, lineHeight: 1 }}>Maisonnée</div>
          </div>
          <div className="muted small" style={{ marginTop: 6 }}>
            La maison, un peu plus organisée.
          </div>
        </div>

        <div style={{ height: 28 }} />

        {!pickedUser ? (
          <div className="col gap-3" style={{ position: "relative" }}>
            <div className="tiny">Qui se connecte&nbsp;?</div>
            <div className="row gap-3">
              {Object.entries(USERS).map(([key, u]) => (
                <button key={key} onClick={() => { setPickedUser(key); setPwd(""); setErr(""); }}
                  style={{
                    flex: 1, padding: "20px 16px", borderRadius: 16,
                    background: "var(--bg-2)", border: "1px solid var(--line-2)",
                    display: "flex", flexDirection: "column", alignItems: "center", gap: 10,
                    transition: "all .18s ease",
                  }}
                  onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.boxShadow = "var(--shadow)"; e.currentTarget.style.borderColor = u.color + "55"; }}
                  onMouseLeave={(e) => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.boxShadow = "none"; e.currentTarget.style.borderColor = "var(--line-2)"; }}
                >
                  <div style={{
                    width: 56, height: 56, borderRadius: 999,
                    background: u.color, color: "#FFF8F0",
                    display: "flex", alignItems: "center", justifyContent: "center",
                    fontFamily: "var(--font-display)", fontSize: 28,
                  }}>{u.avatar}</div>
                  <div style={{ fontWeight: 600 }}>{u.name}</div>
                </button>
              ))}
            </div>
          </div>
        ) : (
          <form onSubmit={submit} className="col gap-3" style={{ position: "relative" }}>
            <div className="row gap-3" style={{ alignItems: "center" }}>
              <div style={{
                width: 48, height: 48, borderRadius: 999,
                background: USERS[pickedUser].color, color: "#FFF8F0",
                display: "flex", alignItems: "center", justifyContent: "center",
                fontFamily: "var(--font-display)", fontSize: 22,
              }}>{USERS[pickedUser].avatar}</div>
              <div className="col grow" style={{ gap: 2 }}>
                <div style={{ fontFamily: "var(--font-display)", fontSize: 22 }}>Bonjour, {USERS[pickedUser].name}</div>
                <div className="small muted">Entrez votre mot de passe</div>
              </div>
              <button type="button" onClick={() => setPickedUser(null)} style={{ color: "var(--ink-3)", fontSize: 12 }}>changer</button>
            </div>
            <input
              ref={inputRef}
              type="password"
              value={pwd}
              onChange={(e) => setPwd(e.target.value)}
              placeholder="Mot de passe"
              style={{
                width: "100%", padding: "12px 14px",
                background: "var(--bg-2)",
                border: `1px solid ${err ? "var(--prio-high)" : "var(--line-2)"}`,
                borderRadius: 12, fontSize: 16, outline: "none",
                transition: "border-color .15s ease",
              }}
            />
            {err && <div className="small" style={{ color: "var(--prio-high)" }}>{err}</div>}
            <Button variant="primary" type="submit" disabled={busy} style={{ justifyContent: "center", opacity: busy ? 0.6 : 1 }}>
              {busy ? "Connexion…" : "Se connecter"}
            </Button>
            <div className="small muted" style={{ textAlign: "center", marginTop: 4 }}>
              Mot de passe : votre prénom en minuscules
            </div>
          </form>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { USERS, useAuth, LoginScreen });
