// Login screen — shown when there's no Supabase session.
// Personal-use dashboard, so no sign-up flow: create the auth user once
// in the Supabase dashboard, then sign in here.

function LoginScreen({ onSignedIn }) {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const handleSubmit = async (e) => {
    if (e) e.preventDefault();
    if (!email || !password) {
      setError("Email and password required.");
      return;
    }
    setError(null);
    setSubmitting(true);
    try {
      const { data, error } = await window.sb.auth.signInWithPassword({ email, password });
      if (error) {
        setError(error.message || "Sign-in failed.");
        setSubmitting(false);
        return;
      }
      // Session is set; onAuthStateChange in App will pick it up.
      if (onSignedIn) onSignedIn(data.session);
    } catch (err) {
      setError(err.message || "Network error.");
      setSubmitting(false);
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter") handleSubmit(e);
  };

  return (
    <div style={{
      minHeight: "100vh",
      background: "var(--bg-app)",
      display: "grid",
      placeItems: "center",
      padding: 16,
    }}>
      <div className="card" style={{
        width: "100%",
        maxWidth: 360,
        padding: 28,
        boxShadow: "var(--shadow-md)",
      }}>
        {/* Brand */}
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 22 }}>
          <div style={{
            width: 32, height: 32, borderRadius: 8,
            background: "var(--text-1)",
            display: "grid", placeItems: "center",
            color: "var(--bg)", fontWeight: 700, fontSize: 15,
          }}>L</div>
          <div>
            <div style={{ fontSize: 15, fontWeight: 700, color: "var(--text-1)", letterSpacing: "-0.01em" }}>Ledger</div>
            <div style={{ fontSize: 11, color: "var(--text-muted)" }}>Personal finance</div>
          </div>
        </div>

        <h1 style={{
          fontSize: 18, fontWeight: 600, margin: "0 0 4px",
          color: "var(--text-1)", letterSpacing: "-0.01em",
        }}>Sign in</h1>
        <p style={{ fontSize: 13, color: "var(--text-muted)", margin: "0 0 22px" }}>
          Enter the credentials you set up in Supabase.
        </p>

        {/* Email */}
        <label style={{ fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.04em" }}>
          Email
        </label>
        <div style={{ position: "relative", marginTop: 5, marginBottom: 14 }}>
          <Icon name="mail" size={14} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-muted)", pointerEvents: "none" }}/>
          <input
            type="email"
            value={email}
            onChange={e => setEmail(e.target.value)}
            onKeyDown={handleKeyDown}
            autoComplete="username"
            placeholder="you@example.com"
            disabled={submitting}
            className="input"
            style={{ paddingLeft: 36 }}
          />
        </div>

        {/* Password */}
        <label style={{ fontSize: 11, fontWeight: 600, color: "var(--text-muted)", textTransform: "uppercase", letterSpacing: "0.04em" }}>
          Password
        </label>
        <div style={{ position: "relative", marginTop: 5, marginBottom: 18 }}>
          <Icon name="lock" size={14} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-muted)", pointerEvents: "none" }}/>
          <input
            type="password"
            value={password}
            onChange={e => setPassword(e.target.value)}
            onKeyDown={handleKeyDown}
            autoComplete="current-password"
            placeholder="••••••••"
            disabled={submitting}
            className="input"
            style={{ paddingLeft: 36 }}
          />
        </div>

        {error && (
          <div style={{
            padding: "9px 12px",
            background: "var(--danger-soft)",
            color: "var(--danger)",
            borderRadius: 8,
            fontSize: 12,
            marginBottom: 14,
            display: "flex", alignItems: "center", gap: 6,
          }}>
            <Icon name="alert" size={13}/>
            {error}
          </div>
        )}

        <button
          onClick={handleSubmit}
          disabled={submitting}
          className="btn-primary"
          style={{
            width: "100%",
            justifyContent: "center",
            padding: "10px 14px",
            fontSize: 13,
            opacity: submitting ? 0.6 : 1,
            cursor: submitting ? "wait" : "pointer",
          }}>
          {submitting ? "Signing in…" : (<><Icon name="check" size={14}/> Sign in</>)}
        </button>

        <div style={{ marginTop: 22, paddingTop: 18, borderTop: "1px solid var(--border-subtle)", fontSize: 11, color: "var(--text-muted)", lineHeight: 1.6 }}>
          Forgot your password? Reset it in Supabase: <span style={{ color: "var(--text-2)" }}>Authentication → Users → click your row → Send password recovery</span>.
        </div>
      </div>
    </div>
  );
}

// Loading screen — shown after sign-in while fetching data
function LoadingScreen({ message = "Loading your data…" }) {
  return (
    <div style={{
      minHeight: "100vh",
      background: "var(--bg-app)",
      display: "grid",
      placeItems: "center",
      color: "var(--text-muted)",
      fontSize: 13,
    }}>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
        <div style={{
          width: 32, height: 32, borderRadius: 8,
          background: "var(--text-1)",
          display: "grid", placeItems: "center",
          color: "var(--bg)", fontWeight: 700, fontSize: 15,
        }}>L</div>
        <div>{message}</div>
      </div>
    </div>
  );
}

// Error screen — shown if data load fails
function ErrorScreen({ message, onRetry, onSignOut }) {
  return (
    <div style={{
      minHeight: "100vh",
      background: "var(--bg-app)",
      display: "grid",
      placeItems: "center",
      padding: 16,
    }}>
      <div className="card" style={{ maxWidth: 400, padding: 24, textAlign: "center" }}>
        <Icon name="alert" size={24} style={{ color: "var(--danger)", marginBottom: 10 }}/>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>Something went wrong</div>
        <div style={{ fontSize: 13, color: "var(--text-muted)", marginBottom: 18 }}>{message}</div>
        <div style={{ display: "flex", gap: 8, justifyContent: "center" }}>
          {onRetry && <button onClick={onRetry} className="btn-primary">Retry</button>}
          {onSignOut && <button onClick={onSignOut} className="btn-ghost">Sign out</button>}
        </div>
      </div>
    </div>
  );
}

window.LoginScreen = LoginScreen;
window.LoadingScreen = LoadingScreen;
window.ErrorScreen = ErrorScreen;
