/* global React, ChIcon, NavIcon, CHANNELS, TICKETS, StateBadge */

const { useMemo: useMemoQ, useState: useStateQ, useRef: useRefQ, useEffect: useEffectQ } = React;

const initials = (name) => name.split(/\s+/).filter(Boolean).slice(0,2).map(w => w[0]).join("").toUpperCase();

const phaseFromState = (t) => {
  if (t.state === "resolved") return 5;
  if (t.state === "auto" && t.handler === "sofia") return 4;
  if (t.state === "progress") return 3;
  if (t.state === "waiting") return 2;
  if (t.state === "escalated" || t.urgent) return 2;
  return 3;
};

const stateToTone = (t) => {
  if (t.urgent || t.state === "escalated") return "yellow";
  if (t.state === "progress") return "lavender";
  if (t.state === "waiting") return "pink";
  if (t.state === "auto") return "lavender";
  if (t.state === "resolved") return "white";
  return "white";
};

const stateChipLabel = (t) => {
  if (t.urgent || t.state === "escalated") return { label: "Requiere operador", cls: "urgent" };
  if (t.state === "auto") return { label: "Auto · SOF.IA", cls: "" };
  if (t.state === "progress") return { label: "En curso", cls: "" };
  if (t.state === "waiting") return { label: "Esperando cliente", cls: "" };
  if (t.state === "resolved") return { label: "Resuelto", cls: "" };
  return { label: t.state, cls: "" };
};

const TicketCard = ({ t, onOpen }) => {
  const ph = phaseFromState(t);
  const tone = stateToTone(t);
  const chip = stateChipLabel(t);
  const isSofia = t.handler === "sofia" && !(t.urgent || t.state === "escalated");
  return (
    <div className={`tk-card tone-${tone}`} onClick={() => onOpen(t)}>
      <div className="tk-top">
        <div style={{flex:1, minWidth:0}}>
          <h4 className="tk-title">{t.issue}</h4>
          <div className="tk-sub">#{t.id} · {t.company}</div>
        </div>
        <button className="tk-menu" onClick={e => e.stopPropagation()} title="Acciones">⋯</button>
      </div>

      <span className={`tk-chip ${chip.cls}`} style={{alignSelf:"flex-start"}}>
        <span className="d"/> {chip.label}
      </span>

      <div className="tk-progress">
        {[1,2,3,4,5].map(i => <i key={i} className={i <= ph ? "on" : ""}/>)}
      </div>

      <div className="tk-meta">
        <div className="handler">
          <div className={`avatar ${isSofia ? "sofia" : ""}`}>
            {isSofia ? "S" : initials(t.customer)}
          </div>
          <div style={{minWidth:0}}>
            <div className="who-name">{isSofia ? "SOF.IA" : t.customer.split(" ").slice(0,2).join(" ")}</div>
            <div className="who-date">{t.age}{t.time ? ` · ${t.time}` : ""}</div>
          </div>
        </div>
        <div className="tk-ch-icon" title={CHANNELS.find(c => c.id === t.channel)?.label}>
          <ChIcon channel={t.channel} size="sm"/>
        </div>
      </div>
    </div>
  );
};

const PlaceholderCard = () => (
  <div className="tk-card tone-stone" style={{minHeight:188, display:"grid", placeItems:"center"}}>
    <div style={{display:"flex",gap:8,opacity:0.55}}>
      <div className="icon-pill" style={{width:34,height:34,background:"#FFFFFF"}}><NavIcon name="filter"/></div>
      <div className="icon-pill" style={{width:34,height:34,background:"#FFFFFF"}}><NavIcon name="user"/></div>
      <div className="icon-pill" style={{width:34,height:34,background:"#FFFFFF"}}><NavIcon name="bolt"/></div>
    </div>
  </div>
);

// ============ List view ============
const TicketRow = ({ t, onOpen }) => {
  const chip = stateChipLabel(t);
  return (
    <div className="q-row" onClick={() => onOpen(t)}>
      <ChIcon channel={t.channel}/>
      <div className="id">#{t.id}</div>
      <div className="cust">
        <b>{t.customer}</b>
        <span>{t.company}</span>
      </div>
      <div className="printer">
        {t.printer}
        <span className="serial">SN · {t.serial}</span>
      </div>
      <div>
        <span className={`tk-chip ${chip.cls}`} style={{background: chip.cls === "urgent" ? "#161A22" : "var(--bg-3)"}}>
          <span className="d"/> {chip.label}
        </span>
      </div>
      <div className="handler">
        {t.handler === "sofia" ? (
          <><div className="handler-avatar sofia">S</div><span>SOF.IA</span></>
        ) : (
          <><div className="handler-avatar">OP</div><span style={{color:"var(--red)"}}>Dispatcher</span></>
        )}
      </div>
      <div className="time" style={{textAlign:"right"}}>{t.age}</div>
      <div className="arr"><NavIcon name="arrow"/></div>
    </div>
  );
};

const STATE_FILTERS = [
  { id: "all",        label: "Todos" },
  { id: "urgent",     label: "Urgentes" },
  { id: "progress",   label: "En curso" },
  { id: "auto",       label: "Auto · SOF.IA" },
  { id: "resolved",   label: "Resueltos" },
];

const SORT_OPTIONS = [
  { id: "recent",  label: "Más recientes" },
  { id: "urgency", label: "Urgencia" },
  { id: "channel", label: "Por canal" },
];

const QueueScreen = ({ filterChannel, setFilterChannel, openTicket, setRoute }) => {
  const [viewMode, setViewMode] = useStateQ("cards");
  const [search, setSearch] = useStateQ("");
  const [sortBy, setSortBy] = useStateQ("recent");
  const [sortOpen, setSortOpen] = useStateQ(false);
  const [stateFilter, setStateFilter] = useStateQ("all");
  const sortRef = useRefQ(null);

  // Close sort dropdown on outside click
  useEffectQ(() => {
    if (!sortOpen) return;
    const handler = (e) => {
      if (sortRef.current && !sortRef.current.contains(e.target)) setSortOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [sortOpen]);

  const filtered = useMemoQ(() => {
    let r = TICKETS;
    if (filterChannel) r = r.filter(t => t.channel === filterChannel);
    if (stateFilter !== "all") {
      if (stateFilter === "urgent")        r = r.filter(t => t.urgent || t.state === "escalated");
      else if (stateFilter === "progress") r = r.filter(t => t.state === "progress" || t.state === "waiting");
      else if (stateFilter === "auto")     r = r.filter(t => t.state === "auto" && !t.urgent);
      else if (stateFilter === "resolved") r = r.filter(t => t.state === "resolved");
    }
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      r = r.filter(t =>
        (t.customer + " " + t.company + " " + t.id + " " + t.printer + " " + t.serial + " " + t.issue).toLowerCase().includes(q)
      );
    }
    if (sortBy === "urgency") {
      const score = (t) => (t.urgent ? 3 : 0) + (t.state === "escalated" ? 2 : 0) + (t.state === "waiting" ? 1 : 0);
      r = [...r].sort((a, b) => score(b) - score(a));
    } else if (sortBy === "channel") {
      r = [...r].sort((a, b) => a.channel.localeCompare(b.channel));
    }
    return r;
  }, [filterChannel, search, sortBy, stateFilter]);

  const counts = useMemoQ(() => {
    const c = {};
    CHANNELS.forEach(ch => { c[ch.id] = TICKETS.filter(t => t.channel === ch.id).length; });
    return c;
  }, []);

  const stateCounts = useMemoQ(() => ({
    all: TICKETS.length,
    urgent: TICKETS.filter(t => t.urgent || t.state === "escalated").length,
    progress: TICKETS.filter(t => t.state === "progress" || t.state === "waiting").length,
    auto: TICKETS.filter(t => t.state === "auto" && !t.urgent).length,
    resolved: TICKETS.filter(t => t.state === "resolved").length,
  }), []);

  const totalActive = TICKETS.filter(t => t.state !== "resolved").length;

  const sections = useMemoQ(() => {
    const urgent = filtered.filter(t => t.urgent || t.state === "escalated");
    const progress = filtered.filter(t => !t.urgent && t.state !== "escalated" && (t.state === "progress" || t.state === "waiting"));
    const auto = filtered.filter(t => !t.urgent && t.state === "auto");
    const resolved = filtered.filter(t => t.state === "resolved");
    return { urgent, progress, auto, resolved };
  }, [filtered]);

  const currentSort = SORT_OPTIONS.find(o => o.id === sortBy);

  return (
    <div className="page" data-screen-label="01 Cola omnicanal">
      <div className="page-head-v2">
        <div className="ttl-block">
          <p className="eyebrow">Cola Omnicanal · {filtered.length} de {TICKETS.length} tickets</p>
          <h1>Tickets Activos</h1>
        </div>
        <div className="kpis-inline">
          <div className="kpi-inline">
            <span className="l">Resueltos sin humano</span>
            <span className="v">80<span className="u">%</span></span>
          </div>
          <div className="kpi-inline">
            <span className="l">Captura promedio</span>
            <span className="v">42<span className="u">seg</span></span>
          </div>
          <div className="kpi-inline">
            <span className="l">Escalados hoy</span>
            <span className="v">23</span>
          </div>
        </div>
      </div>

      {/* Tabs nav only */}
      <div className="pill-tabs">
        <span className="pill-tab on">
          Activos
          <span className="ct">{totalActive}</span>
        </span>
        <span className="pill-tab" onClick={() => setRoute && setRoute("pending")}>
          Pendientes
          <span className="ct urgent">14</span>
        </span>
        <span className="pill-tab" onClick={() => setRoute && setRoute("resolved")}>
          Resueltos hoy
          <span className="ct">47</span>
        </span>
        <span className="pill-tab" onClick={() => setRoute && setRoute("lifecycle")}>
          Todos los tickets
          <span className="ct">{TICKETS.length + 30}</span>
        </span>
      </div>

      {/* === TOOLBAR === */}
      <div className="q-toolbar">
        <div className="q-search">
          <NavIcon name="filter"/>
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Buscar por cliente, empresa, ticket, modelo, serie…"
          />
          {search && (
            <button className="q-search-clear" onClick={() => setSearch("")} title="Limpiar">×</button>
          )}
        </div>

        <div className="q-view">
          <span
            className={`q-view-btn ${viewMode === "cards" ? "on" : ""}`}
            onClick={() => setViewMode("cards")}
            title="Vista tablero"
          ><NavIcon name="routes"/></span>
          <span
            className={`q-view-btn ${viewMode === "list" ? "on" : ""}`}
            onClick={() => setViewMode("list")}
            title="Vista lista"
          ><NavIcon name="inbox"/></span>
        </div>

        <div className="q-sort" ref={sortRef}>
          <button className="q-sort-btn" onClick={() => setSortOpen(o => !o)}>
            <NavIcon name="bookmark"/>
            <span>{currentSort.label}</span>
            <span style={{fontSize:9,opacity:0.6}}>▾</span>
          </button>
          {sortOpen && (
            <div className="q-sort-menu">
              {SORT_OPTIONS.map(o => (
                <button
                  key={o.id}
                  className={`q-sort-item ${sortBy === o.id ? "on" : ""}`}
                  onClick={() => { setSortBy(o.id); setSortOpen(false); }}
                >
                  {o.label}
                  {sortBy === o.id && <span style={{marginLeft:"auto"}}>✓</span>}
                </button>
              ))}
            </div>
          )}
        </div>

        <button className="q-icon-btn" title="Sincronizar"><NavIcon name="rotate"/></button>
        <button className="q-icon-btn" title="Métricas" onClick={() => setRoute && setRoute("mcp")}><NavIcon name="metrics"/></button>
      </div>

      {/* === FILTER ROW === */}
      <div className="filter-row">
        <div className="filter-group">
          <span className="filter-label">Estado</span>
          <div className="filter-pills">
            {STATE_FILTERS.map(s => (
              <span
                key={s.id}
                className={`filter-pill ${stateFilter === s.id ? "on" : ""}`}
                onClick={() => setStateFilter(s.id)}
              >
                {s.label}
                <span className="cn">{stateCounts[s.id]}</span>
              </span>
            ))}
          </div>
        </div>
        <div className="filter-group">
          <span className="filter-label">Canal</span>
          <div className="filter-pills">
            <span
              className={`filter-pill ${!filterChannel ? "on" : ""}`}
              onClick={() => setFilterChannel(null)}
            >
              Todos
              <span className="cn">{TICKETS.length}</span>
            </span>
            {CHANNELS.map(ch => (
              <span
                key={ch.id}
                className={`filter-pill ${filterChannel === ch.id ? "on" : ""}`}
                onClick={() => setFilterChannel(filterChannel === ch.id ? null : ch.id)}
              >
                <ChIcon channel={ch.id} size="sm"/>
                {ch.label}
                <span className="cn">{counts[ch.id]}</span>
              </span>
            ))}
          </div>
        </div>
      </div>

      {/* Empty state */}
      {filtered.length === 0 && (
        <div style={{padding:60,textAlign:"center",color:"var(--text-3)",fontSize:13,fontFamily:"var(--mono)",letterSpacing:"0.06em",textTransform:"uppercase",border:"1px dashed var(--line-2)",borderRadius:16,background:"transparent"}}>
          — sin tickets para los filtros activos —
        </div>
      )}

      {/* === CARDS VIEW === */}
      {viewMode === "cards" && filtered.length > 0 && (
        <>
          {sections.urgent.length > 0 && (
            <div className="tk-section">
              <div className="tk-section-head">
                <span className="tk-section-title">Requieren operador</span>
                <span className="tk-section-count">{sections.urgent.length} {sections.urgent.length === 1 ? "ticket" : "tickets"} · cliente esperando</span>
                <span className="tk-section-rule yellow"/>
              </div>
              <div className="tk-grid">
                {sections.urgent.map(t => <TicketCard key={t.id} t={t} onOpen={openTicket}/>)}
              </div>
            </div>
          )}

          {sections.progress.length > 0 && (
            <div className="tk-section">
              <div className="tk-section-head">
                <span className="tk-section-title">En curso</span>
                <span className="tk-section-count">{sections.progress.length} {sections.progress.length === 1 ? "ticket" : "tickets"} · indagación o espera</span>
                <span className="tk-section-rule pink"/>
              </div>
              <div className="tk-grid">
                {sections.progress.map(t => <TicketCard key={t.id} t={t} onOpen={openTicket}/>)}
              </div>
            </div>
          )}

          {sections.auto.length > 0 && (
            <div className="tk-section">
              <div className="tk-section-head">
                <span className="tk-section-title">SOF.IA · resolviendo en automático</span>
                <span className="tk-section-count">{sections.auto.length} {sections.auto.length === 1 ? "ticket" : "tickets"} · sin intervención humana</span>
                <span className="tk-section-rule lavender"/>
              </div>
              <div className="tk-grid">
                {sections.auto.map(t => <TicketCard key={t.id} t={t} onOpen={openTicket}/>)}
                <PlaceholderCard/>
              </div>
            </div>
          )}

          {sections.resolved.length > 0 && (
            <div className="tk-section">
              <div className="tk-section-head">
                <span className="tk-section-title">Resueltos recientemente</span>
                <span className="tk-section-count">{sections.resolved.length} {sections.resolved.length === 1 ? "ticket" : "tickets"} · cerrados en las últimas horas</span>
                <span className="tk-section-rule stone"/>
              </div>
              <div className="tk-grid">
                {sections.resolved.map(t => <TicketCard key={t.id} t={t} onOpen={openTicket}/>)}
              </div>
            </div>
          )}
        </>
      )}

      {/* === LIST VIEW === */}
      {viewMode === "list" && filtered.length > 0 && (
        <div className="queue">
          <div className="q-head">
            <span></span>
            <span>Ticket</span>
            <span>Cliente</span>
            <span>Equipo</span>
            <span>Estado</span>
            <span>Manejado por</span>
            <span style={{textAlign:"right"}}>Edad</span>
            <span></span>
          </div>
          {filtered.map(t => <TicketRow key={t.id} t={t} onOpen={openTicket}/>)}
        </div>
      )}
    </div>
  );
};

window.QueueScreen = QueueScreen;
