// ============ AGENTS TAB · OFFICE FLOOR ============
// The default landing view: a wall of "workstation" cards. Each card is
// drawn front-on (think Zoom-call thumbnail of a coworker at their desk):
// a company-name banner across the top, the agent's character behind a
// desk, an office chair peeking up behind their head, a monitor in the
// foreground showing their live activity. Adding a new agent appends
// a new desk to the floor.

const _CharacterAvatar_agents = window.CharacterAvatar;

function AgentsTab({ agents, activity, onOpen, onNew, onRate, onChat, onSwitchTab }) {
  const feed = activity || ACTIVITY;
  const live = agents.filter(a => a.status === "live").length;
  const total = agents.length;
  const totalRuns = agents.reduce((s, a) => s + a.runs, 0);
  const avgRating = agents.length === 0
    ? "—"
    : (agents.reduce((s, a) => s + a.rating, 0) / agents.length).toFixed(1);

  // Office name lives in citrus_profile.name (the same key Settings uses).
  const readProfile = () => {
    try { return JSON.parse(localStorage.getItem("citrus_profile") || "{}"); }
    catch { return {}; }
  };
  const [officeName, setOfficeName]   = useState(() => readProfile().name || "Your office");
  const [editingName, setEditingName] = useState(false);
  const [draftName, setDraftName]     = useState(officeName);
  const [brand, setBrand]             = useState(() => readProfile());

  // Watch for brand changes (logo / color) and re-render
  useEffect(() => {
    const handler = () => setBrand(readProfile());
    window.addEventListener("citrus-brand", handler);
    return () => window.removeEventListener("citrus-brand", handler);
  }, []);
  const saveName = () => {
    const next = draftName.trim() || officeName;
    setOfficeName(next);
    try {
      const p = readProfile(); p.name = next;
      localStorage.setItem("citrus_profile", JSON.stringify(p));
    } catch {}
    setEditingName(false);
    window.toast && window.toast("Office name saved", "good");
  };

  const seenRef = useRef(new Set(agents.map(a => a.id)));
  const [justAdded, setJustAdded] = useState(null);
  useEffect(() => {
    const fresh = agents.find(a => !seenRef.current.has(a.id));
    if (fresh) {
      setJustAdded(fresh.id);
      seenRef.current.add(fresh.id);
      const t = setTimeout(() => setJustAdded(null), 1400);
      return () => clearTimeout(t);
    }
  }, [agents]);

  // Last 3 activity entries per agent — Workstation cycles through them
  // so each desk shows a rotating "doing now" ticker.
  const recentByAgent = {};
  feed.forEach((e) => {
    if (!recentByAgent[e.agent]) recentByAgent[e.agent] = [];
    if (recentByAgent[e.agent].length < 3) recentByAgent[e.agent].push(e);
  });

  // ---- Empty-state onboarding ----
  // Zero agents = brand-new workspace. Show a welcome panel and quick-start
  // template chips that drop the user into the architect with a head start.
  if (agents.length === 0) {
    const QUICK_STARTS = [
      { id: "wa-help", icon: "💬", title: "WhatsApp helper", desc: "Answer customers, send you the leads." },
      { id: "monday",  icon: "📊", title: "Monday morning analyst", desc: "Read the books, write the summary." },
      { id: "lead",    icon: "✦",  title: "Lead grabber", desc: "Capture every form fill, follow up politely." },
    ];
    return (
      <div className="ag-page">
        <div className="of-empty-page">
          <div className="of-empty-mark-big"><span>◍</span></div>
          <h2 className="of-empty-h">Welcome to {officeName}.</h2>
          <p className="of-empty-p">Your office is empty. Hire your first agent and they'll be at their desk in seconds.</p>
          <button className="btn btn-primary btn-cta" onClick={onNew}>
            Hire your first agent
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 7h11M8 3l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
          <div className="of-empty-or">or pick a quick-start</div>
          <div className="of-empty-quickstart">
            {QUICK_STARTS.map((q) => (
              <button key={q.id} className="of-empty-card" onClick={onNew}>
                <span className="of-empty-card-icon">{q.icon}</span>
                <span className="of-empty-card-title">{q.title}</span>
                <span className="of-empty-card-desc">{q.desc}</span>
              </button>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="ag-page">
      <div className="ag-stats">
        <Stat label="On shift"         v={`${live} / ${total}`} hint="agents live now" />
        <Stat label="Actions today"    v={`${totalRuns}`}       hint="across all agents" />
        <Stat label="Conversations"    v={`${feed.length}`}     hint="recent activity entries" />
        <Stat label="Avg rating"       v={`${avgRating} ★`}     hint="from your reviews" />
      </div>

      <div className="of-floor" style={brand.color ? { "--brand": brand.color } : null}>
        <header className="of-sign">
          <div className="of-sign-glyph" style={brand.color ? { background: `radial-gradient(circle at 30% 30%, ${brand.color}, ${brand.color}AA 60%, ${brand.color}66)` } : null}>
            {brand.logo ? <img src={brand.logo} alt="logo" /> : "◍"}
          </div>
          <div className="of-sign-body">
            {editingName ? (
              <input
                className="of-sign-input"
                value={draftName}
                autoFocus
                maxLength={40}
                onChange={(e) => setDraftName(e.target.value)}
                onBlur={saveName}
                onKeyDown={(e) => {
                  if (e.key === "Enter") saveName();
                  if (e.key === "Escape") { setDraftName(officeName); setEditingName(false); }
                }}
              />
            ) : (
              <button
                type="button"
                className="of-sign-name"
                onClick={() => { setDraftName(officeName); setEditingName(true); }}
                title="Click to rename your office"
              >
                {officeName}
                <span className="of-sign-edit" aria-hidden="true">✎</span>
              </button>
            )}
            <div className="of-sign-meta">{live} on shift · {total} {total === 1 ? "desk" : "desks"} · {totalRuns} {totalRuns === 1 ? "action" : "actions"} today</div>
          </div>
        </header>

        <div className="of-grid">
          {agents.map((a) => (
            <Workstation
              key={a.id}
              agent={a}
              office={officeName}
              recent={recentByAgent[a.id] || []}
              isNew={justAdded === a.id}
              onOpen={() => onOpen(a.id)}
              onChat={() => onChat(a.id)}
              onRate={(r) => onRate(a.id, r)}
            />
          ))}
          <button type="button" className="of-station of-station-empty" onClick={onNew}>
            <div className="of-banner">
              <span className="of-banner-co">{officeName}</span>
              <span className="of-banner-sep">·</span>
              <span className="of-banner-dept">empty desk</span>
            </div>
            <div className="of-scene of-scene-empty">
              <div className="of-empty-chair" />
              <div className="of-empty-mark"><span>+</span></div>
              <div className="of-empty-monitor" />
            </div>
            <div className="of-foot of-foot-empty">
              <div className="of-empty-name">Hire someone new</div>
            </div>
          </button>
        </div>
      </div>

      <div className="ag-runs">
        <div>
          <div className="ag-runs-k">{totalRuns.toLocaleString()}</div>
          <div className="ag-runs-l">total actions this month, across all agents</div>
        </div>
        <button className="btn btn-ghost" onClick={() => onSwitchTab && onSwitchTab("insights")}>See full report</button>
      </div>
    </div>
  );
}

function Stat({ label, v, hint, delta }) {
  return (
    <div className="stat">
      <div className="stat-l">{label}</div>
      <div className="stat-v">{v}</div>
      <div className="stat-h">
        {hint}
        {delta ? <span className="stat-d">{delta}</span> : null}
      </div>
    </div>
  );
}

// One workstation, drawn front-on like a Zoom-call thumbnail.
function Workstation({ agent, office, recent, isNew, onOpen, onChat, onRate }) {
  const a = agent;
  const firstMetricKey = Object.keys(a.metrics)[0];
  const firstMetricVal = a.metrics[firstMetricKey];

  // Rotating ticker — cycles through the agent's most recent actions.
  const [tickIdx, setTickIdx] = useState(0);
  useEffect(() => {
    if (!recent || recent.length <= 1) return;
    const id = setInterval(() => setTickIdx((i) => (i + 1) % recent.length), 4500);
    return () => clearInterval(id);
  }, [recent && recent.length]);
  // When activity changes, reset the index back to the freshest entry.
  useEffect(() => { setTickIdx(0); }, [recent && recent[0] && recent[0].id]);
  const showing = a.status === "live" && recent && recent.length > 0 ? recent[tickIdx % recent.length] : null;

  return (
    <div
      className={`of-station ${a.status === "training" ? "is-training" : ""} ${isNew ? "is-new" : ""}`}
      style={{ "--skin": a.palette.skin, "--accent": a.palette.accent, "--dark": a.palette.skinDark }}
    >
      {/* Top banner: company + agent role — looks like an office name plate */}
      <div className="of-banner">
        <span className="of-banner-co">{office}</span>
        <span className="of-banner-sep">·</span>
        <span className="of-banner-dept">{a.role}</span>
      </div>

      {/* Front-view scene */}
      <div className="of-scene">
        {/* Status pip */}
        <span className={`of-status ag-pill ag-pill-${a.status}`}>
          <span className="ag-pill-dot" />
          {a.status === "live" ? "on shift" : "training"}
        </span>

        {/* Tools as sticky notes pinned on the wall */}
        <div className="of-pinboard">
          {a.tools.slice(0, 3).map((t, i) => (
            <span key={t} className={`of-pin of-pin-${i}`} title={t}>{t[0]}</span>
          ))}
        </div>

        {/* Office chair peeking up behind the agent's head */}
        <div className="of-chairback" />

        {/* The agent — head + shoulders, front-facing */}
        <div className="of-person">
          <div
            className="of-head"
            style={{ background: `radial-gradient(circle at 30% 30%, ${a.palette.accent}, ${a.palette.skin} 60%, ${a.palette.skinDark})` }}
          >
            <_CharacterAvatar_agents palette={a.palette} glyph={a.glyph} size="md" />
          </div>
          <div className="of-shoulders" />
        </div>

        {/* Monitor in the foreground showing live work */}
        <div className="of-monitor">
          <div className="of-monitor-screen">
            <div className="of-monitor-spark">
              <Sparkline data={a.spark} label="" color={a.palette.skin} />
            </div>
            <div className="of-monitor-stat">
              <span className="of-monitor-v">{firstMetricVal}</span>
              <span className="of-monitor-l">{firstMetricKey.toLowerCase()}</span>
            </div>
          </div>
          <div className="of-monitor-stand" />
          <div className="of-monitor-base" />
        </div>

      </div>

      {/* Live ticker strip — outside the scene, sits above the footer */}
      {showing ? (
        <div className="of-ticker" key={showing.id}>
          <span className="of-ticker-dot" />
          <span className="of-ticker-time">{showing.t}</span>
          <span className="of-ticker-text">{showing.text}</span>
        </div>
      ) : a.status === "training" ? (
        <div className="of-ticker of-ticker-training">
          <span className="of-ticker-dot of-ticker-dot-train" />
          <span className="of-ticker-text">getting set up…</span>
        </div>
      ) : null}

      {/* Footer: agent name, rating, actions */}
      <div className="of-foot">
        <div className="of-foot-id">
          <div className="of-foot-name">
            {a.name}
            {a.version && <span className="of-version">v{a.version}</span>}
          </div>
          <RatingStars value={a.rating} onChange={onRate} />
        </div>
        <div className="of-foot-cta">
          <button className="of-btn of-btn-ghost" onClick={onChat} title={`Chat with ${a.name}`}>
            <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M2.5 3h11a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H6l-3 2v-2h-.5a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/></svg>
          </button>
          <button className="of-btn of-btn-primary" onClick={onOpen}>
            Open desk
            <svg width="11" height="11" viewBox="0 0 12 12"><path d="M1 6h9M7 3l3 3-3 3" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

window.AgentsTab = AgentsTab;
