// Copilot right-rail — activity feed + scripted Q&A that reads live app state.

function Copilot({ onClose }) {
  const { state, dispatch } = useApp();
  const tab = state.filters.copilotTab;
  const [input, setInput] = React.useState("");
  const bodyRef = React.useRef(null);

  // Auto-scroll chat to bottom on new messages or typing.
  React.useEffect(() => {
    if (tab === "chat" && bodyRef.current) {
      bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
    }
  }, [state.messages, state.typing, tab]);

  function respondTo(q) {
    const ql = q.toLowerCase();
    // Scripted answers pull live numbers from state so they stay truthful after user actions.
    const openShifts = state.rosterRows.filter(r => r.staff.open).length;
    const payrollOpen = state.payrollOpen.filter(r => r.tone !== "block").length;
    const blocked = state.staff.filter(s => s.status === "block").length;
    const expiring = state.expiries.filter(e => e.tone === "warn").length;

    if (ql.includes("plan")) return `Plan for today: 1) Resolve ${blocked} compliance block(s). 2) Approve ${payrollOpen} payroll exception(s) before 17:00 close. 3) Fill ${openShifts} open shift(s). Shall I open each in order?`;
    if (ql.includes("agency")) return "Agency spend is $18.4k WTD, down 24% vs plan. 7.4% dependency. I can draft a memo explaining the reduction for the exec team.";
    if (ql.includes("lachlan") || ql.includes("ahpra") || ql.includes("compliance")) {
      return blocked > 0
        ? `Lachlan Fitzgerald's AHPRA lapsed 12 Apr. I've held 3 shifts and gated pay release. Open the People page and use "Verify via AHPRA" to clear him.`
        : "Compliance is clean — no active blockers. Nice work.";
    }
    if (ql.includes("roster") || ql.includes("open shift")) {
      return openShifts > 0
        ? `Banksia Fri 24 Apr has ${openShifts} open slot(s). I've proposed Siobhán K. — internal agency, $412 less than Medacs, meets ratio, no consecutive nights. Accept from the Roster page.`
        : "Roster is fully staffed across the week. Nothing open.";
    }
    if (ql.includes("expire") || ql.includes("credential")) {
      return expiring > 0
        ? `${expiring} credential(s) expiring in the next 60 days: ${state.expiries.filter(e => e.tone === "warn").slice(0, 3).map(e => e.name.split(" ")[0]).join(", ")}. I've drafted renewal emails. Approve from the Compliance page.`
        : "No credentials expiring in the next 60 days. All clear.";
    }
    if (ql.includes("payroll") || ql.includes("pay")) {
      return payrollOpen > 0
        ? `${payrollOpen} payroll exception(s) still open. Biggest impact: missing manager approval on 8 Wattle shifts (+$2,180). Open Payroll → Resolve.`
        : "Payroll is clean — no open exceptions. You can run the period whenever you're ready.";
    }
    if (ql.includes("overtime") || ql.includes("ot")) return "OT ratio is 4.1% — under the 5% target. 1 staff member (Hien Nguyen) at 44.2h is the main contributor.";
    if (ql.includes("hello") || ql.includes("hi")) return "Morning Jess. What would you like me to check?";
    return `I don't have a scripted answer for that in this demo, but in production I'd reason over your live workforce data. Try asking about: plan, agency, compliance, open shifts, expiring credentials, or payroll.`;
  }

  function send(e) {
    e && e.preventDefault();
    const q = input.trim();
    if (!q) return;
    dispatch({ type: "COPILOT_MSG", msg: { role: "me", text: q } });
    setInput("");
    dispatch({ type: "SET_TYPING", on: true });
    setTimeout(() => {
      dispatch({ type: "SET_TYPING", on: false });
      dispatch({ type: "COPILOT_MSG", msg: { role: "ai", text: respondTo(q) } });
    }, 700);
  }

  function quickAsk(prompt) {
    dispatch({ type: "COPILOT_MSG", msg: { role: "me", text: prompt } });
    dispatch({ type: "SET_TYPING", on: true });
    dispatch({ type: "SET_FILTER", key: "copilotTab", value: "chat" });
    setTimeout(() => {
      dispatch({ type: "SET_TYPING", on: false });
      dispatch({ type: "COPILOT_MSG", msg: { role: "ai", text: respondTo(prompt) } });
    }, 700);
  }

  return (
    <aside className="copilot">
      <div className="copilot-head">
        <div className="copilot-mark">N</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="copilot-title">NuCo copilot</div>
          <div className="copilot-sub">Watching 4 wards · {state.staff.length} staff · live</div>
        </div>
        <TierBadge tier="L2" />
        <button className="icon-btn" onClick={onClose} aria-label="Close"><Icon name="x" size={13} /></button>
      </div>
      <div style={{ padding: "6px 16px 0", display: "flex", gap: 6, alignItems: "center" }}>
        <Badge tone="ai" dot>Guardrails active</Badge>
        <span className="sub" style={{ fontSize: 10.5 }}>Falls back to human at &lt;70% confidence</span>
      </div>

      <div style={{ padding: "10px 14px 0", display: "flex", gap: 6 }}>
        <button className="chip" data-active={tab === "activity"} onClick={() => dispatch({ type: "SET_FILTER", key: "copilotTab", value: "activity" })}>Activity <span className="count">{state.activity.length}</span></button>
        <button className="chip" data-active={tab === "chat"}     onClick={() => dispatch({ type: "SET_FILTER", key: "copilotTab", value: "chat" })}>Ask</button>
        <button className="chip" data-active={tab === "plans"}    onClick={() => dispatch({ type: "SET_FILTER", key: "copilotTab", value: "plans" })}>Plans <span className="count">{state.plans.length}</span></button>
      </div>

      {tab === "activity" && (
        <div className="copilot-body" style={{ overflowY: "auto" }}>
          <div className="eyebrow">Last 24 hours · system actions</div>
          <div>
            {state.activity.map((a, i) => (
              <div key={i} className="activity-item">
                <div className="activity-dot" data-tone={a.tone} />
                <div>
                  <div className="activity-title">{a.title}</div>
                  <div className="activity-body">{a.body}</div>
                  <div className="activity-time">{a.time} · auto</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === "chat" && (
        <>
          <div className="copilot-body" style={{ gap: 8, overflowY: "auto" }} ref={bodyRef}>
            {state.messages.map((m) => (
              <div key={m.id} className={"chat-msg" + (m.role === "me" ? " me" : "")}>
                {m.text}
              </div>
            ))}
            {state.typing && (
              <div className="chat-msg"><span className="typing"><i /><i /><i /></span></div>
            )}
            <div className="kbar" style={{ marginTop: 8 }}>
              <button className="chip" onClick={() => quickAsk("Plan my day")}>Plan my day</button>
              <button className="chip" onClick={() => quickAsk("Show agency exposure")}>Agency exposure</button>
              <button className="chip" onClick={() => quickAsk("Fix Lachlan's compliance")}>Fix Lachlan</button>
              <button className="chip" onClick={() => quickAsk("What credentials are expiring?")}>Expiring creds</button>
              <button className="chip" onClick={() => quickAsk("How many open shifts?")}>Open shifts</button>
            </div>
          </div>
          <form className="chat-input" onSubmit={send}>
            <input placeholder="Ask NuCo…" value={input} onChange={e => setInput(e.target.value)} />
            <button type="button" className="icon-btn" onClick={() => dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: "Voice input coming soon." } })}><Icon name="mic" size={14} /></button>
            <button type="submit" className="icon-btn" style={{ background: "var(--ink)", color: "var(--paper)" }}><Icon name="arrowRight" size={14} /></button>
          </form>
        </>
      )}

      {tab === "plans" && (
        <div className="copilot-body" style={{ overflowY: "auto" }}>
          <div className="eyebrow">Active plans · awaiting approval</div>
          {state.plans.length === 0 && (
            <div style={{ padding: 28, textAlign: "center" }}>
              <div className="serif" style={{ fontSize: 18 }}>No pending plans.</div>
              <div className="sub">NuCo will surface a new plan when something worth proposing emerges.</div>
            </div>
          )}
          {state.plans.map((p, i) => (
            <div key={p.id} className="card" style={{ background: "var(--bone)" }}>
              <div className="card-head" style={{ alignItems: "flex-start" }}>
                <div>
                  <div className="card-title">{p.title}</div>
                  <div className="card-sub">{p.steps.length} steps · {p.summary} · {p.risk} risk</div>
                </div>
                <Badge tone="ai">AI plan</Badge>
              </div>
              <div style={{ padding: "0 var(--dense-pad) 6px" }} className="hstack">
                <TierBadge tier="L3" />
                <ConfidencePill value={0.93 - i * 0.04} />
              </div>
              <div className="card-body hstack" style={{ gap: 6 }}>
                <button className="btn sage" onClick={() => {
                  dispatch({ type: "APPROVE_AI_PLAN", planId: p.id });
                  dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: `Plan applied · ${p.title.split(" ").slice(0, 4).join(" ")}…` } });
                }}>Approve</button>
                <button className="btn" onClick={() => dispatch({ type: "OPEN_MODAL", modal: { kind: "plan-review", planId: p.id } })}>Review</button>
              </div>
            </div>
          ))}
        </div>
      )}
    </aside>
  );
}

Object.assign(window, { Copilot });
