// screens-status.jsx — SYSTEM STATUS (حالة النظام): the one screen a non-technical owner opens to see
// WHAT IS CONNECTED, WHAT IS BROKEN, and HOW TO FIX IT. Renders the real engines: /integrations/truth
// (5-state, no fake connected), /assem/org-hierarchy (the one company + brain status), and the WhatsApp
// line/diagnostic status. Every status is server-truth; the "Open AI Settings" button navigates the owner
// straight to where they fix the brain — no redeploy, no technical knowledge.
const { useState: useStatusState, useEffect: useStatusEffect } = React;

// the 5 honest states → {tone, ar, en, icon}. Never a fake green.
const TRUTH_META = {
  REAL_CONNECTED: { tone: "green", ar: "متصل", en: "Connected", icon: "checkcircle" },
  NOT_CONNECTED: { tone: "neutral", ar: "غير متصل", en: "Not connected", icon: "circle" },
  CONFIGURED_BUT_FAILED: { tone: "red", ar: "مُعدّ لكنه يفشل", en: "Configured but failing", icon: "alert" },
  NOT_IMPLEMENTED: { tone: "dark", ar: "غير متاح حاليًا", en: "Not available yet", icon: "minus" },
  NO_DATA: { tone: "neutral", ar: "لا توجد بيانات", en: "No data", icon: "circle" },
};
const BRAIN_META = {
  LIVE_LLM: { tone: "green", ar: "العقل يعمل مباشرة", en: "Brain live" },
  INVALID_KEY: { tone: "red", ar: "مفتاح الذكاء غير صالح", en: "Invalid AI key" },
  MISSING_KEY: { tone: "orange", ar: "لا يوجد مفتاح ذكاء", en: "No AI key" },
  PROVIDER_ERROR: { tone: "red", ar: "خطأ في مزوّد الذكاء", en: "Provider error" },
  FALLBACK_DETERMINISTIC: { tone: "neutral", ar: "وضع احتياطي حتمي", en: "Deterministic fallback" },
  CONFIGURED_BUT_FAILED: { tone: "red", ar: "مفتاح الذكاء غير صالح", en: "AI key failing" },
  NOT_CONNECTED: { tone: "orange", ar: "لا يوجد مفتاح ذكاء", en: "No AI key" },
  REAL_CONNECTED: { tone: "green", ar: "العقل يعمل مباشرة", en: "Brain live" },
};
const INTEG_AR = { stripe: "سترايب (المدفوعات)", google: "جوجل (البريد + التقويم)", meta: "إنستغرام / فيسبوك", tiktok: "تيك توك", whatsapp: "واتساب", ai_providers: "مزوّدو الذكاء", voice: "الصوت" };

function openAiSettings() { try { window.dispatchEvent(new CustomEvent("maxab:goto", { detail: { screen: "settings", tab: "ai" } })); } catch (e) {} }

function TruthChip({ truth, lang }) {
  const m = TRUTH_META[truth] || TRUTH_META.NO_DATA;
  return <Badge tone={m.tone}>{lang === "ar" ? m.ar : m.en}</Badge>;
}

function SystemStatusScreen() {
  const { lang } = useLang();
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [truth, setTruth] = useStatusState(null);
  const [org, setOrg] = useStatusState(null);
  const [wa, setWa] = useStatusState(null);
  const [loading, setLoading] = useStatusState(true);
  const [err, setErr] = useStatusState(null);

  const load = () => {
    setLoading(true); setErr(null);
    Promise.allSettled([API.integrations.truth(), API.assem.orgHierarchy(lang), API.whatsapp.status()])
      .then(([t, o, w]) => {
        if (t.status === "fulfilled") setTruth(t.value); else setErr(T("تعذّر تحميل حالة التكاملات.", "Could not load integration status."));
        if (o.status === "fulfilled") setOrg(o.value);
        if (w.status === "fulfilled") setWa(w.value);
      })
      .finally(() => setLoading(false));
  };
  useStatusEffect(() => { load(); /* eslint-disable-next-line */ }, [lang]);

  const brain = (truth && truth.roles && truth.roles.brain) || null;
  const bm = brain ? (BRAIN_META[brain.truth] || BRAIN_META.FALLBACK_DETERMINISTIC) : null;

  return (
    <div className="col" style={{ gap: 16, maxWidth: 920, margin: "0 auto", padding: "4px 2px 40px" }}>
      <div className="row between" style={{ alignItems: "center", flexWrap: "wrap", gap: 8 }}>
        <div className="col" style={{ gap: 2 }}>
          <h2 style={{ margin: 0, fontSize: 20 }}>{T("حالة النظام", "System Status")}</h2>
          <div className="subtle" style={{ fontSize: 13 }}>{T("ما المتصل، ما المعطّل، وكيف تُصلحه — كل شيء حقيقي، لا حالات وهمية.", "What's connected, what's broken, how to fix it — all real, no fake states.")}</div>
        </div>
        <Button variant="ghost" size="sm" icon="refresh" onClick={load} disabled={loading}>{T("تحديث", "Refresh")}</Button>
      </div>

      {loading ? <Card><div className="subtle" style={{ padding: 18, fontSize: 13 }}>{T("جارٍ التحميل…", "Loading…")}</div></Card> : null}
      {err ? <Card><div style={{ padding: 16, color: "var(--color-red, #DC2626)", fontSize: 13 }}>{err} <Button variant="ghost" size="sm" onClick={load}>{T("إعادة المحاولة", "Retry")}</Button></div></Card> : null}

      {/* THE BRAIN — the most important status: can Assem think? + the one-click fix. */}
      {brain ? (
        <Card>
          <div className="row between" style={{ alignItems: "center", flexWrap: "wrap", gap: 10, padding: 4 }}>
            <div className="row" style={{ gap: 12, alignItems: "center", minWidth: 0 }}>
              <div style={{ width: 40, height: 40, borderRadius: 12, background: "var(--color-primary)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}><Icon name="sparkles" size={20} style={{ color: "#fff" }} /></div>
              <div className="col" style={{ gap: 3, minWidth: 0 }}>
                <div className="row" style={{ gap: 8, alignItems: "center" }}><b style={{ fontSize: 15 }}>{T("عقل الشركة (عاصم)", "Company brain (Assem)")}</b><Badge tone={bm.tone}>{lang === "ar" ? bm.ar : bm.en}</Badge></div>
                <div className="subtle" style={{ fontSize: 12.5, maxWidth: 560 }}>{brain.truth === "REAL_CONNECTED" ? T("كل الأدوار تفكّر مباشرة عبر العقل الواحد.", "Every role reasons live through the one brain.") : T("الأدوار موصولة بالعقل لكنها لا تفكّر مباشرة بعد. أصلِح مفتاح الذكاء لتفعيلها.", "Roles are wired to the brain but not thinking live yet. Fix the AI key to enable them.")}{brain.reason ? " — " + brain.reason : ""}</div>
              </div>
            </div>
            {brain.truth !== "REAL_CONNECTED" ? <Button variant="primary" size="sm" icon="settings" onClick={openAiSettings}>{T("فتح إعدادات الذكاء", "Open AI Settings")}</Button> : null}
          </div>
        </Card>
      ) : null}

      {/* INTEGRATIONS — the 5-state truth, each with the exact next step. */}
      {truth ? (
        <Card title={T("التكاملات", "Integrations")}>
          <div className="col" style={{ gap: 0 }}>
            {truth.integrations.map((i, idx) => {
              const meta = TRUTH_META[i.truth] || TRUTH_META.NO_DATA;
              const need = (i.missingRequirements || [])[0] || i.detail || null;
              return (
                <div key={i.id} className="row between" style={{ alignItems: "flex-start", gap: 10, padding: "11px 4px", borderTop: idx ? "1px solid var(--border-1)" : "none", flexWrap: "wrap" }}>
                  <div className="row" style={{ gap: 10, alignItems: "center", minWidth: 0 }}>
                    <Icon name={meta.icon} size={16} style={{ color: i.truth === "REAL_CONNECTED" ? "var(--color-green, #16A34A)" : i.truth === "CONFIGURED_BUT_FAILED" ? "var(--color-red, #DC2626)" : "var(--fg-4)", flexShrink: 0 }} />
                    <div className="col" style={{ gap: 2, minWidth: 0 }}>
                      <b style={{ fontSize: 13.5 }}>{lang === "ar" ? (INTEG_AR[i.id] || i.label) : i.label}</b>
                      {need ? <div className="subtle" style={{ fontSize: 11.5, maxWidth: 520 }}>{i.truth === "REAL_CONNECTED" ? "" : (T("المطلوب: ", "Needs: ") + need)}</div> : null}
                    </div>
                  </div>
                  <div className="row" style={{ gap: 8, alignItems: "center" }}>
                    <TruthChip truth={i.truth} lang={lang} />
                    {i.id === "ai_providers" && i.truth !== "REAL_CONNECTED" ? <Button variant="ghost" size="sm" icon="settings" onClick={openAiSettings}>{T("إصلاح", "Fix")}</Button> : null}
                    {i.id === "whatsapp" ? <Button variant="ghost" size="sm" onClick={() => { try { window.dispatchEvent(new CustomEvent("maxab:goto", { detail: { screen: "settings", tab: "integrations" } })); } catch (e) {} }}>{T("إعداد", "Setup")}</Button> : null}
                  </div>
                </div>
              );
            })}
          </div>
          <div className="subtle" style={{ fontSize: 11, marginTop: 10, paddingTop: 8, borderTop: "1px solid var(--border-1)" }}>{(truth.note && (lang === "ar" ? truth.note.ar : truth.note.en)) || ""}</div>
        </Card>
      ) : null}

      {/* WHATSAPP DIAGNOSTICS — line count + last events (real, never faked). */}
      {wa ? (
        <Card title={T("تشخيص واتساب", "WhatsApp diagnostics")}>
          <div className="row" style={{ gap: 18, flexWrap: "wrap", padding: 2 }}>
            <Stat label={T("الخطوط المتصلة", "Connected lines")} value={(wa.activeLineCount != null ? wa.activeLineCount : (wa.lineCount != null ? wa.lineCount : 0))} />
            <Stat label={T("الرقم المتصل", "Connected number")} value={wa.connectedNumber || wa.phoneNumber || "—"} />
            <Stat label={T("الوضع", "Mode")} value={wa.mode || wa.channel || "—"} />
            <Stat label={T("الويبهوك", "Webhook")} value={wa.webhookConfigured ? T("مُعدّ", "Configured") : T("غير مُعدّ", "Not set")} />
            <Stat label={T("آخر خطأ", "Last error")} value={wa.lastError || "—"} />
          </div>
          {!(wa.live || wa.connected || wa.webStatus === "connected") ? <div className="subtle" style={{ fontSize: 11.5, marginTop: 8 }}>{T("لا يوجد خط واتساب متصل. اربط خطاً من إعداد النظام لتلقّي الرسائل والرد عليها.", "No WhatsApp line connected. Connect a line in System Setup to receive + reply to messages.")}</div> : null}
        </Card>
      ) : null}

      {/* THE COMPANY — one org, every role + its brain status (honest: functional roles labelled). */}
      {org ? (
        <Card title={T("الشركة الواحدة", "The one company")}>
          <div className="col" style={{ gap: 8, padding: 2 }}>
            <RoleRow label={T("عاصم (الرئيس التنفيذي)", "Assem (CEO)")} sub={org.ceo && org.ceo.objectives} tone={org.brain && org.brain.status === "LIVE_LLM" ? "green" : "orange"} lang={lang} />
            <div className="subtle" style={{ fontSize: 12, fontWeight: 700, marginTop: 4 }}>{T("المدراء التنفيذيون", "Directors")} ({org.directors.length})</div>
            {org.directors.map((d) => <RoleRow key={d.roleId} label={(lang === "ar" ? "" : "") + d.title} sub={d.objectives} indent lang={lang} />)}
            <div className="subtle" style={{ fontSize: 12, fontWeight: 700, marginTop: 4 }}>{T("المدراء", "Managers")} · {T("الوكلاء", "Agents")}</div>
            <div className="subtle" style={{ fontSize: 12 }}>
              {T("مدير مبيعات حقيقي", "1 real Sales Manager")} ({org.counts.managersReal}) · {org.counts.managersFunctional} {T("أدوار وظيفية", "functional")} · {org.counts.agentsReal} {T("وكلاء حقيقيون", "real agents")} · {org.counts.agentsFunctional} {T("أدوار وكلاء وظيفية", "functional agent roles")}
            </div>
            <div className="subtle" style={{ fontSize: 11, marginTop: 6 }}>{(org.note && (lang === "ar" ? org.note.ar : org.note.en)) || ""}</div>
          </div>
        </Card>
      ) : null}
    </div>
  );
}

function Stat({ label, value }) {
  return (
    <div className="col" style={{ gap: 2, minWidth: 110 }}>
      <div className="subtle" style={{ fontSize: 11 }}>{label}</div>
      <div style={{ fontSize: 14, fontWeight: 700, wordBreak: "break-word" }}>{String(value)}</div>
    </div>
  );
}
function RoleRow({ label, sub, indent, tone, lang }) {
  return (
    <div className="row between" style={{ alignItems: "center", gap: 8, paddingInlineStart: indent ? 14 : 0 }}>
      <div className="col" style={{ gap: 1, minWidth: 0 }}>
        <b style={{ fontSize: 13 }}>{label}</b>
        {sub ? <div className="subtle" style={{ fontSize: 11, maxWidth: 560, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{sub}</div> : null}
      </div>
      {tone ? <Badge tone={tone}>{tone === "green" ? (lang === "ar" ? "مباشر" : "Live") : (lang === "ar" ? "بانتظار المفتاح" : "Awaiting key")}</Badge> : null}
    </div>
  );
}
