/* global React, ReactDOM, ChIcon, NavIcon, CHANNELS, TICKETS, QueueScreen, CaseScreen, EscalationScreen, KbScreen, McpScreen, LifecycleScreen, PendingScreen, ResolvedScreen, FlowScreen */

const { useState, useEffect } = React;

const Sidebar = ({ route, setRoute, filterChannel, setFilterChannel }) => {
  const counts = {};
  CHANNELS.forEach(ch => { counts[ch.id] = TICKETS.filter(t => t.channel === ch.id).length; });

  const goQueueWithFilter = (chId) => {
    setFilterChannel(chId);
    setRoute("queue");
  };

  return (
    <aside className="sidebar">
      <div className="sb-group-label">Bandeja</div>
      <div className={`sb-item ${route === "queue" && !filterChannel ? "active" : ""}`} onClick={() => { setFilterChannel(null); setRoute("queue"); }}>
        <NavIcon name="inbox"/>
        <span className="lbl">Tickets activos</span>
        <span className="badge">12</span>
      </div>
      <div className={`sb-item ${route === "lifecycle" ? "active" : ""}`} onClick={() => setRoute("lifecycle")}>
        <NavIcon name="routes"/>
        <span className="lbl">Todos los tickets</span>
        <span className="badge dim">128</span>
      </div>
      <div className={`sb-item ${route === "pending" ? "active" : ""}`} onClick={() => setRoute("pending")}>
        <NavIcon name="pending"/>
        <span className="lbl">Pendientes</span>
        <span className="badge urgent">14</span>
      </div>
      <div className={`sb-item ${route === "resolved" ? "active" : ""}`} onClick={() => setRoute("resolved")}>
        <NavIcon name="resolved"/>
        <span className="lbl">Resueltos hoy</span>
        <span className="badge dim">47</span>
      </div>

      <div className="sb-group-label">Canales</div>
      {CHANNELS.map(ch => (
        <div
          key={ch.id}
          className={`sb-item ${filterChannel === ch.id ? "active" : ""}`}
          onClick={() => goQueueWithFilter(filterChannel === ch.id ? null : ch.id)}
        >
          <ChIcon channel={ch.id} size="sm"/>
          <span className="lbl">{ch.label}</span>
          <span className="badge dim">{counts[ch.id]}</span>
        </div>
      ))}

      <div className="sb-group-label">SOF.IA</div>
      <div className={`sb-item ${route === "flow" ? "active" : ""}`} onClick={() => setRoute("flow")}>
        <NavIcon name="bolt"/>
        <span className="lbl">Centro de Control</span>
        <span className="badge" style={{background:"var(--orange-bg)",borderColor:"rgba(255,92,0,0.25)",color:"var(--orange-deep)",fontWeight:600}}>FLUJO</span>
      </div>
      <div className={`sb-item ${route === "mcp" ? "active" : ""}`} onClick={() => setRoute("mcp")}>
        <NavIcon name="bolt"/>
        <span className="lbl">Preguntar a SOF.IA</span>
        <span className="badge" style={{background:"var(--orange-bg)",borderColor:"rgba(255,92,0,0.25)",color:"var(--orange-deep)",fontWeight:600}}>MCP</span>
      </div>
      <div className={`sb-item ${route === "kb" ? "active" : ""}`} onClick={() => setRoute("kb")}>
        <NavIcon name="kb"/>
        <span className="lbl">Knowledge Base</span>
        <span className="badge dim">214</span>
      </div>
      <div className="sb-item">
        <NavIcon name="metrics"/>
        <span className="lbl">Métricas</span>
      </div>
      <div className={`sb-item ${route === "escalation" ? "active" : ""}`} onClick={() => setRoute("escalation")}>
        <NavIcon name="escal"/>
        <span className="lbl">Escalamientos</span>
        <span className="badge urgent">3</span>
      </div>

      <div className="spacer"/>

      <div className="sb-footer">
        <div className="sb-item">
          <NavIcon name="history"/>
          <span className="lbl">Historial</span>
        </div>
        <div className="sb-item">
          <NavIcon name="settings"/>
          <span className="lbl">Configuración</span>
        </div>
      </div>
    </aside>
  );
};

const TopBar = ({ setRoute }) => (
  <header className="topbar">
    <div className="brand">
      <div className="brand-mark">S</div>
      <div>
        <div className="brand-name">SOF<span className="dot">.</span>IA</div>
      </div>
      <span className="brand-sub">MCP CONSOLE · v1.4</span>
    </div>
    <div className="topbar-center">
      <div className="search" onClick={() => setRoute("mcp")} style={{cursor:"pointer"}}>
        <NavIcon name="filter"/>
        <span>Pregúntale a SOF.IA o busca ticket, cliente, serie, NIT…</span>
        <kbd>⌘K</kbd>
      </div>
    </div>
    <div className="topbar-right">
      <span className="status-pill"><span className="pulse"/> ONLINE · 4 CANALES</span>
      <button className="btn ghost sm"><NavIcon name="bolt"/></button>
      <div className="user-chip">
        <div className="avatar">AC</div>
        <div className="meta">
          <b>Alejandra Carrillo</b>
          <span>DISPATCHER · CANELLA</span>
        </div>
      </div>
    </div>
  </header>
);

const App = () => {
  const [route, setRoute] = useState("queue");
  const [filterChannel, setFilterChannel] = useState(null);
  const [activeTicket, setActiveTicket] = useState("CNL-2841");

  useEffect(() => {
    const hash = window.location.hash.replace("#", "");
    if (["queue","case","escalation","kb","mcp","lifecycle","pending","resolved","flow"].includes(hash)) setRoute(hash);
  }, []);
  useEffect(() => {
    window.location.hash = route;
  }, [route]);

  const openTicket = (t) => {
    setActiveTicket(t.id);
    if (t.state === "escalated" || t.phase === "escalado") {
      setRoute("escalation");
    } else {
      setRoute("case");
    }
  };

  return (
    <div className="app">
      <TopBar setRoute={setRoute}/>
      <Sidebar
        route={route}
        setRoute={setRoute}
        filterChannel={filterChannel}
        setFilterChannel={setFilterChannel}
      />
      <main className="main">
        {route === "queue" && (
          <QueueScreen
            filterChannel={filterChannel}
            setFilterChannel={setFilterChannel}
            openTicket={openTicket}
            setRoute={setRoute}
          />
        )}
        {route === "lifecycle" && (
          <LifecycleScreen openTicket={openTicket} setRoute={setRoute}/>
        )}
        {route === "case" && (
          <CaseScreen
            ticketId={activeTicket}
            goToQueue={() => setRoute("queue")}
            goToEscalation={() => setRoute("escalation")}
          />
        )}
        {route === "escalation" && (
          <EscalationScreen
            goToQueue={() => setRoute("queue")}
            goToCase={() => setRoute("case")}
          />
        )}
        {route === "kb" && <KbScreen/>}
        {route === "mcp" && <McpScreen/>}
        {route === "pending" && (
          <PendingScreen
            openTicket={openTicket}
            goToEscalation={() => setRoute("escalation")}
            setRoute={setRoute}
          />
        )}
        {route === "resolved" && (
          <ResolvedScreen openTicket={openTicket}/>
        )}
        {route === "flow" && (
          <FlowScreen setRoute={setRoute}/>
        )}
      </main>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
