/* ============================================================================
   ALFRED — operational butler for Mission Control.
   Local-only. Reads window.MissionState. Zero tokens, zero network, zero AI.

   Wrapped in an IIFE: Babel standalone evaluates each <script type="text/babel">
   in the SAME global scope, so a bare `const { useState } = React` here
   would collide with the identical line in app.jsx / inbox.jsx / guide.jsx.
============================================================================ */
(function () {
const { useState, useEffect, useMemo } = React;

// Re-render whenever MissionState mutates. Same pattern as the other views.
function useAlfredTick() {
  const [, force] = useState(0);
  useEffect(() => {
    const ms = window.MissionState;
    if (!ms || typeof ms.subscribe !== "function") return;
    return ms.subscribe(() => force(n => (n + 1) | 0));
  }, []);
}

function navigateTo(target) {
  if (window.MissionControlNav && typeof window.MissionControlNav.goTo === "function") {
    window.MissionControlNav.goTo(target);
  }
}

// Compact HMS from a log timestamp (already HH:MM:SS) or fall back.
function shortTimestamp(s) {
  if (typeof s !== "string" || !s) return "—";
  return s.slice(0, 8);
}

// -----------------------------------------------------------------------------
// HEADER
// -----------------------------------------------------------------------------
function AlfredHeader() {
  return (
    <div className="al-header">
      <div>
        <div className="al-eyebrow">JARVIS · ALFRED</div>
        <div className="al-title">Encargado de Mission Control</div>
        <div className="al-sub">Resumen vivo del sistema. Conozco el manual y leo el estado actual.</div>
      </div>
      <div className="al-mode-tag">MODO LOCAL · SIN IA</div>
    </div>
  );
}

// -----------------------------------------------------------------------------
// SYSTEM SNAPSHOT — 5 mini-cards derived from MissionState.
// -----------------------------------------------------------------------------
function SystemSnapshot({ snapshot }) {
  if (!snapshot) return null;
  const cards = [
    {
      label: "Agentes",
      lines: [
        snapshot.agents.working + " activos",
        snapshot.agents.idle + " en espera",
      ],
      tone: "info",
    },
    {
      label: "Salas",
      lines: [
        snapshot.rooms.core + " base",
        snapshot.rooms.custom + " custom",
      ],
      tone: "info",
    },
    {
      label: "Tareas",
      lines: [
        snapshot.tasks.running + " corriendo",
        snapshot.tasks.queued + " en cola",
        snapshot.tasks.terminal + " cerradas",
      ],
      tone: snapshot.tasks.atHundred > 0 ? "warning" : "info",
    },
    {
      label: "Alertas",
      lines: [
        snapshot.alerts.critical + " critical",
        snapshot.alerts.warning + " warning",
      ],
      tone: snapshot.alerts.critical > 0 ? "critical" : (snapshot.alerts.warning > 0 ? "warning" : "info"),
    },
    {
      label: "Bandeja",
      lines: [
        snapshot.inbox.totalNew + " sin revisar",
        snapshot.inbox.urgent + " urgentes",
      ],
      tone: snapshot.inbox.urgent > 0 ? "warning" : "info",
    },
  ];

  return (
    <div className="al-snapshot">
      {cards.map(c => (
        <div key={c.label} className={"al-snap-card al-tone-" + c.tone}>
          <div className="al-snap-label">{c.label}</div>
          <div className="al-snap-lines">
            {c.lines.map((ln, i) => <div key={i} className="al-snap-line">{ln}</div>)}
          </div>
        </div>
      ))}
    </div>
  );
}

// -----------------------------------------------------------------------------
// SYSTEM STATUS LINE — automation + last activity, single line.
// -----------------------------------------------------------------------------
function SystemStatus({ snapshot }) {
  if (!snapshot) return null;
  const automationOk = snapshot.automation.running;
  const cls = "al-status" + (automationOk ? " al-status-ok" : " al-status-warn");
  const dot = automationOk ? "●" : "○";
  const automationText = automationOk ? "Automatización corriendo" : "Automatización detenida";
  const lastLog = snapshot.lastLogTimestamp
    ? "Última actividad " + shortTimestamp(snapshot.lastLogTimestamp)
    : "Sin actividad reciente";
  return (
    <div className={cls}>
      <span className="al-status-dot">{dot}</span>
      <span>Sistema operativo</span>
      <span className="al-status-sep">·</span>
      <span>{automationText}</span>
      <span className="al-status-sep">·</span>
      <span>{lastLog}</span>
    </div>
  );
}

// -----------------------------------------------------------------------------
// REVIEW QUEUE — what to look at first, derived from current state.
// -----------------------------------------------------------------------------
function ReviewQueue({ items, allClearMessage }) {
  if (!items.length) {
    return (
      <div className="al-review-empty">
        <span className="al-review-empty-icon">✓</span>
        <span className="al-review-empty-text">{allClearMessage}</span>
      </div>
    );
  }
  return (
    <ol className="al-review-list">
      {items.map((it, i) => (
        <li key={it.id} className={"al-review-step al-review-tone-" + (it.tone || "info")}>
          <span className="al-review-num">{i + 1}</span>
          <div className="al-review-body">
            <div className="al-review-step-title">{it.title}</div>
            <div className="al-review-step-detail">{it.detail}</div>
          </div>
          {it.tabTarget && (
            <button
              type="button"
              className="al-review-go"
              onClick={() => navigateTo(it.tabTarget)}
            >Ir ›</button>
          )}
        </li>
      ))}
    </ol>
  );
}

// -----------------------------------------------------------------------------
// CAPABILITIES LIST — what's active + what's pending.
// -----------------------------------------------------------------------------
function CapabilitiesList() {
  const K = window.AlfredKnowledge;
  if (!K) return null;
  return (
    <div className="al-caps">
      <ul className="al-caps-list">
        {K.capabilities.map(c => (
          <li key={c.id} className="al-cap">
            <span className="al-cap-mark al-cap-mark-active">✓</span>
            <div className="al-cap-body">
              <div className="al-cap-name">
                {c.name}
                {c.tabTarget && (
                  <button
                    type="button"
                    className="al-cap-go"
                    onClick={() => navigateTo(c.tabTarget)}
                    aria-label={"Ir a " + c.name}
                  >›</button>
                )}
              </div>
              <div className="al-cap-line">{c.tagline}</div>
            </div>
          </li>
        ))}
        {K.pendingCapabilities.map(c => (
          <li key={c.id} className="al-cap al-cap-pending">
            <span className="al-cap-mark al-cap-mark-pending">◷</span>
            <div className="al-cap-body">
              <div className="al-cap-name">{c.name} <span className="al-cap-tag">PENDIENTE</span></div>
              <div className="al-cap-line">{c.tagline}</div>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

// -----------------------------------------------------------------------------
// RECENT CHANGES — last meaningful logs (filtering ambient automation noise).
// -----------------------------------------------------------------------------
function RecentChanges({ logs, milestones }) {
  const hasMilestones = milestones && milestones.length > 0;
  if (!logs.length && !hasMilestones) {
    return <div className="al-recent-empty">Sin actividad reciente.</div>;
  }
  return (
    <ul className="al-recent">
      {hasMilestones && milestones.map(m => (
        <li key={"ms-" + m.id} className="al-recent-row">
          <span className="al-recent-time">{m.label || "·"}</span>
          <span className="al-recent-msg" title={m.message}>{m.message}</span>
        </li>
      ))}
      {logs.map(l => (
        <li key={l.id} className="al-recent-row">
          <span className="al-recent-time">{shortTimestamp(l.timestamp)}</span>
          <span className="al-recent-msg" title={l.message}>{l.message}</span>
        </li>
      ))}
    </ul>
  );
}

// -----------------------------------------------------------------------------
// LOGIC: build the snapshot + review queue from MissionState.
// Pure derivation — no mutations.
// -----------------------------------------------------------------------------
function buildSnapshot(ms) {
  if (!ms) return null;
  const agents  = ms.getAgents       ? ms.getAgents()       : [];
  const rooms   = ms.getRooms        ? ms.getRooms()        : [];
  const tasks   = ms.getTasks        ? ms.getTasks()        : [];
  const alerts  = ms.getActiveAlerts ? ms.getActiveAlerts() : [];
  const inbox   = ms.getInboxSummary ? ms.getInboxSummary() : { urgent: 0, totalNew: 0, collab: 0, opportunity: 0 };
  const autInfo = ms.automationInfo  ? ms.automationInfo()  : { running: false };
  const logs    = ms.getLogs         ? ms.getLogs()         : [];

  const agentCounts = {
    total:   agents.length,
    working: agents.filter(a => a.status === "Working" || a.activity === "working").length,
    idle:    agents.filter(a => a.status !== "Working" && a.activity !== "working").length,
  };
  const roomCounts = {
    total:  rooms.length,
    core:   rooms.filter(r => r.isCore === true).length,
    custom: rooms.filter(r => r.isCore !== true).length,
  };
  const taskCounts = {
    running:   tasks.filter(t => t.status === "running").length,
    paused:    tasks.filter(t => t.status === "paused").length,
    queued:    tasks.filter(t => t.status === "queued").length,
    terminal:  tasks.filter(t => t.status === "completed" || t.status === "cancelled").length,
    atHundred: tasks.filter(t => t.status === "running" && (Number(t.progress) || 0) >= 100).length,
  };
  const alertCounts = {
    total:    alerts.length,
    critical: alerts.filter(a => a.severity === "critical").length,
    warning:  alerts.filter(a => a.severity === "warning").length,
    info:     alerts.filter(a => a.severity === "info").length,
  };
  const inboxCounts = {
    urgent:      inbox.urgent      || 0,
    collab:      inbox.collab      || 0,
    opportunity: inbox.opportunity || 0,
    totalNew:    inbox.totalNew    || 0,
  };

  // Last log timestamp for the status line.
  const lastLogTimestamp = logs.length ? logs[logs.length - 1].timestamp : null;

  return {
    agents:     agentCounts,
    rooms:      roomCounts,
    tasks:      taskCounts,
    alerts:     alertCounts,
    inbox:      inboxCounts,
    automation: { running: !!autInfo.running },
    lastLogTimestamp: lastLogTimestamp,
  };
}

function buildReviewQueue(ms, snapshot) {
  const K = window.AlfredKnowledge;
  if (!ms || !snapshot || !K) return [];
  const out = [];
  const seq = K.reviewSequence;
  const byId = (id) => seq.find(s => s.id === id);

  // 1) Critical alerts
  if (snapshot.alerts.critical > 0) {
    const def = byId("critical_alerts");
    out.push({
      id:        def.id,
      title:     def.title,
      detail:    def.describe(snapshot.alerts.critical),
      tabTarget: def.tabTarget,
      tone:      "critical",
    });
  }
  // 2) Tasks at 100%
  if (snapshot.tasks.atHundred > 0) {
    const def = byId("tasks_at_100");
    out.push({
      id:        def.id,
      title:     def.title,
      detail:    def.describe(snapshot.tasks.atHundred),
      tabTarget: def.tabTarget,
      tone:      "warning",
    });
  }
  // 3) Warning alerts
  if (snapshot.alerts.warning > 0) {
    const def = byId("warning_alerts");
    out.push({
      id:        def.id,
      title:     def.title,
      detail:    def.describe(snapshot.alerts.warning),
      tabTarget: def.tabTarget,
      tone:      "warning",
    });
  }
  // 4) Inbox urgents / collabs / opportunities
  const inboxNeedsAttention =
    snapshot.inbox.urgent > 0 || snapshot.inbox.collab > 0 || snapshot.inbox.opportunity > 0;
  if (inboxNeedsAttention) {
    const def = byId("inbox_priority");
    out.push({
      id:        def.id,
      title:     def.title,
      detail:    def.describe(snapshot.inbox),
      tabTarget: def.tabTarget,
      tone:      snapshot.inbox.urgent > 0 ? "warning" : "info",
    });
  }
  // 5 + 6) Stalled / queue overload — derived from the current alerts.
  const allAlerts = (ms.getActiveAlerts ? ms.getActiveAlerts() : []);
  const stalledCount  = allAlerts.filter(a => a.kind === "task_stalled").length;
  const overloadCount = allAlerts.filter(a => a.kind === "queue_overload").length;
  if (stalledCount > 0) {
    const def = byId("stalled");
    out.push({
      id:        def.id,
      title:     def.title,
      detail:    def.describe(stalledCount),
      tabTarget: def.tabTarget,
      tone:      "warning",
    });
  }
  if (overloadCount > 0) {
    const def = byId("queue_overload");
    out.push({
      id:        def.id,
      title:     def.title,
      detail:    def.describe(overloadCount),
      tabTarget: def.tabTarget,
      tone:      "info",
    });
  }
  return out;
}

// Filter logs for "recent changes": skip ambient AUTO heartbeats, keep
// operator-meaningful events. Last 5, newest first.
function buildRecentLogs(ms) {
  if (!ms || !ms.getLogs) return [];
  const logs = ms.getLogs() || [];
  const meaningful = logs.filter(l => {
    if (!l) return false;
    if (l.source === "AUTO" && l.severity === "low") return false; // ambient noise
    return true;
  });
  // Last 5, newest first.
  return meaningful.slice(-5).reverse().map(l => ({
    id:        l.id,
    timestamp: l.timestamp,
    message:   (l.message || "").slice(0, 110),
  }));
}

// -----------------------------------------------------------------------------
// ROOT
// -----------------------------------------------------------------------------
function AlfredApp() {
  useAlfredTick();
  const ms = window.MissionState;

  const snapshot = useMemo(() => buildSnapshot(ms), [ms, ms && ms.getAgents && ms.getAgents().length, ms && ms.getTasks && ms.getTasks().length]);
  // Note: useMemo deps above are best-effort — useAlfredTick already forces
  // re-render on any notify(), so the snapshot is always fresh.
  const liveSnapshot = buildSnapshot(ms);
  const reviewItems  = buildReviewQueue(ms, liveSnapshot);
  const recentLogs   = buildRecentLogs(ms);
  const K = window.AlfredKnowledge;
  const allClear = (K && K.allClearMessage) || "Sin urgencias ahora. Puedes operar con normalidad.";

  return (
    <div className="al-root">
      <div className="al-bg-grid" aria-hidden="true" />
      <div className="al-shell">
        <AlfredHeader />
        <SystemStatus snapshot={liveSnapshot} />
        <SystemSnapshot snapshot={liveSnapshot} />

        <div className="al-cols">
          <section className="al-col al-col-review">
            <div className="al-section-head">
              <span className="al-section-eyebrow">A · QUÉ REVISAR PRIMERO</span>
              <span className="al-section-meta">{reviewItems.length || "—"}</span>
            </div>
            <ReviewQueue items={reviewItems} allClearMessage={allClear} />
          </section>

          <section className="al-col al-col-caps">
            <div className="al-section-head">
              <span className="al-section-eyebrow">B · CAPACIDADES</span>
            </div>
            <CapabilitiesList />
          </section>

          <section className="al-col al-col-recent">
            <div className="al-section-head">
              <span className="al-section-eyebrow">C · CAMBIOS RECIENTES</span>
            </div>
            <RecentChanges logs={recentLogs} milestones={K && K.recentMilestones} />
          </section>
        </div>
      </div>
    </div>
  );
}

const alfredMountEl = document.getElementById("alfred-react-root");
if (alfredMountEl) {
  const root = ReactDOM.createRoot(alfredMountEl);
  root.render(<AlfredApp />);
}
})();
