// ============================================================
//  Mobile auth — Login + Sign Up (polished)
//  Loads after extras-v2.jsx
// ============================================================
const LOGO_URL = "https://www.nambikkai.com/logo.png";
const APP_NAME_V2 = "Ground Voice";

function AuthField({ label, icon: Ic, children }) {
  return (
    <label style={{ display: "block", marginBottom: 14 }}>
      <span style={{ fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 13.5,
        color: "var(--text)", display: "block", marginBottom: 7 }}>{label}</span>
      {children}
    </label>
  );
}

function AuthInput({ icon: Ic, type = "text", value, onChange, placeholder, trailing }) {
  return (
    <div style={{ position: "relative" }}>
      {Ic && <span style={{ position: "absolute", left: 12, top: 13, color: "var(--subtext)" }}>
        <Ic size={18} /></span>}
      <input type={type} value={value} onChange={onChange} placeholder={placeholder}
        style={{ ...nkInput, paddingLeft: Ic ? 38 : 14, paddingRight: trailing ? 42 : 14 }} />
      {trailing}
    </div>
  );
}

function PwToggle({ show, onToggle }) {
  return (
    <button onClick={onToggle} style={{ position: "absolute", right: 8, top: 9,
      padding: 4, color: "var(--subtext)", background: "none", border: "none", cursor: "pointer" }}>
      {show ? <Icons.eyeOff size={18} /> : <Icons.eye size={18} />}
    </button>
  );
}

function Login({ onLogin }) {
  const [mode, setMode] = React.useState("login");
  // Login fields
  const [user, setUser] = React.useState("");
  const [pw, setPw] = React.useState("");
  const [showPw, setShowPw] = React.useState(false);
  // Signup fields
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [signPw, setSignPw] = React.useState("");
  const [signPwC, setSignPwC] = React.useState("");
  const [showSignPw, setShowSignPw] = React.useState(false);
  const [loc, setLoc] = React.useState("");
  const [agreed, setAgreed] = React.useState(false);

  const validLogin = user.trim().length > 2 && pw.length >= 4;
  const validSignup = name.trim().length > 2 && email.trim().length > 3
    && signPw.length >= 4 && signPw === signPwC && agreed;
  const pwMismatch = signPwC.length > 0 && signPw !== signPwC;

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column",
      background: "var(--blue)" }}>
      {/* ---- brand block ---- */}
      <div style={{ flex: "0 0 auto", padding: "54px 26px 24px", color: "#fff" }}>
        <div style={{ background: "#fff", borderRadius: 14, padding: "10px 14px",
          width: "fit-content", marginBottom: 16 }}>
          <img src={LOGO_URL} alt="Nambikkai" style={{ height: 36, display: "block",
            maxWidth: 140, objectFit: "contain" }}
            onError={(e) => { e.currentTarget.onerror = null; e.currentTarget.src = "assets/logo.png"; }} />
        </div>
        <div style={{ fontFamily: "var(--ff-brand)", fontWeight: 800, fontSize: 28,
          letterSpacing: "-0.02em", lineHeight: 1.05 }}>{APP_NAME_V2}</div>
        <div style={{ fontFamily: "var(--ff-ui)", fontSize: 14, opacity: 0.82, marginTop: 6,
          lineHeight: 1.4 }}>
          நம்பிக்கை · Report the story from where you stand.
        </div>
      </div>

      {/* ---- form sheet ---- */}
      <div style={{ flex: 1, background: "var(--bg-app)", borderTopLeftRadius: 26,
        borderTopRightRadius: 26, padding: "0 24px", display: "flex",
        flexDirection: "column", overflow: "auto" }}>

        {/* tab toggle */}
        <div style={{ display: "flex", margin: "20px 0 18px", background: "var(--bg-sunken)",
          borderRadius: 10, padding: 3, border: "1px solid var(--border)" }}>
          {[["login", "Log in"], ["signup", "Sign up"]].map(([k, l]) => (
            <button key={k} onClick={() => setMode(k)} style={{ flex: 1, padding: "10px 0",
              borderRadius: 8, fontFamily: "var(--ff-ui)", fontSize: 14, fontWeight: 600,
              border: "none", cursor: "pointer", transition: "all .15s ease",
              color: mode === k ? "#fff" : "var(--subtext)",
              background: mode === k ? "var(--blue)" : "transparent",
              boxShadow: mode === k ? "0 2px 8px rgba(0,68,187,0.22)" : "none" }}>{l}</button>
          ))}
        </div>

        {mode === "login" ? (
          <React.Fragment>
            <AuthField label="Username">
              <AuthInput icon={Icons.user} value={user}
                onChange={(e) => setUser(e.target.value)} placeholder="arjun.v" />
            </AuthField>
            <AuthField label="Password">
              <AuthInput icon={Icons.lock} type={showPw ? "text" : "password"} value={pw}
                onChange={(e) => setPw(e.target.value)} placeholder="••••••••"
                trailing={<PwToggle show={showPw} onToggle={() => setShowPw((s) => !s)} />} />
            </AuthField>

            <div style={{ textAlign: "right", marginTop: -6, marginBottom: 18 }}>
              <span style={{ fontFamily: "var(--ff-ui)", fontSize: 13, color: "var(--blue)",
                fontWeight: 600, cursor: "pointer" }}>Forgot password?</span>
            </div>

            <button onClick={() => onLogin("password")} disabled={!validLogin}
              style={{ width: "100%", padding: "14px", borderRadius: 11,
                fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 15.5,
                color: "#fff", background: validLogin ? "var(--blue)" : "var(--border-2)",
                border: "none", cursor: validLogin ? "pointer" : "not-allowed",
                boxShadow: validLogin ? "0 8px 18px rgba(0,68,187,0.28)" : "none",
                transition: "all .15s ease" }}>
              Log in
            </button>

            <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "18px 0" }}>
              <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
              <span style={{ fontFamily: "var(--ff-ui)", fontSize: 12.5,
                color: "var(--subtext)" }}>or</span>
              <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
            </div>

            <button onClick={() => onLogin("google")} style={{ width: "100%", padding: "13px",
              borderRadius: 11, fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 15,
              color: "var(--text)", background: "var(--bg-card)",
              border: "1px solid var(--border-2)", cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 10 }}>
              <Icons.google size={20} /> Continue with Google
            </button>

            <div style={{ marginTop: "auto", padding: "22px 0", textAlign: "center",
              fontFamily: "var(--ff-ui)", fontSize: 13.5, color: "var(--subtext)" }}>
              New reporter? <span onClick={() => setMode("signup")}
                style={{ color: "var(--blue)", fontWeight: 600, cursor: "pointer" }}>
                Sign up</span>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <AuthField label="Full name">
              <AuthInput icon={Icons.user} value={name}
                onChange={(e) => setName(e.target.value)} placeholder="Arjun Vasudevan" />
            </AuthField>
            <AuthField label="Email or phone">
              <AuthInput icon={Icons.mail} value={email}
                onChange={(e) => setEmail(e.target.value)} placeholder="arjun@example.com" />
            </AuthField>
            <AuthField label="Create password">
              <AuthInput icon={Icons.lock} type={showSignPw ? "text" : "password"} value={signPw}
                onChange={(e) => setSignPw(e.target.value)} placeholder="Min. 8 characters"
                trailing={<PwToggle show={showSignPw} onToggle={() => setShowSignPw((s) => !s)} />} />
            </AuthField>
            <AuthField label="Confirm password">
              <div style={{ position: "relative" }}>
                <span style={{ position: "absolute", left: 12, top: 13, color: "var(--subtext)" }}>
                  <Icons.lock size={18} /></span>
                <input type={showSignPw ? "text" : "password"} value={signPwC}
                  onChange={(e) => setSignPwC(e.target.value)} placeholder="Re-enter password"
                  style={{ ...nkInput, paddingLeft: 38,
                    borderColor: pwMismatch ? "var(--red)" : undefined }} />
                {pwMismatch && (
                  <div style={{ fontFamily: "var(--ff-ui)", fontSize: 12, color: "var(--red)",
                    marginTop: 4 }}>Passwords don't match</div>
                )}
              </div>
            </AuthField>
            <AuthField label="Location">
              <AuthInput icon={Icons.pin} value={loc}
                onChange={(e) => setLoc(e.target.value)} placeholder="Coimbatore, TN" />
            </AuthField>

            {/* terms checkbox */}
            <button onClick={() => setAgreed((a) => !a)} style={{ width: "100%", display: "flex",
              alignItems: "flex-start", gap: 11, background: "none", border: "none",
              cursor: "pointer", padding: "4px 0 18px", textAlign: "left" }}>
              <span style={{ width: 22, height: 22, borderRadius: 6, flexShrink: 0,
                display: "grid", placeItems: "center", color: "#fff", marginTop: 1,
                background: agreed ? "var(--blue)" : "var(--bg-card)",
                border: `1.5px solid ${agreed ? "var(--blue)" : "var(--border-2)"}`,
                transition: "all .15s ease" }}>
                {agreed && <Icons.check size={14} sw={2.6} />}
              </span>
              <span style={{ fontFamily: "var(--ff-ui)", fontSize: 13, color: "var(--text-2)",
                lineHeight: 1.4 }}>
                I agree to the <span style={{ color: "var(--blue)", fontWeight: 600 }}>
                  contributor terms</span> and <span style={{ color: "var(--blue)",
                    fontWeight: 600 }}>privacy policy</span>.
              </span>
            </button>

            <button onClick={() => onLogin("signup")} disabled={!validSignup}
              style={{ width: "100%", padding: "14px", borderRadius: 11,
                fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 15.5,
                color: "#fff", background: validSignup ? "var(--blue)" : "var(--border-2)",
                border: "none", cursor: validSignup ? "pointer" : "not-allowed",
                boxShadow: validSignup ? "0 8px 18px rgba(0,68,187,0.28)" : "none",
                transition: "all .15s ease", marginBottom: 8 }}>
              Create account
            </button>

            <div style={{ padding: "14px 0 20px", textAlign: "center",
              fontFamily: "var(--ff-ui)", fontSize: 13.5, color: "var(--subtext)" }}>
              Already registered? <span onClick={() => setMode("login")}
                style={{ color: "var(--blue)", fontWeight: 600, cursor: "pointer" }}>
                Log in</span>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Login, LOGO_URL, APP_NAME_V2 });
