// FRM-PROC-02 · Farmer login — single-screen phone + OTP
const LoginScreen = ({ nav, t, setTweak }) => {
  const { Btn, OtpInput, Banner } = window.Fm;
  const Ic = window.Icons;
  const otpStep = t.loginStep === "otp";
  const [phone, setPhone] = useState("722 905 318");
  const [otp, setOtp] = useState(t.loginState === "wrong" ? "550321" : "");
  const phoneValid = phone.replace(/\s/g, "").length >= 9;
  const invalid = t.loginState === "invalid";
  const wrong = t.loginState === "wrong";
  const locked = t.loginState === "locked";

  const [secs, setSecs] = useState(300);
  useEffect(() => {
    if (!otpStep) return;
    setSecs(300);
    const id = setInterval(() => setSecs(s => (s > 0 ? s - 1 : 0)), 1000);
    return () => clearInterval(id);
  }, [otpStep]);
  const mmss = `${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, "0")}`;

  return (
    <>
      <div className="fm-hero">
        <div className="fm-hero-inner" style={{ paddingTop: 24, paddingBottom: 34 }}>
          <div className="fm-brand">
            <span className="fm-brand-mark"><Ic.Leaf size={17}/></span>
            <div>
              <div className="fm-brand-name">AMOMS</div>
              <div className="fm-brand-sub">Farmer app · Murang'a</div>
            </div>
          </div>
          <h1 style={{ marginTop: 26 }}>Welcome back</h1>
          <p>Sign in with your phone number to see today's requirements.</p>
        </div>
      </div>

      <div className="fm-body">
        <div className="fm-scroll" style={{ paddingTop: 22 }}>
          {locked && (
            <div style={{ marginBottom: 18 }}>
              <Banner tone="danger" icon={Ic.Lock} title="Too many attempts"
                      desc="For your security, sign-in is paused. Try again in 10 minutes."/>
            </div>
          )}

          <div className="fm-field">
            <label className="fm-label">Phone number</label>
            <div className="fm-phone-input">
              <span className="fm-cc"><span className="flag"/>+254</span>
              <input className={`fm-input ${invalid ? "err" : ""}`} inputMode="tel" placeholder="722 000 000"
                     value={phone} onChange={(e) => setPhone(e.target.value)} disabled={otpStep}/>
            </div>
            {invalid && (
              <div className="fm-err"><Ic.Warning size={14}/>
                No account found for this number.&nbsp;<span className="fm-link" onClick={() => nav.replace("register")}>Register?</span>
              </div>
            )}
          </div>

          {otpStep && (
            <div className="fm-field">
              <label className="fm-label">Enter the 6-digit code</label>
              <OtpInput value={otp} onChange={setOtp} err={wrong}/>
              {wrong && <div className="fm-err" style={{ justifyContent: "center", marginTop: 12 }}><Ic.Warning size={14}/>Incorrect code. Please try again.</div>}
              <div style={{ textAlign: "center", marginTop: 16, fontSize: 13 }} className="muted">
                Resend code in <b style={{ color: "var(--foreground)", fontVariantNumeric: "tabular-nums" }}>{mmss}</b>
              </div>
            </div>
          )}

          <div style={{ marginTop: 8 }}>
            {!otpStep
              ? <Btn variant="primary" disabled={!phoneValid || locked} onClick={() => setTweak("loginStep", "otp")}>Send OTP</Btn>
              : <Btn variant="primary" disabled={otp.length < 6 || wrong} onClick={() => nav.tab("home")}>Verify &amp; sign in</Btn>}
          </div>

          <button className="fm-btn fm-btn-outline" style={{ marginTop: 12 }} onClick={() => nav.tab("home")}>
            <Ic.Fingerprint size={18}/> Use fingerprint
          </button>

          <div className="fm-divider"/>
          <div style={{ textAlign: "center", fontSize: 13.5 }} className="muted">
            Don't have an account? <span className="fm-link" onClick={() => nav.replace("register")}>Register</span>
          </div>
          <div style={{ textAlign: "center", fontSize: 13.5, marginTop: 12 }}>
            <span className="fm-link" onClick={() => nav.go("home")}><Ic.HelpCircle size={14} style={{ verticalAlign: "-2px", marginRight: 4 }}/>Need help?</span>
          </div>
        </div>
      </div>
    </>
  );
};

window.FarmerPages = Object.assign(window.FarmerPages || {}, {
  login: { brandStatus: true, render: (ctx) => <LoginScreen {...ctx}/> },
});
