// screens-journey.jsx — the guided BUSINESS LAUNCH WORKFLOW for HOME. Turns the dashboard into an
// onboarding OS: "What should I do now?" + a 12-step visual journey + per-director recommendations.
// Reuse-only over /assem/journey. Every step's state is REAL (from business-journey.js).
const { useState: useJState, useEffect: useJEffect } = React;

const JDIRECTOR_LABEL = { assem: { en: "Assem CEO", ar: "عاصم" }, revenue: { en: "Revenue Director", ar: "مدير الإيراد" }, sales: { en: "Revenue Director", ar: "مدير الإيراد" }, marketing: { en: "Channel Director", ar: "مدير القنوات" }, research: { en: "Data Director", ar: "مدير البيانات" }, customer_success: { en: "Customer Success Director", ar: "مدير نجاح العملاء" }, cto: { en: "CTO", ar: "المدير التقني" }, operations: { en: "Operations Director", ar: "مدير العمليات" }, data: { en: "Data Director", ar: "مدير البيانات" } };

function jL(x, lang) { return x && typeof x === "object" ? (lang === "ar" ? x.ar : x.en) : x; }
function jDir(id, lang) { return jL(JDIRECTOR_LABEL[id] || { en: id, ar: id }, lang); }

// the deep-link nav helper (mirrors shell deepLink).
function jGo(go, route, tab) {
  try { if (tab) { window.__navTab = { screen: route, tab }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: window.__navTab })); } } catch (e) {}
  go(route);
}

// "What should I do now?" — the single, always-answered next action.
function WhatShouldIDoNow({ next, currency, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  if (!next) return null;
  return (
    <Card style={{ background: "linear-gradient(180deg, var(--color-primary-tint-soft), #fff)", border: "1px solid var(--color-primary)" }}>
      <div className="col" style={{ gap: 8, padding: 8 }}>
        <div className="row" style={{ gap: 7, alignItems: "center" }}><Icon name="sparkles" size={16} style={{ color: "var(--color-secondary)" }} /><b style={{ fontSize: 13, letterSpacing: ".02em" }}>{T("ماذا أفعل الآن؟", "What should I do now?")}</b></div>
        <div style={{ fontSize: 18, fontWeight: 800 }}>{next.action}</div>
        <div className="subtle" style={{ fontSize: 12.5 }}><b>{T("لماذا", "Why")}:</b> {next.why}</div>
        <div className="subtle" style={{ fontSize: 12.5 }}><b>{T("النتيجة المتوقّعة", "Expected result")}:</b> {next.expectedResult}</div>
        <div className="between" style={{ marginTop: 4, flexWrap: "wrap", gap: 8 }}>
          <span className="subtle" style={{ fontSize: 12 }}>{T("المدير المسؤول", "Responsible Director")}: <b>{jDir(next.director, lang)}</b></span>
          <Button icon="arrowRight" onClick={() => jGo(go, next.cta.route, next.cta.tab)}>{T("نفّذ", "Execute")}</Button>
        </div>
      </div>
    </Card>
  );
}

// The 12-step visual journey.
function BusinessLaunchWorkflow({ steps, progressPct, completed, total, lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const icon = (st) => (st === "done" ? "checkcircle" : st === "current" ? "arrowRight" : "circle");
  const color = (st) => (st === "done" ? "var(--color-success)" : st === "current" ? "var(--color-secondary)" : "var(--fg-disabled)");
  return (
    <Card><div className="col" style={{ gap: 8, padding: 6 }}>
      <div className="between"><b style={{ fontSize: 14 }}>{T("رحلة إطلاق الأعمال", "Business Launch Workflow")}</b><span className="subtle" style={{ fontSize: 12 }}>{completed}/{total} · {progressPct}%</span></div>
      <div style={{ height: 7, borderRadius: 99, background: "var(--bg-2)", overflow: "hidden" }}><div style={{ height: "100%", width: progressPct + "%", background: "var(--color-secondary)", transition: "width .4s" }} /></div>
      <div className="col" style={{ gap: 2, marginTop: 4 }}>
        {(steps || []).map((s, i) => (
          <button key={s.key} onClick={() => jGo(go, s.cta.route, s.cta.tab)} className="row between" style={{ gap: 10, padding: "8px 10px", borderRadius: 9, border: "1px solid " + (s.status === "current" ? "var(--color-primary)" : "var(--border-1)"), background: s.status === "current" ? "var(--color-primary-tint-soft)" : "#fff", cursor: "pointer", textAlign: "start" }}>
            <span className="row" style={{ gap: 9 }}>
              <Icon name={icon(s.status)} size={16} style={{ color: color(s.status), flexShrink: 0 }} />
              <span style={{ fontSize: 12.5, fontWeight: s.status === "current" ? 700 : 600, color: s.status === "done" ? "var(--fg-3)" : "var(--fg-1)", textDecoration: s.status === "done" ? "line-through" : "none" }}>{jL(s.label, lang)}</span>
              {s.count != null && s.count > 0 ? <Badge tone="neutral">{s.count}</Badge> : null}
            </span>
            <span className="row" style={{ gap: 6, flexShrink: 0 }}>
              <span className="subtle" style={{ fontSize: 11 }}>{jDir(s.director, lang)}</span>
              {s.status === "current" ? <Badge tone="lime">{T("التالي", "Next")}</Badge> : null}
            </span>
          </button>
        ))}
      </div>
    </div></Card>
  );
}

// Executive Recommendations panel — top rec per director, each with Approve/Reject/Modify/Assign.
function ExecutiveRecommendationsPanel({ lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [data, setData] = useJState(null);
  const [acted, setActed] = useJState({});   // director → action label
  useJEffect(() => { API.assem.journeyRecommendations(lang).then(setData).catch(() => setData({ error: true })); }, [lang]);
  const act = (r, action) => {
    if (action === "modify" || action === "assign") { go("head"); return; }
    setActed((a) => ({ ...a, [r.director]: action }));
    API.assem.recommendationAction(r.director, r.recommendation, action).catch(() => {});
  };
  if (!data) return <Card><div className="skel" style={{ height: 80, borderRadius: 10 }} /></Card>;
  if (data.error || !(data.recommendations || []).length) return null;
  return (
    <Card><div className="col" style={{ gap: 8, padding: 6 }}>
      <b style={{ fontSize: 14 }}>{T("توصيات تنفيذية", "Executive recommendations")}</b>
      {data.recommendations.map((r, i) => (
        <div key={i} className="col" style={{ gap: 6, padding: "8px 0", borderTop: i ? "1px solid var(--border-1)" : "none" }}>
          <div className="row between" style={{ gap: 8, flexWrap: "wrap" }}>
            <span style={{ fontSize: 12.5 }}><b>{jDir(r.director, lang)}:</b> {r.recommendation}</span>
          </div>
          {acted[r.director] ? <div className="subtle" style={{ fontSize: 11.5, color: "#15803D" }}><Icon name="checkcircle" size={12} /> {T("سُجّل", "Recorded")}: {acted[r.director]}</div> : (
            <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
              <Button size="sm" onClick={() => act(r, "approve")}>{T("اعتمد", "Approve")}</Button>
              <Button size="sm" variant="ghost" onClick={() => act(r, "reject")}>{T("ارفض", "Reject")}</Button>
              <Button size="sm" variant="ghost" onClick={() => act(r, "modify")}>{T("عدّل", "Modify")}</Button>
              <Button size="sm" variant="ghost" onClick={() => act(r, "assign")}>{T("أسند", "Assign")}</Button>
              <Button size="sm" variant="ghost" onClick={() => act(r, "escalate")}>{T("تصعيد", "Escalate")}</Button>
            </div>
          )}
        </div>
      ))}
      <div className="subtle" style={{ fontSize: 10.5, color: "var(--color-orange)" }}>{T("كل إجراء يُسجَّل كقرار قابل للتدقيق — لا تنفيذ تلقائي.", "Every action is recorded as an auditable decision — nothing auto-executes.")}</div>
    </div></Card>
  );
}

// DailyBriefHomeCard — the CEO DAILY OPERATING MEETING at the TOP of HOME (Executive Operating Loop V2).
// "Good morning Mohamed. Here's what happened yesterday, what must happen today, what's blocked, and what
// I need you to approve." Reuse-only over /assem/morning-meeting. Kept SIMPLE — chips + top actions, no
// giant tables. Every action/decision has a REAL button (opens the responsible manager / decisions).
function DailyBriefHomeCard({ lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const data = useStore();
  const [d, setD] = useJState(null);
  useJEffect(() => { API.assem.morningMeeting(lang).then(setD).catch(() => setD({ error: true })); }, [lang]);
  if (!d) return <Card><div className="skel" style={{ height: 120, borderRadius: 10 }} /></Card>;
  if (d.error) return null;
  const y = d.yesterday || {}; const today = d.today || {}; const ans = d.answers || {}; const acct = d.accountabilityCounts || {};
  const name = (data.meta && data.meta.user && data.meta.user.name) ? String(data.meta.user.name).split(" ")[0] : "";
  const goDir = (dir) => { try { window.__navTab = { screen: "head", director: dir || "assem" }; window.dispatchEvent(new CustomEvent("maxab:navtab", { detail: window.__navTab })); } catch (e) {} go("head"); };
  const ownerLabel = (o) => (o && o !== "founder" && JDIRECTOR_LABEL[o]) ? jDir(o, lang) : T("المؤسس", "Founder");
  const chip = (k, v, tone) => <span style={{ fontSize: 11.5, padding: "3px 9px", borderRadius: 7, background: tone ? "var(--color-orange-soft, #FFF7ED)" : "var(--bg-2)", border: "1px solid " + (tone ? "var(--color-orange)" : "var(--border-1)"), color: tone ? "var(--color-orange)" : "inherit" }}>{k}: <b>{v == null ? "—" : v}</b></span>;
  const actions = d.actionPlan || [];
  return (
    <Card style={{ border: "1px solid var(--color-primary)", background: "linear-gradient(180deg, var(--color-primary-tint-soft), #fff)" }}>
      <div className="col" style={{ gap: 10, padding: 8 }}>
        <div className="between" style={{ flexWrap: "wrap", gap: 8 }}>
          <b style={{ fontSize: 15 }}>☀ {jL(d.greeting, lang)}{name ? ` ${name}` : ""} — {T("اجتماع اليوم", "today's meeting")}</b>
          <Button size="sm" variant="ghost" icon="arrowRight" onClick={() => goDir("assem")}>{T("الموجز الكامل", "Full brief")}</Button>
        </div>
        {/* YESTERDAY */}
        <div className="col" style={{ gap: 4 }}>
          <span className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{T("أمس", "Yesterday")}</span>
          <div className="row wrap" style={{ gap: 6 }}>
            {chip(T("إيراد", "Revenue"), y.revenue != null ? window.fmtCurrency(y.revenue) : "—")}
            {chip(T("اجتماعات", "Meetings"), y.meetings)}
            {chip(T("فوز", "Wins"), y.wins)}
            {chip(T("خسارة", "Losses"), y.losses)}
            {chip(T("تجديدات", "Renewals"), y.renewals)}
          </div>
        </div>
        {/* TODAY — what must happen */}
        {today.topPriority ? (
          <div className="col" style={{ gap: 2 }}>
            <span className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{T("اليوم", "Today")}</span>
            <div style={{ fontSize: 13 }}><b>{today.topPriority.action}</b>{today.topPriority.why ? <span className="subtle"> — {today.topPriority.why}</span> : null}</div>
          </div>
        ) : null}
        {/* ACTION PLAN — top actions, each with a real button (open the responsible manager) */}
        {actions.length ? (
          <div className="col" style={{ gap: 5 }}>
            <span className="subtle" style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".04em" }}>{T("خطة العمل — أهم الإجراءات", "Action plan — top actions")}</span>
            {actions.slice(0, 4).map((a, i) => (
              <div key={i} className="row between" style={{ gap: 8, flexWrap: "wrap", paddingTop: i ? 5 : 0, borderTop: i ? "1px solid var(--border-1)" : "none" }}>
                <span style={{ fontSize: 12.5, minWidth: 0 }}><Icon name="arrowRight" size={12} style={{ color: "var(--color-secondary)" }} /> {jL(a.action, lang) || a.action} <span className="subtle">· {ownerLabel(a.owner)}{a.approvalNeeded ? " · " + T("يحتاج اعتمادك", "needs you") : ""}</span></span>
                <Button size="sm" variant="ghost" onClick={() => goDir(a.cta && a.cta.director)}>{jL(a.cta && a.cta.label, lang) || T("افتح", "Open")}</Button>
              </div>
            ))}
          </div>
        ) : null}
        {/* NEEDS YOUR ATTENTION — decisions + risks + who's blocked / waiting you (each actionable) */}
        <div className="row wrap" style={{ gap: 6 }}>
          {d.founderDecisions && d.founderDecisions.count ? <button onClick={() => goDir("assem")} style={{ cursor: "pointer", fontSize: 11.5, padding: "3px 9px", borderRadius: 7, background: "var(--color-orange-soft, #FFF7ED)", border: "1px solid var(--color-orange)", color: "var(--color-orange)" }}>{T("قرارات تنتظرك", "Decisions for you")}: <b>{d.founderDecisions.count}</b> →</button> : null}
          {acct.blocked ? <span style={{ fontSize: 11.5, padding: "3px 9px", borderRadius: 7, background: "var(--color-danger-soft, #FEF2F2)", border: "1px solid var(--color-danger)", color: "var(--color-danger)" }}>{T("مدير معطّل", "Blocked")}: <b>{acct.blocked}</b></span> : null}
          {acct.waitingFounder ? <span style={{ fontSize: 11.5, padding: "3px 9px", borderRadius: 7, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("بانتظارك", "Waiting you")}: <b>{acct.waitingFounder}</b></span> : null}
          {(d.risks || []).length ? <span style={{ fontSize: 11.5, padding: "3px 9px", borderRadius: 7, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>{T("مخاطر", "Risks")}: <b>{d.risks.length}</b></span> : null}
        </div>
        {/* One honest pressure line: customer at risk OR what's blocking revenue (only if real) */}
        {ans.customerAtRisk && ans.customerAtRisk.name ? (
          <div className="row" style={{ gap: 7, fontSize: 12, padding: "7px 10px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
            <Icon name="heart" size={13} style={{ color: "var(--color-orange)", flexShrink: 0 }} />
            <span>{T("عميل معرّض للتسرّب", "Customer at risk")}: <b>{ans.customerAtRisk.name}</b>{ans.customerAtRisk.action ? <span className="subtle"> — {ans.customerAtRisk.action}</span> : null}</span>
          </div>
        ) : (ans.blockingRevenue && !ans.blockingRevenue.answer ? null : (ans.blockingRevenue && ans.blockingRevenue.owner ? (
          <div className="row" style={{ gap: 7, fontSize: 12, padding: "7px 10px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--border-1)" }}>
            <Icon name="alert" size={13} style={{ color: "var(--color-orange)", flexShrink: 0 }} />
            <span>{T("ما يعيق الإيراد", "Blocking revenue")}: <b>{jL(ans.blockingRevenue.answer, lang) || ans.blockingRevenue.answer}</b></span>
          </div>
        ) : null))}
      </div>
    </Card>
  );
}

// JourneyHome — the guided HOME (First-Revenue view). Composes the three pieces.
function JourneyHome({ lang, go }) {
  const T = (ar, en) => (lang === "ar" ? ar : en);
  const [j, setJ] = useJState(null);
  useJEffect(() => { API.assem.journey(lang).then(setJ).catch(() => setJ({ error: true })); }, [lang]);
  if (!j) return <Card><div className="skel" style={{ height: 120, borderRadius: 10 }} /></Card>;
  if (j.error) return <Card><EmptyState icon="alert" title={T("تعذّر تحميل الرحلة", "Could not load the journey")} /></Card>;
  // The current bottleneck = the journey's current step (what is blocking progress to revenue). Reuse-only — no extra fetch.
  const bottleneck = (j.steps || []).find((s) => s.status === "current");
  return (
    <div className="col" style={{ gap: 14 }}>
      {/* Daily Executive Brief (P3) — the founder's morning recap, first thing on HOME. */}
      <DailyBriefHomeCard lang={lang} go={go} />
      {/* Workflow header (Part 12) + plain app purpose, so a first-time founder gets it in seconds. */}
      <div className="col" style={{ gap: 2 }}>
        <div className="subtle" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--fg-disabled)" }}>{T("افهم ← قرّر ← نفّذ", "Understand → Decide → Act")}</div>
        <div className="subtle" style={{ fontSize: 12.5 }}>{T("هذه شركتك للمبيعات بالذكاء الاصطناعي — تجد العملاء، تبيع، تحصّل، وتنمّي الإيراد. ابدأ بالخطوة التالية بالأسفل.", "This is your AI sales company — it finds leads, sells, collects, and grows revenue. Start with the next step below.")}</div>
      </div>
      {bottleneck ? (
        <div className="row" style={{ gap: 9, fontSize: 12.5, padding: "9px 12px", borderRadius: 9, background: "var(--bg-2)", border: "1px solid var(--color-orange)" }}>
          <Icon name="alert" size={15} style={{ color: "var(--color-orange)", flexShrink: 0 }} />
          <span><b>{T("العائق الحالي", "Current bottleneck")}:</b> {jL(bottleneck.label, lang)} — <span className="subtle">{T("المسؤول", "owner")} {jDir(bottleneck.director, lang)}</span></span>
        </div>
      ) : null}
      <WhatShouldIDoNow next={j.nextAction} currency={j.currency} lang={lang} go={go} />
      <BusinessLaunchWorkflow steps={j.steps} progressPct={j.progressPct} completed={j.completed} total={j.total} lang={lang} go={go} />
      <ExecutiveRecommendationsPanel lang={lang} go={go} />
    </div>
  );
}
window.JourneyHome = JourneyHome;
