// Onboarding part 3 — Documents, eligibility scan animation, program matches.

function OnbDocuments({ data, setData, onNext, onPrev, t }) {
  const docs = [
    { id: "id", name: t("National ID","البطاقة المدنية"), auto: true, source: "Civil Registry", req: true },
    { id: "salary", name: t("Recent salary certificate","شهادة راتب حديثة"), source: "Citizen upload", req: true },
    { id: "marriage", name: t("Marriage certificate","عقد زواج"), auto: true, source: "Civil Registry", req: true },
    { id: "statement", name: t("6-month bank statement","كشف حساب 6 أشهر"), source: "Bank API · 1 click consent", req: true },
    { id: "liability", name: t("Existing loan liability statement","كشف الالتزامات"), auto: true, source: "Credit Bureau", req: false },
  ];

  function toggle(id) {
    setData({ ...data, docs: { ...data.docs, [id]: !data.docs[id] } });
  }

  const fulfilled = docs.filter(d => data.docs[d.id]).length;
  const required = docs.filter(d => d.req).length;
  const reqFulfilled = docs.filter(d => d.req && data.docs[d.id]).length;
  const canContinue = reqFulfilled === required;

  return (
    <OnbStep
      eyebrow={t("Required documents","المستندات المطلوبة")}
      title={t("We've grabbed what we can.","استرجعنا ما أمكن.")}
      sub={t("3 documents auto-fetched from government records. You only need to provide 2.","تم استرجاع 3 مستندات تلقائياً.")}
      secondary={t("Back","رجوع")}
      primary={t("Run eligibility check","تشغيل فحص الأهلية")}
      primaryDisabled={!canContinue}
      onSecondary={onPrev}
      onPrimary={onNext}
    >
      <div className="onb-docs">
        <div className="onb-doc-progress">
          <div className="onb-doc-progress-text">
            <span className="serif-big">{fulfilled}<span className="muted">/{docs.length}</span></span>
            <span className="tiny muted">{t("documents on file","مستندات في الملف")}</span>
          </div>
          <div className="onb-doc-progress-bar">
            <div className="onb-doc-progress-fill" style={{width: `${(fulfilled / docs.length) * 100}%`}}/>
          </div>
        </div>

        <div className="onb-doc-list">
          {docs.map((d) => (
            <div key={d.id} className={`onb-doc-row ${data.docs[d.id] ? "done" : ""}`}>
              <div className="onb-doc-icon">
                {data.docs[d.id] ? <Icon name="doc_check" size={18}/> : <Icon name="doc" size={18}/>}
              </div>
              <div style={{flex:1, minWidth:0}}>
                <div className="row" style={{gap:8, flexWrap:"wrap"}}>
                  <span className="text-14" style={{fontWeight:600}}>{d.name}</span>
                  {d.auto && <span className="pill ghost tiny">{t("Auto-fetched","تلقائي")}</span>}
                  {!d.req && <span className="pill ghost tiny">{t("Optional","اختياري")}</span>}
                </div>
                <div className="tiny muted">{d.source}</div>
              </div>
              {data.docs[d.id] ? (
                <span className="pill ok"><Icon name="check" size={11}/> {t("Verified","موثق")}</span>
              ) : (
                <button className="btn copper sm" onClick={() => toggle(d.id)}>
                  <Icon name="upload" size={13}/> {t("Upload","رفع")}
                </button>
              )}
            </div>
          ))}
        </div>

        <div className="onb-helper">
          <Icon name="shield" size={13} style={{color:"var(--brand-teal)"}}/>
          <span className="text-13">
            {t("Documents are encrypted in transit and at rest. Shared only with your chosen partner bank, with your explicit consent.",
              "المستندات مشفرة. يتم مشاركتها فقط مع البنك المختار.")}
          </span>
        </div>
      </div>
    </OnbStep>
  );
}

/* ─── 6. Eligibility scanning animation ───── */

function OnbScanning({ data, onNext, t, citizen }) {
  const sources = [
    { id: "civil", name: t("Civil Registry","السجل المدني"), icon: "id", duration: 600 },
    { id: "income", name: t("Income & Employment","الدخل والعمل"), icon: "wallet", duration: 900 },
    { id: "land", name: t("Land / Plot Registry","السجل العقاري"), icon: "home", duration: 700 },
    { id: "moh", name: t("Ministry of Housing","وزارة الإسكان"), icon: "shield", duration: 500 },
    { id: "credit", name: t("Credit Bureau","المكتب الائتماني"), icon: "scale", duration: 800 },
    { id: "ohb", name: t("OHB Waiting List","قائمة انتظار البنك"), icon: "clock", duration: 400 },
    { id: "employer", name: t("Employer Check","فحص جهة العمل"), icon: "briefcase", duration: 600 },
    { id: "rules", name: t("Run 11 eligibility rules","تشغيل 11 قاعدة"), icon: "shield", duration: 700 },
  ];

  const [completed, setCompleted] = React.useState([]);
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    let acc = 0;
    sources.forEach((s, i) => {
      acc += s.duration;
      setTimeout(() => setCompleted((c) => [...c, s.id]), acc);
    });
    setTimeout(() => setDone(true), acc + 800);
    setTimeout(() => onNext(), acc + 1800);
  }, []);

  const decision = window.evaluateProgram(citizen, window.OHB_DATA.iskanProgram, window.OHB_DATA.ruleLibrary);

  return (
    <div className="onb-scanning">
      <div className="onb-scan-art">
        <div className="scan-orbit">
          <div className="scan-orbit-ring r1"/>
          <div className="scan-orbit-ring r2"/>
          <div className="scan-orbit-ring r3"/>
          <div className="scan-center">
            <Icon name="shield" size={32}/>
          </div>
        </div>
      </div>
      <div className="label-eyebrow">{t("Eligibility check in progress","جاري فحص الأهلية")}</div>
      <h1 className="h2 onb-title" style={{marginTop:8}}>
        {!done ? t("We're checking everything…","نحن نفحص كل شيء…") : t("Done.","تم.")}
      </h1>
      <p className="onb-sub">
        {!done
          ? t("Querying 8 government systems and 1 credit bureau in parallel. This usually takes ~1.4 seconds — we'll wait for you to catch up.","نستعلم من 8 أنظمة حكومية بالتوازي.")
          : t("All systems responded. Computing your matches now.","تم الرد. نحسب نتائجك الآن.")}
      </p>

      <div className="onb-scan-list">
        {sources.map((s) => (
          <div key={s.id} className={`scan-row ${completed.includes(s.id) ? "done" : "pending"}`}>
            <div className="scan-row-icon"><Icon name={s.icon} size={14}/></div>
            <div style={{flex:1, minWidth:0}}>
              <div className="text-13" style={{fontWeight:600}}>{s.name}</div>
              <div className="tiny muted">{completed.includes(s.id) ? t("200 OK","تم") : t("Querying…","استعلام…")}</div>
            </div>
            {completed.includes(s.id) ? <Icon name="check" size={14} style={{color:"var(--ok)"}}/>
              : <span className="scan-spinner"/>}
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── 7. Program matches ─────────────────── */

function OnbMatches({ data, citizen, onComplete, t }) {
  const programs = window.OHB_DATA.programs.filter(p => p.status === "Active");

  // Compute fitness for each program based on citizen profile
  const matches = programs.map((p) => {
    const d = window.evaluateProgram(citizen, window.OHB_DATA.iskanProgram, window.OHB_DATA.ruleLibrary);
    return {
      program: p,
      outcome: d.outcome,
      routing: d.routing,
      score: d.outcome === "eligible" ? 100 : d.outcome === "manual_review" ? 78 : 22,
      passed: d.trace.filter(r => r.status === "passed").length,
      total: d.trace.length,
      blockers: d.trace.filter(r => r.status === "failed"),
    };
  });

  matches.sort((a, b) => b.score - a.score);
  const eligibleCount = matches.filter(m => m.outcome === "eligible").length;
  const reviewCount = matches.filter(m => m.outcome === "manual_review").length;

  return (
    <div className="onb-matches">
      <div className="onb-matches-head">
        <div className="onb-result-art">
          <div className="result-ring">
            <svg viewBox="0 0 100 100" width="100" height="100">
              <circle cx="50" cy="50" r="45" stroke="rgba(27,65,73,0.1)" strokeWidth="6" fill="none"/>
              <circle cx="50" cy="50" r="45" stroke="var(--brand-teal)" strokeWidth="6" fill="none"
                strokeDasharray={`${(eligibleCount + reviewCount * 0.5) / matches.length * 283} 283`}
                strokeLinecap="round" transform="rotate(-90 50 50)"/>
            </svg>
            <div className="result-ring-inner">
              <div className="serif-big">{eligibleCount}</div>
              <div className="tiny muted">{t("of","من")} {matches.length}</div>
            </div>
          </div>
        </div>
        <div>
          <div className="label-eyebrow">{t("Eligibility complete","اكتمل الفحص")}</div>
          <h1 className="h1 onb-h1">
            {eligibleCount > 0
              ? <>{citizen.name.split(" ")[0]}, <em className="onb-italic">{t("you qualify.","أنت مؤهل.")}</em></>
              : <>{t("Some paths exist.","توجد مسارات أخرى.")}</>
            }
          </h1>
          <p className="onb-sub" style={{maxWidth:480}}>
            {eligibleCount > 0
              ? t(`You're fully eligible for ${eligibleCount} program${eligibleCount > 1 ? "s" : ""} and need review for ${reviewCount}. Pick one to move forward — you can always come back and switch.`,
                  `أنت مؤهل تماماً لـ ${eligibleCount} برامج وتحتاج مراجعة لـ ${reviewCount}.`)
              : t("ISKAN isn't an exact fit, but two adjacent programs could work. We've sorted them by best match.","إسكان ليس مناسباً تماماً، لكن لدينا برامج بديلة.")}
          </p>
        </div>
      </div>

      <div className="onb-program-grid">
        {matches.map((m, i) => <ProgramMatchCard key={m.program.id} match={m} t={t} featured={i === 0} onSelect={onComplete}/>)}
      </div>

      <div className="onb-matches-foot">
        <button className="btn ghost"><Icon name="download" size={14}/> {t("Download eligibility report (PDF)","تنزيل التقرير")}</button>
        <button className="btn ghost"><Icon name="message" size={14}/> {t("Talk to an advisor","تحدث مع مستشار")}</button>
      </div>
    </div>
  );
}

function ProgramMatchCard({ match, t, featured, onSelect }) {
  const p = match.program;
  const status = match.outcome === "eligible" ? "ok" : match.outcome === "manual_review" ? "warn" : "bad";
  return (
    <div className={`program-match ${featured ? "featured" : ""} status-${status}`}>
      {featured && <div className="match-best">{t("Best match for you","الأفضل لك")}</div>}
      <div className="match-head">
        <div>
          <div className="label-eyebrow">{p.type}</div>
          <div className="h3 match-name">{p.name}</div>
          <div className="tiny muted">{p.nameAr}</div>
        </div>
        <div className="match-score">
          <div className="serif-big">{match.score}</div>
          <div className="tiny muted">match</div>
        </div>
      </div>

      <div className="match-status">
        {match.outcome === "eligible" && (
          <><Icon name="check_circle" size={16}/> <strong>{t("You qualify.","أنت مؤهل.")}</strong> {match.passed}/{match.total} {t("rules pass","قواعد")} · {match.routing}</>
        )}
        {match.outcome === "manual_review" && (
          <><Icon name="alert" size={16}/> <strong>{t("Almost — review needed.","تقريباً — يلزم مراجعة.")}</strong> {match.passed}/{match.total} {t("rules pass","قواعد")}</>
        )}
        {match.outcome === "rejected" && (
          <><Icon name="x_circle" size={16}/> <strong>{t("Not eligible today.","غير مؤهل اليوم.")}</strong> {match.blockers.length} {t("blockers","حواجز")}</>
        )}
      </div>

      <div className="match-perks">
        <Perk icon="cash" label={t("Max financing","حد التمويل")} value={`OMR ${p.maxFinancingNormal.toLocaleString()}`}/>
        <Perk icon="clock" label={t("Repayment","السداد")} value={`${p.maxTermMonths/12} ${t("years","سنة")}`}/>
        <Perk icon="building" label={t("Available in","متاح في")} value={`${p.governorates.length} ${t("governorates","محافظات")}`}/>
        <Perk icon="users" label={t("Partner banks","البنوك الشريكة")} value={`${p.partnerBanks.length}`}/>
      </div>

      {match.outcome === "rejected" && match.blockers.length > 0 && (
        <div className="match-blockers">
          <div className="tiny muted" style={{marginBottom:6}}>{t("Blocked because:","محجوب بسبب:")}</div>
          {match.blockers.slice(0,2).map((b) => (
            <div key={b.ruleId} className="match-blocker">
              <Icon name="x" size={11}/> {b.name}
            </div>
          ))}
        </div>
      )}

      <div className="match-foot">
        <button className="btn ghost" onClick={onSelect}>{t("View details","التفاصيل")}</button>
        {match.outcome !== "rejected" && (
          <button className={`btn ${match.outcome === "eligible" ? "copper" : "teal"}`} onClick={onSelect}>
            {match.outcome === "eligible" ? t("Apply now","قدم الآن") : t("Submit for review","تقديم للمراجعة")}
            <Icon name="arrow_right" size={13} className="arrow-flip"/>
          </button>
        )}
      </div>
    </div>
  );
}

function Perk({ icon, label, value }) {
  return (
    <div className="perk">
      <Icon name={icon} size={12} style={{color:"var(--muted)"}}/>
      <div>
        <div className="tiny muted">{label}</div>
        <div className="text-13" style={{fontWeight:600}}>{value}</div>
      </div>
    </div>
  );
}

window.OnbDocuments = OnbDocuments;
window.OnbScanning = OnbScanning;
window.OnbMatches = OnbMatches;
