/* Tasks & Reminders · Documents · Workflows · Alerts & Signals.
   Grounded in window.OPS + window.DATA. Exports four views.            */

/* ============================ TASKS & REMINDERS ============================ */
const TASK_TYPE_META = {
  Risk: { c: "var(--rose)", icon: "bolt" }, Review: { c: "var(--accent)", icon: "target" },
  Report: { c: "var(--info)", icon: "document" }, Call: { c: "var(--warn)", icon: "phone" },
  Payment: { c: "var(--good)", icon: "receipt" },
};
function TasksView({ onOpen, userName }) {
  const D = window.DATA, O = window.OPS;
  const [done, setDone] = useLocalState("an_tasks_done", {});
  const [scope, setScope] = React.useState("all");
  const me = "p-maya"; // current user maps to lead account holder for demo
  const toggle = (id) => setDone((d) => ({ ...d, [id]: !d[id] }));
  const list = O.tasks.filter((t) => scope === "all" || (scope === "mine" ? t.owner === me : t.type === scope));
  const open = list.filter((t) => !done[t.id]);
  const groups = [
    ["Overdue", open.filter((t) => new Date(t.due) < O.today)],
    ["Today", open.filter((t) => t.due === O.iso(O.today))],
    ["Upcoming", open.filter((t) => new Date(t.due) > O.today)],
    ["Completed", list.filter((t) => done[t.id])],
  ];
  const overdueN = O.tasks.filter((t) => !done[t.id] && new Date(t.due) < O.today).length;
  const todayN = O.tasks.filter((t) => !done[t.id] && t.due === O.iso(O.today)).length;
  const doneN = O.tasks.filter((t) => done[t.id]).length;

  const Row = ({ t }) => {
    const tm = TASK_TYPE_META[t.type] || TASK_TYPE_META.Review; const isDone = !!done[t.id];
    const overdue = !isDone && new Date(t.due) < O.today;
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", borderBottom: "1px solid var(--border)" }}>
        <button onClick={() => toggle(t.id)} className="focusable" style={{ width: 20, height: 20, flex: "none", borderRadius: 6, border: "1.5px solid " + (isDone ? "var(--good)" : "var(--border-strong)"), background: isDone ? "var(--good)" : "transparent", color: "#fff", cursor: "pointer", display: "grid", placeItems: "center", padding: 0 }}>{isDone && <Icon name="check" size={13} />}</button>
        <span style={{ width: 26, height: 26, flex: "none", borderRadius: 7, display: "grid", placeItems: "center", background: "var(--surface-3)", color: tm.c }}><Icon name={tm.icon} size={14} /></span>
        <button className="focusable" onClick={() => onOpen(t.org)} style={{ flex: 1, minWidth: 0, textAlign: "left", background: "none", border: "none", cursor: "pointer", font: "inherit", padding: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 550, color: isDone ? "var(--text-faint)" : "var(--text)", textDecoration: isDone ? "line-through" : "none", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</div>
          <div style={{ fontSize: 11.5, color: "var(--text-muted)" }}>{t.type} · {D.byId[t.owner] ? D.byId[t.owner].name : "-"}</div>
        </button>
        {t.priority === "high" && !isDone && <span className="badge" style={{ background: "var(--rose-bg)", color: "var(--rose)", borderColor: "transparent" }}>High</span>}
        <span className="mono" style={{ fontSize: 12, width: 78, textAlign: "right", color: overdue ? "var(--rose)" : "var(--text-muted)" }}>{relDay(t.due)}</span>
      </div>
    );
  };

  return (
    <ModulePage icon="tasks" eyebrow="Tools" title="Tasks & Reminders" maxWidth={1100}
      subtitle="Reminders, follow-ups and reporting deadlines tied to every relationship - with a shared team view of what's due."
      actions={<button className="btn btn-primary"><Icon name="plus" size={15} /> New task</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 18, marginBottom: 20 }}>
        <StatTile icon="tasks" label="Open tasks" value={O.tasks.filter((t) => !done[t.id]).length} accent />
        <StatTile icon="bolt" label="Overdue" value={overdueN} color="var(--rose)" />
        <StatTile icon="calendar" label="Due today" value={todayN} color="var(--warn)" />
        <StatTile icon="check" label="Completed" value={doneN} color="var(--good)" />
      </div>

      <div style={{ marginBottom: 20 }}>
        <AINote title="Focus for today">
          {overdueN > 0 ? <span>You have <strong>{overdueN} overdue</strong> item{overdueN > 1 ? "s" : ""} - clearing the risk-flagged ones first protects your most important grantees.</span> : <span>Nothing overdue. {todayN} item{todayN === 1 ? "" : "s"} due today - a clear runway.</span>}
        </AINote>
      </div>

      <div style={{ display: "flex", gap: 6, marginBottom: 14, flexWrap: "wrap" }}>
        {[["all", "All"], ["mine", "Assigned to me"], ["Risk", "Risk"], ["Report", "Reports"], ["Call", "Calls"], ["Payment", "Payments"]].map(([v, l]) => {
          const on = scope === v;
          return <button key={v} className="tap focusable" onClick={() => setScope(v)} style={{ font: "inherit", fontSize: 12, fontWeight: 550, cursor: "pointer", padding: "5px 11px", borderRadius: 999, border: "1px solid " + (on ? "transparent" : "var(--border)"), background: on ? "var(--accent)" : "var(--surface-2)", color: on ? "var(--accent-contrast)" : "var(--text-muted)" }}>{l}</button>;
        })}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
        {groups.map(([label, items]) => items.length > 0 && (
          <div key={label} className="card" style={{ overflow: "hidden", padding: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "12px 16px", borderBottom: "1px solid var(--border)", background: "var(--surface-2)" }}>
              <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase", color: label === "Overdue" ? "var(--rose)" : "var(--text-muted)" }}>{label}</span>
              <span className="badge mono">{items.length}</span>
            </div>
            {items.map((t) => <Row key={t.id} t={t} />)}
          </div>
        ))}
      </div>
    </ModulePage>
  );
}

/* compact dashboard widget - exported for the dashboard */
function TasksWidget({ onNavigate, onOpen }) {
  const D = window.DATA, O = window.OPS;
  let done = {}; try { done = JSON.parse(localStorage.getItem("an_tasks_done") || "{}"); } catch (e) {}
  const open = O.tasks.filter((t) => !done[t.id]).slice(0, 5);
  return (
    <ModulePanel title="Tasks & reminders" icon="tasks" right={<button className="btn btn-sm btn-ghost" style={{ color: "var(--accent)" }} onClick={() => onNavigate("tasks")}>All <Icon name="arrowRight" size={14} /></button>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        {open.map((t) => {
          const tm = TASK_TYPE_META[t.type] || TASK_TYPE_META.Review;
          const overdue = new Date(t.due) < O.today;
          return (
            <button key={t.id} className="focusable" onClick={() => onOpen(t.org)} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", border: "1px solid var(--border)", borderRadius: 11, background: "var(--surface-2)", cursor: "pointer", textAlign: "left" }}>
              <span style={{ width: 26, height: 26, flex: "none", borderRadius: 7, display: "grid", placeItems: "center", background: "var(--surface-3)", color: tm.c }}><Icon name={tm.icon} size={14} /></span>
              <span style={{ flex: 1, fontSize: 13, fontWeight: 550, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{t.title}</span>
              <span className="mono" style={{ fontSize: 11.5, color: overdue ? "var(--rose)" : "var(--text-muted)", flex: "none" }}>{relDay(t.due)}</span>
            </button>
          );
        })}
      </div>
    </ModulePanel>
  );
}

/* ============================ DOCUMENTS ============================ */
function DocumentsView({ onOpen }) {
  const D = window.DATA, O = window.OPS;
  const [q, setQ] = React.useState("");
  const [kind, setKind] = React.useState("all");
  const kinds = ["all", ...Array.from(new Set(O.documents.map((d) => d.kind)))];
  const rows = O.documents.filter((d) => (kind === "all" || d.kind === kind) && (!q || d.name.toLowerCase().includes(q.toLowerCase())));
  const extColor = { PDF: "var(--rose)", DOCX: "var(--info)", XLSX: "var(--good)" };
  const totalSize = O.documents.length;

  return (
    <ModulePage icon="document" eyebrow="Tools" title="Documents" maxWidth={1200}
      subtitle="Agreements, reports and correspondence against every record - versioned, searchable and linked."
      actions={<button className="btn btn-primary"><Icon name="plus" size={15} /> Upload</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 18, marginBottom: 20 }}>
        <StatTile icon="document" label="Documents" value={totalSize} sub="across the ecosystem" accent />
        <StatTile icon="building" label="Linked orgs" value={new Set(O.documents.map((d) => d.org)).size} />
        <StatTile icon="receipt" label="Agreements" value={O.documents.filter((d) => d.kind === "Grant agreement").length} color="var(--good)" />
        <StatTile icon="history" label="Updated this month" value={O.documents.filter((d) => new Date(d.updated) > new Date(Date.now() - 31 * 864e5)).length} color="var(--info)" />
      </div>

      <div style={{ display: "flex", gap: 10, marginBottom: 14, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ position: "relative", flex: 1, minWidth: 220 }}>
          <Icon name="search" size={15} style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--text-faint)", pointerEvents: "none" }} />
          <input className="input focusable" placeholder="Search documents…" value={q} onChange={(e) => setQ(e.target.value)} style={{ paddingLeft: 36, height: 40 }} />
        </div>
        {kinds.map((k) => {
          const on = kind === k;
          return <button key={k} className="tap focusable" onClick={() => setKind(k)} style={{ font: "inherit", fontSize: 12, fontWeight: 550, cursor: "pointer", padding: "6px 11px", borderRadius: 999, border: "1px solid " + (on ? "transparent" : "var(--border)"), background: on ? "var(--accent)" : "var(--surface-2)", color: on ? "var(--accent-contrast)" : "var(--text-muted)" }}>{k === "all" ? "All types" : k}</button>;
        })}
      </div>

      <div className="card" style={{ overflow: "hidden", padding: 0 }}>
        {rows.slice(0, 40).map((d, i) => (
          <button key={d.id} className="focusable" onClick={() => onOpen(d.org)} style={{ display: "flex", alignItems: "center", gap: 13, width: "100%", textAlign: "left", padding: "12px 16px", border: "none", borderBottom: i < Math.min(rows.length, 40) - 1 ? "1px solid var(--border)" : "none", background: "none", cursor: "pointer" }}>
            <span style={{ width: 34, height: 34, flex: "none", borderRadius: 8, display: "grid", placeItems: "center", background: "var(--surface-3)", color: extColor[d.ext] || "var(--text-muted)" }}><Icon name="document" size={17} /></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 550, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{d.name}</div>
              <div style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{d.kind} · {d.size} · updated {relDay(d.updated)}</div>
            </div>
            <span className="badge mono" style={{ flex: "none" }}>{d.ext}</span>
            <Icon name="external" size={15} style={{ color: "var(--text-faint)", flex: "none" }} />
          </button>
        ))}
        {rows.length === 0 && <div style={{ padding: 28, textAlign: "center", fontSize: 13.5, color: "var(--text-faint)" }}>No documents match.</div>}
      </div>
    </ModulePage>
  );
}

/* ============================ WORKFLOWS ============================ */
function WorkflowsView() {
  const D = window.DATA, O = window.OPS;
  const [enabled, setEnabled] = useLocalState("an_workflows", O.workflows.reduce((m, w) => (m[w.id] = w.enabled, m), {}));
  const toggle = (id) => setEnabled((e) => ({ ...e, [id]: !e[id] }));
  const activeN = O.workflows.filter((w) => enabled[w.id]).length;
  const totalRuns = O.workflows.reduce((s, w) => s + w.runs, 0);

  return (
    <ModulePage icon="workflow" eyebrow="Tools" title="Workflows" maxWidth={1100}
      subtitle="No-code automations - when something happens in the ecosystem, run the busywork for you."
      actions={<button className="btn btn-primary"><Icon name="plus" size={15} /> New workflow</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginBottom: 20 }}>
        <StatTile icon="workflow" label="Active automations" value={activeN} sub={`of ${O.workflows.length} built`} accent />
        <StatTile icon="bolt" label="Runs this quarter" value={totalRuns} color="var(--good)" />
        <StatTile icon="clock" label="Time saved" value={`~${Math.round(totalRuns * 0.4)}h`} sub="estimated" color="var(--info)" />
      </div>

      <div style={{ marginBottom: 20 }}>
        <AINote title="Suggested automation">
          {O.alerts.length} live alerts were raised this week. Turning on <strong>"Relationship cooling"</strong> would auto-draft check-ins for the {O.atRisk.length} relationships predicted to go quiet.
        </AINote>
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {O.workflows.map((w) => {
          const on = !!enabled[w.id];
          return (
            <div key={w.id} className="card" style={{ padding: 18 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 14 }}>
                <span style={{ width: 38, height: 38, flex: "none", borderRadius: 10, display: "grid", placeItems: "center", background: on ? "var(--accent-soft)" : "var(--surface-3)", color: on ? "var(--accent)" : "var(--text-muted)" }}><Icon name="workflow" size={19} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 650 }}>{w.name}</div>
                  <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>{w.trigger} · <span className="mono">{w.runs}</span> runs</div>
                </div>
                <button onClick={() => toggle(w.id)} className="focusable" title={on ? "Disable" : "Enable"}
                  style={{ width: 44, height: 26, flex: "none", borderRadius: 999, border: "none", cursor: "pointer", background: on ? "var(--accent)" : "var(--surface-3)", position: "relative", transition: ".15s" }}>
                  <span style={{ position: "absolute", top: 3, left: on ? 21 : 3, width: 20, height: 20, borderRadius: 999, background: "#fff", transition: ".15s", boxShadow: "var(--shadow-sm)" }} />
                </button>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", opacity: on ? 1 : 0.5 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
                  <span style={{ width: 26, height: 26, borderRadius: 7, display: "grid", placeItems: "center", background: "var(--warn-bg)", color: "var(--warn)" }}><Icon name="bolt" size={14} /></span>
                  <span style={{ fontSize: 12.5, fontWeight: 600 }}>Trigger</span>
                </span>
                {w.steps.map(([ic, label], i) => (
                  <React.Fragment key={i}>
                    <Icon name="arrowRight" size={15} style={{ color: "var(--text-faint)", flex: "none" }} />
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "8px 12px", borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
                      <span style={{ width: 26, height: 26, borderRadius: 7, display: "grid", placeItems: "center", background: "var(--accent-soft)", color: "var(--accent)" }}><Icon name={ic} size={14} /></span>
                      <span style={{ fontSize: 12.5, fontWeight: 600 }}>{label}</span>
                    </span>
                  </React.Fragment>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </ModulePage>
  );
}

/* ============================ ALERTS & SIGNALS ============================ */
function AlertsView({ onOpen }) {
  const D = window.DATA, O = window.OPS;
  const [rules, setRules] = useLocalState("an_rules", O.rules.reduce((m, r) => (m[r.id] = r.enabled, m), {}));
  const toggle = (id) => setRules((e) => ({ ...e, [id]: !e[id] }));
  const sevMeta = { high: { c: "var(--rose)", bg: "var(--rose-bg)" }, med: { c: "var(--warn)", bg: "var(--warn-bg)" }, low: { c: "var(--info)", bg: "var(--info-bg)" } };
  const liveAlerts = O.alerts.filter((a) => rules[a.rule]);

  return (
    <ModulePage icon="signal" eyebrow="Tools" title="Alerts & Signals" maxWidth={1240}
      subtitle="Set living signals and get notified the moment something needs you - risk, silence, or an opportunity."
      actions={<button className="btn btn-primary"><Icon name="plus" size={15} /> New signal</button>}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 18, marginBottom: 20 }}>
        <StatTile icon="signal" label="Active signals" value={Object.values(rules).filter(Boolean).length} sub={`of ${O.rules.length} rules`} accent />
        <StatTile icon="bell" label="Live alerts" value={liveAlerts.length} color="var(--rose)" />
        <StatTile icon="bolt" label="High severity" value={liveAlerts.filter((a) => a.sev === "high").length} color="var(--warn)" />
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1.2fr", gap: 20, alignItems: "start" }}>
        <ModulePanel title="Signals" icon="signal" right={<span className="badge mono">{O.rules.length}</span>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
            {O.rules.map((r) => {
              const on = !!rules[r.id]; const sm = sevMeta[r.sev];
              return (
                <div key={r.id} style={{ display: "flex", alignItems: "flex-start", gap: 11, padding: "12px 13px", border: "1px solid var(--border)", borderRadius: 11, background: "var(--surface-2)" }}>
                  <span style={{ width: 8, height: 8, marginTop: 5, borderRadius: 999, background: sm.c, flex: "none" }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600 }}>{r.name}</div>
                    <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.45, marginTop: 2 }}>{r.desc}</div>
                    <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 5 }}><Icon name="bell" size={11} style={{ verticalAlign: "-1px" }} /> {r.channel}</div>
                  </div>
                  <button onClick={() => toggle(r.id)} className="focusable" style={{ width: 40, height: 23, flex: "none", borderRadius: 999, border: "none", cursor: "pointer", background: on ? "var(--accent)" : "var(--surface-3)", position: "relative" }}>
                    <span style={{ position: "absolute", top: 3, left: on ? 20 : 3, width: 17, height: 17, borderRadius: 999, background: "#fff", transition: ".15s", boxShadow: "var(--shadow-sm)" }} />
                  </button>
                </div>
              );
            })}
          </div>
        </ModulePanel>

        <ModulePanel title="Live alert feed" icon="bell" iconColor="var(--rose)" right={<span className="badge mono">{liveAlerts.length}</span>}>
          {liveAlerts.length ? <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {liveAlerts.map((a) => {
              const sm = sevMeta[a.sev];
              return (
                <button key={a.id} className="focusable" onClick={() => onOpen(a.org)} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", border: "1px solid var(--border)", borderLeft: `3px solid ${sm.c}`, borderRadius: 10, background: "var(--surface-2)", cursor: "pointer", textAlign: "left" }}>
                  <span style={{ width: 28, height: 28, flex: "none", borderRadius: 8, display: "grid", placeItems: "center", background: sm.bg, color: sm.c }}><Icon name="bell" size={14} /></span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 550, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.title}</div>
                    <div style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{relDay(a.when)} · {(O.rules.find((r) => r.id === a.rule) || {}).name}</div>
                  </div>
                  <span className="badge" style={{ flex: "none", background: sm.bg, color: sm.c, borderColor: "transparent", textTransform: "capitalize" }}>{a.sev}</span>
                </button>
              );
            })}
          </div> : <div style={{ fontSize: 13, color: "var(--text-faint)", padding: 8 }}>No live alerts - enable signals to start monitoring.</div>}
        </ModulePanel>
      </div>
    </ModulePage>
  );
}

window.TasksView = TasksView;
window.TasksWidget = TasksWidget;
window.DocumentsView = DocumentsView;
window.WorkflowsView = WorkflowsView;
window.AlertsView = AlertsView;
