// Onboarding steps 2-5: identity, personal, income, housing
// (Documents, scanning, matches in part 3)

function OnbIdentity({ data, setData, onNext, onPrev, t }) {
  const [phase, setPhase] = React.useState("id"); // id | otp | verified
  const [otpDigits, setOtpDigits] = React.useState(["", "", "", ""]);
  const refs = [React.useRef(), React.useRef(), React.useRef(), React.useRef()];

  React.useEffect(() => {
    if (phase === "verified") setTimeout(onNext, 1100);
  }, [phase]);

  function onIdSubmit() {
    setData({ ...data, nationalId: "OM-1989-100245" });
    setPhase("otp");
    setTimeout(() => refs[0].current?.focus(), 100);
  }
  function onOtpChange(i, v) {
    if (v && !/^\d$/.test(v)) return;
    const next = [...otpDigits];
    next[i] = v;
    setOtpDigits(next);
    if (v && i < 3) refs[i+1].current?.focus();
    if (next.every(d => d) && next.join("").length === 4) {
      setTimeout(() => setPhase("verified"), 500);
    }
  }

  return (
    <OnbStep
      eyebrow={t("Identity verification","تحقق الهوية")}
      title={phase === "id" ? t("Let's start with your National ID.","لنبدأ ببطاقتك المدنية.") :
             phase === "otp" ? t("Check your phone.","تحقق من هاتفك.") :
             t("Verified.","تم التحقق.")}
      sub={phase === "id" ? t("We'll pull your basic profile from the Civil Registry. Faster than typing it.","سنسحب ملفك الأساسي من السجل المدني.") :
           phase === "otp" ? t("We sent a 4-digit code to •••• 4467. It expires in 5 minutes.","أرسلنا رمزاً مكوناً من 4 أرقام.") :
           t("Your identity is confirmed. Pre-filling your details now…","تم التأكد. نقوم بتعبئة بياناتك…")}
      secondary={phase === "id" ? t("Back","رجوع") : null}
      primary={phase === "id" ? t("Send verification code","إرسال رمز التحقق") : null}
      onSecondary={onPrev}
      onPrimary={onIdSubmit}
    >
      {phase === "id" && (
        <div className="onb-field-group">
          <div className="onb-field-large">
            <div className="field-label">{t("National ID number","الرقم الوطني")}</div>
            <input className="input lg" placeholder="OM-1989-100245" defaultValue="OM-1989-100245"/>
            <div className="tiny muted" style={{marginTop:6}}>{t("Format: OM-YYYY-NNNNNN","التنسيق")}</div>
          </div>
          <div className="onb-sources">
            <div className="onb-sources-head">{t("We'll automatically check with:","سنتحقق تلقائياً مع:")}</div>
            <div className="onb-source"><Icon name="id" size={14}/> {t("Civil Registry","السجل المدني")}</div>
            <div className="onb-source"><Icon name="phone_icon" size={14}/> {t("Telecom OTP","رمز الاتصالات")}</div>
            <div className="onb-source"><Icon name="shield" size={14}/> {t("Records — encrypted & immutable","السجلات مشفرة")}</div>
          </div>
        </div>
      )}
      {phase === "otp" && (
        <div className="onb-otp">
          <div className="otp-row">
            {otpDigits.map((d, i) => (
              <input key={i} ref={refs[i]} className="otp-input" value={d}
                onChange={(e) => onOtpChange(i, e.target.value.slice(-1))}
                onKeyDown={(e) => e.key === "Backspace" && !d && i > 0 && refs[i-1].current?.focus()}
                inputMode="numeric" maxLength={1}/>
            ))}
          </div>
          <div className="muted text-13" style={{textAlign:"center"}}>
            {t("Resend code in","إعادة الإرسال خلال")} <strong>4:48</strong>
          </div>
        </div>
      )}
      {phase === "verified" && (
        <div className="onb-verified">
          <div className="onb-verified-check"><Icon name="check" size={32}/></div>
          <div className="onb-verified-fill">
            <div className="fill-row"><Icon name="check" size={11}/> {t("Full name","الاسم الكامل")}</div>
            <div className="fill-row"><Icon name="check" size={11}/> {t("Date of birth","تاريخ الميلاد")}</div>
            <div className="fill-row"><Icon name="check" size={11}/> {t("Marital status","الحالة الاجتماعية")}</div>
            <div className="fill-row"><Icon name="check" size={11}/> {t("Registered address","العنوان المسجل")}</div>
          </div>
        </div>
      )}
    </OnbStep>
  );
}

function OnbPersonal({ data, setData, citizen, onNext, onPrev, t }) {
  return (
    <OnbStep
      eyebrow={t("Personal details","التفاصيل الشخصية")}
      title={t("Confirm what we know.","أكد ما نعرفه.")}
      sub={t("This is what the Civil Registry has on file. Tap any field to correct it.","هذا ما لدى السجل المدني.")}
      secondary={t("Back","رجوع")}
      primary={t("Looks right · continue","يبدو صحيحاً · متابعة")}
      onSecondary={onPrev}
      onPrimary={onNext}
    >
      <div className="onb-card-grid">
        <ReadField label={t("Full name","الاسم الكامل")} value={citizen.name} hint="From Civil Registry"/>
        <ReadField label={t("Arabic name","الاسم بالعربية")} value={citizen.nameAr} hint="From Civil Registry"/>
        <ReadField label={t("Age","العمر")} value={`${citizen.age} ${t("years","سنة")}`} hint="From DOB"/>
        <ReadField label={t("Marital status","الحالة الاجتماعية")} value={citizen.maritalStatus} hint="Confirmed"/>
        <ReadField label={t("Governorate","المحافظة")} value={citizen.governorate} hint="From address"/>
        <ReadField label={t("Wilayat","الولاية")} value={citizen.wilayat} hint="From address"/>
      </div>
      <div className="onb-helper">
        <Icon name="info" size={13} style={{color:"var(--brand-teal)"}}/>
        <span className="text-13">{t("Need to update something? We'll route the change through the Civil Registry — usually 24 hours.","لتحديث المعلومات نوجه الطلب للسجل المدني.")}</span>
      </div>
    </OnbStep>
  );
}

function ReadField({ label, value, hint }) {
  return (
    <div className="read-field">
      <div className="field-label">{label}</div>
      <div className="read-value">{value}</div>
      <div className="tiny muted">{hint}</div>
    </div>
  );
}

function OnbIncome({ data, setData, onNext, onPrev, t }) {
  return (
    <OnbStep
      eyebrow={t("Income & employment","الدخل والعمل")}
      title={t("How much do you earn?","كم تكسب؟")}
      sub={t("We'll pull a 6-month bank statement once authorised. This sets your financing band and monthly installment.","سنسحب كشف حساب 6 أشهر.")}
      secondary={t("Back","رجوع")}
      primary={t("Continue","متابعة")}
      onSecondary={onPrev}
      onPrimary={onNext}
    >
      <div className="onb-income">
        <div className="onb-field-large">
          <div className="field-label">{t("Monthly income","الدخل الشهري")}</div>
          <div className="onb-currency-input">
            <span className="currency-prefix">OMR</span>
            <input className="input lg currency" type="number" value={data.monthlyIncome}
              onChange={(e) => setData({...data, monthlyIncome: +e.target.value})}/>
            <span className="currency-suffix">/ {t("month","شهر")}</span>
          </div>
          <div className="onb-band">
            <div className="onb-band-track">
              <div className="onb-band-fill" style={{
                left: `${Math.min(100, (data.monthlyIncome / 3000) * 100)}%`,
              }}/>
            </div>
            <div className="onb-band-labels">
              <span>OMR 0</span>
              <span className="onb-band-marker" style={{left: "13.3%"}}>400</span>
              <span className="onb-band-marker" style={{left: "33%"}}>1,000</span>
              <span>3,000</span>
            </div>
            <div className="onb-band-tiers">
              <div className="band-tier" style={{left:0, right:"86.7%"}}>1%</div>
              <div className="band-tier mid" style={{left:"13.3%", right:"67%"}}>3%</div>
              <div className="band-tier high" style={{left:"33%", right:0}}>4%</div>
            </div>
            <div className="tiny muted" style={{textAlign:"center", marginTop:6}}>
              {t("ISKAN profit rate bands","شرائح معدل الربح")}
            </div>
          </div>
        </div>

        <div className="onb-grid-2">
          <div>
            <div className="field-label">{t("Employer type","نوع العمل")}</div>
            <div className="filter-chip-group" style={{flexWrap:"wrap"}}>
              {["Government","Private","Self-employed","Retired"].map(o => (
                <button key={o} className={`chip ${data.employerType === o ? "active" : ""}`}
                  onClick={() => setData({...data, employerType: o})}>{t(o,o)}</button>
              ))}
            </div>
          </div>
          <div>
            <div className="field-label">{t("Employer","جهة العمل")}</div>
            <input className="input" value={data.employer}
              onChange={(e) => setData({...data, employer: e.target.value})}/>
          </div>
        </div>

        <div className="onb-affordability-preview">
          <div className="label-eyebrow">{t("Preview your affordability","معاينة قدرتك")}</div>
          <div className="row" style={{justifyContent:"space-between", alignItems:"baseline", marginTop:6}}>
            <div>
              <div className="serif-big">OMR {Math.round((window.calculateLoan({monthlyIncomeOmr: data.monthlyIncome}, 60000, "normal")).emi)}</div>
              <div className="tiny muted">/ {t("month over 25 years","شهر على مدى 25 سنة")}</div>
            </div>
            <div style={{textAlign:"right"}}>
              <div className="serif-big">OMR {data.monthlyIncome <= 400 ? 1 : data.monthlyIncome <= 1000 ? 3 : 4}<span className="muted text-13">%</span></div>
              <div className="tiny muted">{t("Profit rate","معدل الربح")}</div>
            </div>
            <div style={{textAlign:"right"}}>
              <div className="serif-big">OMR {data.monthlyIncome > 1000 ? "80,000" : "60,000"}</div>
              <div className="tiny muted">{t("Max financing","حد التمويل")}</div>
            </div>
          </div>
        </div>
      </div>
    </OnbStep>
  );
}

function OnbHousing({ data, setData, onNext, onPrev, t }) {
  const Q = ({ id, label, hint, value, onChange }) => (
    <div className="onb-question">
      <div>
        <div className="text-14" style={{fontWeight:600}}>{label}</div>
        {hint && <div className="tiny muted" style={{marginTop:2}}>{hint}</div>}
      </div>
      <div className="onb-yn">
        <button className={`yn ${value === true ? "active yes" : ""}`} onClick={() => onChange(true)}>{t("Yes","نعم")}</button>
        <button className={`yn ${value === false ? "active no" : ""}`} onClick={() => onChange(false)}>{t("No","لا")}</button>
      </div>
    </div>
  );
  return (
    <OnbStep
      eyebrow={t("Housing history","تاريخ السكن")}
      title={t("Tell us about your housing.","أخبرنا عن سكنك.")}
      sub={t("We cross-check these against the Land Registry and Ministry of Housing. Be honest — we'll catch discrepancies.","سنتحقق منها مع السجل العقاري ووزارة الإسكان.")}
      secondary={t("Back","رجوع")}
      primary={t("Continue","متابعة")}
      onSecondary={onPrev}
      onPrimary={onNext}
    >
      <div className="onb-questions">
        <Q label={t("Do you own a residential property in Oman?","هل تملك عقاراً سكنياً في عُمان؟")}
          hint={t("Includes ownership shared with your spouse.","يشمل الملكية المشتركة.")}
          value={data.existingProperty}
          onChange={(v) => setData({...data, existingProperty: v})}/>
        <Q label={t("Do you currently receive a housing benefit?","هل تتلقى حالياً دعماً سكنياً؟")}
          hint={t("From Ministry of Housing or a previous program.","من وزارة الإسكان.")}
          value={data.activeBenefit}
          onChange={(v) => setData({...data, activeBenefit: v})}/>
        <Q label={t("Has your spouse received government housing support before?","هل تلقى زوجك دعماً سكنياً سابقاً؟")}
          hint={t("Includes prior ISKAN, Sanad, or social housing.","يشمل الدعم السابق.")}
          value={data.spousePriorSupport}
          onChange={(v) => setData({...data, spousePriorSupport: v})}/>
      </div>
      <div className="onb-helper warn">
        <Icon name="alert" size={13}/>
        <span className="text-13">{t("All answers are verified against official records. Misrepresentation is a criminal offence under Omani Banking Law.","تتم مطابقة جميع الإجابات.")}</span>
      </div>
    </OnbStep>
  );
}

window.OnbIdentity = OnbIdentity;
window.OnbPersonal = OnbPersonal;
window.OnbIncome = OnbIncome;
window.OnbHousing = OnbHousing;
