// FRM-PROC-01 · Farmer onboarding / register — phone → OTP → profile → welcome
const RegStepper = ({ step, total = 3 }) => (
  <div style={{ marginTop: 20 }}>
    <div style={{ display: "flex", gap: 6, marginBottom: 7 }}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} style={{
          flex: 1, height: 4, borderRadius: 2,
          background: i < step ? "oklch(1 0 0 / 0.95)" : i === step ? "oklch(1 0 0 / 0.55)" : "oklch(1 0 0 / 0.22)"
        }}/>
      ))}
    </div>
    <span style={{ fontSize: 12, fontWeight: 600, color: "oklch(1 0 0 / 0.82)" }}>Step {step + 1} of {total}</span>
  </div>
);

const RegisterScreen = ({ nav, t, setTweak }) => {
  const { Btn, OtpInput } = window.Fm;
  const Ic = window.Icons, FD = window.FD;
  const step = t.regStep; // phone | otp | profile | done

  const [phone, setPhone] = useState("");
  const [otp, setOtp] = useState(t.regOtp === "wrong" ? "118394" : "");
  const [name, setName] = useState("");
  const [region, setRegion] = useState("");
  const [lang, setLang] = useState("English");
  const [prods, setProds] = useState([]);
  const [terms, setTerms] = useState(false);

  const phoneValid = phone.replace(/\s/g, "").length >= 9;
  const profileValid = name.trim().length >= 2 && region && prods.length >= 1 && terms;
  const otpErr = t.regOtp === "wrong";
  const otpExpired = t.regOtp === "expired";

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

  if (step === "done") {
    return (
      <>
        <div className="fm-splash">
          <div className="fm-splash-ring" style={{ background: "var(--avocado-soft)", color: "var(--avocado-fg)" }}>
            <Ic.Leaf size={40}/>
          </div>
          <h2>Welcome to AMOMS</h2>
          <p>Your account is ready, {name || "Mary"}. We'll notify you the moment a buyer posts a requirement for your produce.</p>
        </div>
        <div className="fm-actionbar">
          <Btn variant="primary" icon={Ic.ArrowRight} onClick={() => nav.tab("home")}>Get started</Btn>
        </div>
      </>
    );
  }

  const stepIdx = step === "phone" ? 0 : step === "otp" ? 1 : 2;

  return (
    <>
      <div className="fm-hero">
        <div className="fm-hero-inner">
          <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: 18 }}>
            {step === "phone" ? "Create your account" : step === "otp" ? "Verify your number" : "Set up your profile"}
          </h1>
          <p>
            {step === "phone" ? "Sell your avocados directly to the plant."
              : step === "otp" ? `We sent a 6-digit code to +254 ${phone || "722 905 318"}.`
              : "Tell us what you grow so we can match you to the right buyers."}
          </p>
          <RegStepper step={stepIdx}/>
        </div>
      </div>

      <div className="fm-body">
        <div className="fm-scroll" style={{ paddingTop: 20 }}>
          {step === "phone" && (
            <>
              <div className="fm-field">
                <label className="fm-label">Phone number <span className="req">*</span></label>
                <div className="fm-phone-input">
                  <span className="fm-cc"><span className="flag"/>+254</span>
                  <input className="fm-input" inputMode="tel" placeholder="722 000 000"
                         value={phone} onChange={(e) => setPhone(e.target.value)}/>
                </div>
                <div className="fm-hint">We'll send a one-time code by SMS. Standard rates may apply.</div>
              </div>
              <Btn variant="primary" disabled={!phoneValid} onClick={() => setTweak("regStep", "otp")}>Send OTP</Btn>
              <div style={{ textAlign: "center", marginTop: 18, fontSize: 13.5 }} className="muted">
                Already have an account? <span className="fm-link" onClick={() => nav.replace("login")}>Sign in</span>
              </div>
            </>
          )}

          {step === "otp" && (
            <>
              <OtpInput value={otp} onChange={setOtp} err={otpErr}/>
              {otpErr && <div className="fm-err" style={{ justifyContent: "center", marginTop: 14 }}><Ic.Warning size={14}/>Incorrect code. Please try again.</div>}
              {otpExpired && <div className="fm-warn-note" style={{ justifyContent: "center", marginTop: 14 }}><Ic.Clock size={14}/>Code expired. Request a new one below.</div>}

              <div style={{ textAlign: "center", marginTop: 22, fontSize: 13 }} className="muted">
                {otpExpired
                  ? <span className="fm-link" onClick={() => setTweak("regOtp", "default")}>Resend code</span>
                  : <>Resend code in <b style={{ color: "var(--foreground)", fontVariantNumeric: "tabular-nums" }}>{mmss}</b></>}
              </div>

              <div style={{ marginTop: 26 }}>
                <Btn variant="primary" disabled={otp.length < 6 || otpErr} onClick={() => setTweak("regStep", "profile")}>Verify</Btn>
              </div>
              <div style={{ textAlign: "center", marginTop: 16 }}>
                <span className="fm-link" onClick={() => setTweak("regStep", "phone")}>Change number</span>
              </div>
            </>
          )}

          {step === "profile" && (
            <>
              <div className="fm-field">
                <label className="fm-label">Full name <span className="req">*</span></label>
                <input className="fm-input" placeholder="Enter your full name" value={name} onChange={(e) => setName(e.target.value)}/>
              </div>
              <div className="fm-field">
                <label className="fm-label">Region / district <span className="req">*</span></label>
                <div className="fm-select-wrap">
                  <select className="fm-select" value={region} onChange={(e) => setRegion(e.target.value)}>
                    <option value="">Choose your region</option>
                    {FD.REGIONS.map(r => <option key={r} value={r}>{r}</option>)}
                  </select>
                  <Ic.ChevronDown size={18} className="fm-select-chev"/>
                </div>
              </div>
              <div className="fm-field">
                <label className="fm-label">Preferred language <span className="req">*</span></label>
                <div className="fm-radio-list">
                  {FD.LANGUAGES.map(l => (
                    <button key={l.value} className={`fm-radio ${lang === l.value ? "on" : ""}`} onClick={() => setLang(l.value)}>
                      <span className="fm-radio-dot"/>
                      <div className="fm-radio-text"><div className="fm-radio-label">{l.value}</div><div className="fm-radio-sub" style={{ textAlign: "left" }}>{l.sub}</div></div>
                    </button>
                  ))}
                </div>
              </div>
              <div className="fm-field">
                <label className="fm-label">Products you grow <span className="req">*</span></label>
                <div className="fm-chips wrap">
                  {FD.PRODUCTS.map(p => {
                    const on = prods.includes(p);
                    return (
                      <button key={p} className={`fm-chip pick ${on ? "on" : ""}`}
                              onClick={() => setProds(s => on ? s.filter(x => x !== p) : [...s, p])}>
                        {on && <Ic.Check size={14}/>}{p}
                      </button>
                    );
                  })}
                </div>
                <div className="fm-hint">Add at least one. You'll only see requirements for what you grow.</div>
              </div>
              <button className={`fm-check ${terms ? "on" : ""}`} style={{ marginTop: 4 }} onClick={() => setTerms(v => !v)}>
                <span className="fm-check-box">{terms && <Ic.Check size={15}/>}</span>
                <span className="fm-check-text">I agree to the <a>terms of service</a> and <a>privacy policy</a>.</span>
              </button>
              <div style={{ marginTop: 22 }}>
                <Btn variant="primary" disabled={!profileValid} onClick={() => setTweak("regStep", "done")}>Complete</Btn>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
};

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