// Mobile onboarding — compact, native-feeling slide-style flow.
// Renders inside the iOS device frame.

function MobileOnboardingScreen({ citizen, t, rtl, onComplete }) {
  const [stepIdx, setStepIdx] = React.useState(0);
  const steps = ["welcome", "id", "otp", "income", "housing", "scan", "matches"];
  const step = steps[stepIdx];
  const next = () => stepIdx === steps.length - 1 ? onComplete() : setStepIdx(stepIdx + 1);
  const prev = () => setStepIdx(Math.max(0, stepIdx - 1));

  return (
    <div className="m-onb" dir={rtl ? "rtl" : "ltr"}>
      {/* Spacer for iOS status bar */}
      <div style={{height: 56}}/>

      <div className="m-onb-top">
        <button className="m-onb-back" onClick={prev} style={{opacity: stepIdx === 0 ? 0.3 : 1}}>
          <Icon name="arrow_left" size={18} className="arrow-flip"/>
        </button>
        <div className="m-onb-progress">
          <div className="m-onb-progress-fill" style={{width: `${((stepIdx + 1) / steps.length) * 100}%`}}/>
        </div>
        <span className="tiny muted" style={{minWidth: 28}}>{stepIdx + 1}/{steps.length}</span>
      </div>

      <div className="m-onb-content">
        {step === "welcome" && <MOWelcome onNext={next} t={t}/>}
        {step === "id" && <MOIdentity onNext={next} t={t}/>}
        {step === "otp" && <MOOtp onNext={next} t={t}/>}
        {step === "income" && <MOIncome onNext={next} t={t} citizen={citizen}/>}
        {step === "housing" && <MOHousing onNext={next} t={t}/>}
        {step === "scan" && <MOScan onNext={next} t={t}/>}
        {step === "matches" && <MOMatches onNext={onComplete} t={t} citizen={citizen}/>}
      </div>
    </div>
  );
}

function MOWelcome({ onNext, t }) {
  return (
    <div className="mo-screen welcome">
      <div className="mo-welcome-art">
        <svg viewBox="0 0 200 200">
          <defs>
            <radialGradient id="mow" cx="0.5" cy="0.4" r="0.7">
              <stop offset="0%" stopColor="#eaa07a" stopOpacity="0.4"/>
              <stop offset="100%" stopColor="#1b4149" stopOpacity="0"/>
            </radialGradient>
          </defs>
          <circle cx="100" cy="80" r="80" fill="url(#mow)"/>
          <g transform="translate(60, 60)" stroke="#1b4149" strokeWidth="1.5" fill="none" opacity="0.7">
            <path d="M 0 60 L 40 20 L 80 60 L 80 110 L 0 110 Z"/>
            <path d="M 14 110 L 14 75 L 32 75 L 32 110"/>
            <path d="M 50 75 L 65 75 L 65 92 L 50 92 Z"/>
          </g>
        </svg>
      </div>
      <div className="mo-greeting-eyebrow">{t("ISKAN · OHB","إسكان")}</div>
      <h1 className="mo-h1">
        {t("Your home,","منزلك،")}
        <br/><em>{t("7 steps away.","7 خطوات.")}</em>
      </h1>
      <p className="mo-sub">
        {t("We check your eligibility and show you exactly what you can finance. Takes about 8 minutes.",
          "نفحص أهليتك ونعرض لك ما يمكنك تمويله. يستغرق حوالي 8 دقائق.")}
      </p>
      <div className="mo-foot">
        <button className="btn copper lg" style={{width:"100%"}} onClick={onNext}>
          {t("Create account","إنشاء حساب")} <Icon name="arrow_right" size={14} className="arrow-flip"/>
        </button>
        <button className="btn ghost" style={{width:"100%", marginTop:8}}>{t("I have an account","لدي حساب")}</button>
      </div>
    </div>
  );
}

function MOIdentity({ onNext, t }) {
  return (
    <div className="mo-screen">
      <div className="mo-eyebrow">{t("Step 1 · Identity","الخطوة 1")}</div>
      <h2 className="mo-h2">{t("National ID, please.","البطاقة المدنية.")}</h2>
      <p className="mo-sub">{t("We'll pull your profile from the Civil Registry.","سنسحب ملفك.")}</p>
      <div className="mo-field" style={{marginTop:24}}>
        <div className="field-label">{t("National ID","الرقم الوطني")}</div>
        <input className="input lg" defaultValue="OM-1989-100245"/>
      </div>
      <div className="mo-sources" style={{marginTop:20}}>
        <div className="mo-source"><Icon name="id" size={13}/> {t("Civil Registry · auto-fetch","السجل المدني")}</div>
        <div className="mo-source"><Icon name="phone_icon" size={13}/> {t("SMS verification","تحقق SMS")}</div>
      </div>
      <div className="mo-foot">
        <button className="btn copper lg" style={{width:"100%"}} onClick={onNext}>
          {t("Send code","إرسال الرمز")}
        </button>
      </div>
    </div>
  );
}

function MOOtp({ onNext, t }) {
  const [digits, setDigits] = React.useState(["","","",""]);
  const refs = [React.useRef(), React.useRef(), React.useRef(), React.useRef()];

  React.useEffect(() => {
    refs[0].current?.focus();
  }, []);

  function setDigit(i, v) {
    if (v && !/^\d$/.test(v)) return;
    const next = [...digits];
    next[i] = v;
    setDigits(next);
    if (v && i < 3) refs[i+1].current?.focus();
    if (next.every(d => d)) setTimeout(onNext, 600);
  }
  return (
    <div className="mo-screen">
      <div className="mo-eyebrow">{t("Step 2 · OTP","الخطوة 2")}</div>
      <h2 className="mo-h2">{t("Check your phone.","تحقق من هاتفك.")}</h2>
      <p className="mo-sub">{t("Code sent to •••• 4467","تم الإرسال")}</p>
      <div className="mo-otp">
        {digits.map((d, i) => (
          <input key={i} ref={refs[i]} className="mo-otp-input" value={d}
            onChange={(e) => setDigit(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", marginTop:18}}>
        {t("Resend in","إعادة")} <strong>4:48</strong>
      </div>
    </div>
  );
}

function MOIncome({ onNext, t, citizen }) {
  const [income, setIncome] = React.useState(citizen.monthlyIncomeOmr);
  return (
    <div className="mo-screen">
      <div className="mo-eyebrow">{t("Step 3 · Income","الخطوة 3")}</div>
      <h2 className="mo-h2">{t("Monthly income?","الدخل الشهري؟")}</h2>
      <p className="mo-sub">{t("Sets your financing band.","يحدد شريحة التمويل.")}</p>
      <div className="mo-income-input">
        <span className="omr-prefix">OMR</span>
        <input className="omr-num" type="number" value={income} onChange={(e) => setIncome(+e.target.value)}/>
      </div>
      <div className="mo-band" style={{marginTop:16}}>
        <div className="mo-band-track">
          <div className="mo-band-fill" style={{left: `${Math.min(100, (income / 3000) * 100)}%`}}/>
        </div>
        <div className="row" style={{justifyContent:"space-between", marginTop:8}}>
          <span className="tiny muted">{t("Profit rate","معدل الربح")}</span>
          <span className="text-13" style={{fontWeight:700}}>{income <= 400 ? 1 : income <= 1000 ? 3 : 4}%</span>
        </div>
      </div>
      <div className="mo-preview">
        <div>
          <div className="tiny muted">{t("Max financing","حد التمويل")}</div>
          <div className="text-14" style={{fontWeight:700}}>OMR {income > 1000 ? "80,000" : "60,000"}</div>
        </div>
        <div>
          <div className="tiny muted">{t("Monthly","شهرياً")}</div>
          <div className="text-14" style={{fontWeight:700}}>OMR {Math.round(window.calculateLoan({monthlyIncomeOmr: income}, 60000, "normal").emi)}</div>
        </div>
      </div>
      <div className="mo-foot">
        <button className="btn copper lg" style={{width:"100%"}} onClick={onNext}>{t("Continue","متابعة")}</button>
      </div>
    </div>
  );
}

function MOHousing({ onNext, t }) {
  const [a, setA] = React.useState({});
  const Q = ({ k, label }) => (
    <div className="mo-q">
      <div className="text-13" style={{fontWeight:600}}>{label}</div>
      <div className="row" style={{gap:6, marginTop:8}}>
        <button className={`yn ${a[k] === true ? "active yes" : ""}`} style={{flex:1}} onClick={() => setA({...a, [k]: true})}>{t("Yes","نعم")}</button>
        <button className={`yn ${a[k] === false ? "active no" : ""}`} style={{flex:1}} onClick={() => setA({...a, [k]: false})}>{t("No","لا")}</button>
      </div>
    </div>
  );
  return (
    <div className="mo-screen">
      <div className="mo-eyebrow">{t("Step 4 · Housing","الخطوة 4")}</div>
      <h2 className="mo-h2">{t("Quick housing check.","فحص الإسكان.")}</h2>
      <p className="mo-sub">{t("Verified against Land Registry & MoH.","يتم التحقق رسمياً.")}</p>
      <div style={{display:"flex", flexDirection:"column", gap:10, marginTop:14}}>
        <Q k="prop" label={t("Own a property in Oman?","تملك عقار؟")}/>
        <Q k="bene" label={t("Receive housing benefit?","تتلقى دعم سكني؟")}/>
        <Q k="spouse" label={t("Spouse prior support?","دعم سابق للزوج؟")}/>
      </div>
      <div className="mo-foot">
        <button className="btn copper lg" style={{width:"100%"}} onClick={onNext}>{t("Continue","متابعة")}</button>
      </div>
    </div>
  );
}

function MOScan({ onNext, t }) {
  const sources = [
    { name: t("Civil Registry","السجل المدني"), icon: "id" },
    { name: t("Income & Employment","الدخل"), icon: "wallet" },
    { name: t("Land Registry","السجل العقاري"), icon: "home" },
    { name: t("Ministry of Housing","وزارة الإسكان"), icon: "shield" },
    { name: t("Credit Bureau","الائتمان"), icon: "scale" },
    { name: t("Waiting List","قائمة الانتظار"), icon: "clock" },
  ];
  const [done, setDone] = React.useState(0);
  React.useEffect(() => {
    if (done < sources.length) {
      const t1 = setTimeout(() => setDone(done + 1), 350);
      return () => clearTimeout(t1);
    } else {
      const t2 = setTimeout(onNext, 700);
      return () => clearTimeout(t2);
    }
  }, [done]);
  return (
    <div className="mo-screen scan">
      <div className="mo-scan-art">
        <div className="mo-orbit r1"/>
        <div className="mo-orbit r2"/>
        <div className="mo-orbit r3"/>
        <div className="mo-orbit-center"><Icon name="shield" size={24}/></div>
      </div>
      <div className="mo-eyebrow" style={{textAlign:"center", marginTop:8}}>{t("Checking eligibility","فحص الأهلية")}</div>
      <h2 className="mo-h2" style={{textAlign:"center"}}>{done < sources.length ? t("Querying…","استعلام…") : t("Done.","تم.")}</h2>
      <div className="mo-scan-list">
        {sources.map((s, i) => (
          <div key={i} className={`mo-scan-row ${i < done ? "done" : "pending"}`}>
            <Icon name={s.icon} size={13}/>
            <span className="text-13" style={{flex:1}}>{s.name}</span>
            {i < done ? <Icon name="check" size={12} style={{color:"var(--ok)"}}/> : <span className="scan-spinner"/>}
          </div>
        ))}
      </div>
    </div>
  );
}

function MOMatches({ onNext, t, citizen }) {
  const programs = window.OHB_DATA.programs.filter(p => p.status === "Active");
  return (
    <div className="mo-screen matches">
      <div className="mo-result-ring">
        <svg viewBox="0 0 80 80" width="80" height="80">
          <circle cx="40" cy="40" r="36" stroke="rgba(27,65,73,0.1)" strokeWidth="6" fill="none"/>
          <circle cx="40" cy="40" r="36" stroke="var(--brand-teal)" strokeWidth="6" fill="none"
            strokeDasharray={`${(2/3)*226} 226`} strokeLinecap="round" transform="rotate(-90 40 40)"/>
        </svg>
        <div className="mo-ring-inner">
          <span className="serif-big" style={{fontSize:24}}>2</span>
          <span className="tiny muted">of 3</span>
        </div>
      </div>
      <h2 className="mo-h2 mo-h2-result">
        <em>{t("You qualify.","أنت مؤهل.")}</em>
      </h2>
      <p className="mo-sub" style={{textAlign:"center"}}>
        {t("2 programs ready for you.","برنامجان جاهزان لك.")}
      </p>
      <div className="mo-matches">
        {programs.slice(0,3).map((p, i) => (
          <div key={p.id} className={`mo-match ${i === 0 ? "featured" : ""}`}>
            <div className="row" style={{justifyContent:"space-between", gap:8}}>
              <div style={{flex:1, minWidth:0}}>
                <div className="tiny muted">{p.type}</div>
                <div className="text-14" style={{fontWeight:700, marginTop:2}}>{p.name}</div>
              </div>
              <span className={`pill ${i < 2 ? "ok" : "warn"}`}>{i < 2 ? t("Eligible","مؤهل") : t("Review","مراجعة")}</span>
            </div>
            <div className="row" style={{gap:12, marginTop:8}}>
              <span className="tiny muted"><Icon name="cash" size={11}/> OMR {(p.maxFinancingNormal/1000).toFixed(0)}k</span>
              <span className="tiny muted"><Icon name="clock" size={11}/> 25y</span>
            </div>
          </div>
        ))}
      </div>
      <div className="mo-foot">
        <button className="btn copper lg" style={{width:"100%"}} onClick={onNext}>
          {t("Continue to ISKAN","متابعة")} <Icon name="arrow_right" size={14} className="arrow-flip"/>
        </button>
      </div>
    </div>
  );
}

window.MobileOnboardingScreen = MobileOnboardingScreen;
