/* global React, ChIcon, NavIcon, CHANNELS, PHASES, LIFECYCLE_TICKETS */

const { useState: useStateLC, useMemo: useMemoLC, useRef: useRefLC, useEffect: useEffectLC } = React;

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

// Subtle phase tint — just a top stripe color, card body stays white
const PHASE_TINT = {
  recepcion:   "#B0B5BE",
  validacion:  "#9C8FB8",
  diagnostico: "#C397B0",
  accion:      "#B8A857",
  escalado:    "#C81E37",
  resuelto:    "#0E8F5C",
};

const OWNERS = [
  { id:"all",          label:"Todos",        ini:"·"  },
  { id:"sofia",        label:"SOF.IA",       ini:"S"  },
  { id:"dispatch",     label:"Dispatcher",   ini:"DP" },
  { id:"taller",       label:"Taller",       ini:"TL" },
  { id:"conectividad", label:"Conectividad", ini:"CX" },
];

const PHASE_TONE_CLS = {
  recepcion:   "tone-cream",
  validacion:  "tone-lavender",
  diagnostico: "tone-pink",
  accion:      "tone-yellow-soft",
  escalado:    "tone-yellow",
  resuelto:    "tone-white",
};

const KanCard = ({ t, onOpen }) => {
  const toneCls = PHASE_TONE_CLS[t.phase] || "tone-white";
  const isSofia = t.owner === "sofia" && t.phase !== "escalado";
  return (
    <div
      className={`kan-card-mini ${toneCls} ${t.urgent ? "urgent" : ""}`}
      onClick={() => onOpen(t)}
    >
      <div className="kc-top">
        <div className="kc-id">#{t.id}</div>
        <ChIcon channel={t.channel} size="sm"/>
      </div>
      <div className="kc-cust">{t.customer}</div>
      <div className="kc-company">{t.company}</div>
      <div className="kc-printer">{t.printer}</div>
      {t.urgent && <span className="kc-urgent">Urgente</span>}
      <div className="kc-foot">
        <div className="kc-handler">
          <div className={`handler-avatar ${isSofia ? "sofia" : ""}`} style={{width:22,height:22,fontSize:9}}>
            {isSofia ? "S" : (t.handler === "Dispatcher" ? "DP" : t.handler === "Taller" ? "TL" : t.handler === "Conectividad" ? "CX" : "OP")}
          </div>
          <span>{t.handler}</span>
        </div>
        <span className={`sla-chip ${t.slaPct >= 75 ? "danger" : t.slaPct >= 50 ? "warn" : "ok"}`}>
          {t.slaPct === 100 ? "OK" : `${t.slaPct}%`}
        </span>
      </div>
    </div>
  );
};

const LifecycleScreen = ({ openTicket, setRoute }) => {
  const [view, setView] = useStateLC("kanban");
  const [search, setSearch] = useStateLC("");
  const [filterOwner, setFilterOwner] = useStateLC("all");
  const [filterChannel, setFilterChannel] = useStateLC("all");
  const [filterUrgent, setFilterUrgent] = useStateLC(false);
  const [sortBy, setSortBy] = useStateLC("phase");
  const [sortOpen, setSortOpen] = useStateLC(false);
  const sortRefLC = useRefLC(null);

  useEffectLC(() => {
    if (!sortOpen) return;
    const handler = (e) => {
      if (sortRefLC.current && !sortRefLC.current.contains(e.target)) setSortOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [sortOpen]);

  const SORT_OPTIONS_LC = [
    { id: "phase",   label: "Por fase" },
    { id: "recent",  label: "Más recientes" },
    { id: "sla",     label: "SLA crítico" },
    { id: "channel", label: "Por canal" },
  ];

  const filtered = useMemoLC(() => {
    let r = LIFECYCLE_TICKETS;
    if (filterOwner !== "all") r = r.filter(t => t.owner === filterOwner);
    if (filterChannel !== "all") r = r.filter(t => t.channel === filterChannel);
    if (filterUrgent) r = r.filter(t => t.urgent);
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      r = r.filter(t =>
        (t.customer + " " + t.company + " " + t.id + " " + t.printer + " " + t.handler).toLowerCase().includes(q)
      );
    }
    if (sortBy === "recent") {
      r = [...r].sort((a, b) => (a.age || "").localeCompare(b.age || ""));
    } else if (sortBy === "sla") {
      r = [...r].sort((a, b) => (b.slaPct || 0) - (a.slaPct || 0));
    } else if (sortBy === "channel") {
      r = [...r].sort((a, b) => a.channel.localeCompare(b.channel));
    }
    return r;
  }, [filterOwner, filterChannel, filterUrgent, search, sortBy]);

  const byPhase = useMemoLC(() => {
    const g = {};
    PHASES.forEach(p => { g[p.id] = []; });
    filtered.forEach(t => { if (g[t.phase]) g[t.phase].push(t); });
    return g;
  }, [filtered]);

  const totals = useMemoLC(() => {
    const t = LIFECYCLE_TICKETS;
    const sofia = t.filter(x => x.owner === "sofia" && x.phase !== "escalado" && x.phase !== "resuelto").length;
    const escalado = t.filter(x => x.phase === "escalado").length;
    const resueltos = t.filter(x => x.phase === "resuelto").length;
    const active = t.length - resueltos;
    return {
      total: t.length, active,
      sofia, sofiaPct: Math.round(sofia / active * 100),
      escalado, escaladoPct: Math.round(escalado / active * 100),
      resueltos,
    };
  }, []);

  const channelCounts = useMemoLC(() => {
    const c = {};
    CHANNELS.forEach(ch => { c[ch.id] = LIFECYCLE_TICKETS.filter(t => t.channel === ch.id).length; });
    return c;
  }, []);

  const ownerCounts = useMemoLC(() => ({
    all: LIFECYCLE_TICKETS.length,
    sofia: LIFECYCLE_TICKETS.filter(t => t.owner === "sofia").length,
    dispatch: LIFECYCLE_TICKETS.filter(t => t.owner === "dispatch").length,
    taller: LIFECYCLE_TICKETS.filter(t => t.owner === "taller").length,
    conectividad: LIFECYCLE_TICKETS.filter(t => t.owner === "conectividad").length,
  }), []);

  return (
    <div className="page" data-screen-label="06 Tablero por fases">
      <div className="page-head-v2">
        <div className="ttl-block">
          <p className="eyebrow">Ciclo de vida · {filtered.length} de {LIFECYCLE_TICKETS.length} tickets</p>
          <h1>Todos los Tickets</h1>
        </div>
        <div className="kpis-inline">
          <div className="kpi-inline">
            <span className="l">Total</span>
            <span className="v">{totals.total}</span>
          </div>
          <div className="kpi-inline">
            <span className="l">SOF.IA</span>
            <span className="v">{totals.sofiaPct}<span className="u">%</span></span>
          </div>
          <div className="kpi-inline">
            <span className="l">Escalados</span>
            <span className="v">{totals.escalado}</span>
          </div>
          <div className="kpi-inline">
            <span className="l">Resueltos</span>
            <span className="v">{totals.resueltos}</span>
          </div>
        </div>
      </div>

      {/* Pill tabs — cross-nav only */}
      <div className="pill-tabs">
        <span className="pill-tab" onClick={() => setRoute && setRoute("queue")}>
          Activos
          <span className="ct">{totals.active}</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 on">
          Todos los tickets
          <span className="ct">{totals.total}</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, equipo, área…"
          />
          {search && (
            <button className="q-search-clear" onClick={() => setSearch("")} title="Limpiar">×</button>
          )}
        </div>

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

        <div className="q-sort" ref={sortRefLC}>
          <button className="q-sort-btn" onClick={() => setSortOpen(o => !o)}>
            <NavIcon name="bookmark"/>
            <span>{SORT_OPTIONS_LC.find(o => o.id === sortBy).label}</span>
            <span style={{fontSize:9,opacity:0.6}}>▾</span>
          </button>
          {sortOpen && (
            <div className="q-sort-menu">
              {SORT_OPTIONS_LC.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 ${filterUrgent ? "on" : ""}`}
          title="Solo urgentes"
          onClick={() => setFilterUrgent(v => !v)}
          style={filterUrgent ? {background:"#161A22",color:"#FFFFFF",borderColor:"#161A22"} : {}}
        ><NavIcon name="alert"/></button>
        <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>

      {/* Inline filter bar — owner + channels in one quiet row */}
      <div className="filter-row">
        <div className="filter-group">
          <span className="filter-label">Manejado por</span>
          <div className="filter-pills">
            {OWNERS.map(o => (
              <span
                key={o.id}
                className={`filter-pill ${filterOwner === o.id ? "on" : ""}`}
                onClick={() => setFilterOwner(o.id)}
              >
                {o.label}
                <span className="cn">{ownerCounts[o.id]}</span>
              </span>
            ))}
          </div>
        </div>
        <div className="filter-group">
          <span className="filter-label">Canal</span>
          <div className="filter-pills">
            <span
              className={`filter-pill ${filterChannel === "all" ? "on" : ""}`}
              onClick={() => setFilterChannel("all")}
            >
              Todos
              <span className="cn">{LIFECYCLE_TICKETS.length}</span>
            </span>
            {CHANNELS.map(ch => (
              <span
                key={ch.id}
                className={`filter-pill ${filterChannel === ch.id ? "on" : ""}`}
                onClick={() => setFilterChannel(filterChannel === ch.id ? "all" : ch.id)}
              >
                <ChIcon channel={ch.id} size="sm"/>
                {ch.label}
                <span className="cn">{channelCounts[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>
      )}

      {/* KANBAN */}
      {view === "kanban" && filtered.length > 0 && (
        <div className="kanban-clean">
          {PHASES.map(p => (
            <div key={p.id} className="kan-col-clean">
              <div className="kan-head-clean">
                <span className="ph-dot" style={{background: PHASE_TINT[p.id] || p.color}}/>
                <span className="ph-name">{p.label}</span>
                <span className="ph-count">{byPhase[p.id].length}</span>
              </div>
              {byPhase[p.id].length === 0 ? (
                <div className="kan-empty-clean">vacío</div>
              ) : byPhase[p.id].map(t => (
                <KanCard key={t.id} t={t} onOpen={openTicket}/>
              ))}
            </div>
          ))}
        </div>
      )}

      {/* TABLE */}
      {view === "tabla" && filtered.length > 0 && (
        <div className="queue">
          <div className="q-head" style={{gridTemplateColumns:"32px 84px 1.2fr 1fr 130px 0.9fr 90px 32px"}}>
            <span></span>
            <span>Ticket</span>
            <span>Cliente</span>
            <span>Equipo</span>
            <span>Fase</span>
            <span>Manejado por</span>
            <span style={{textAlign:"right"}}>SLA</span>
            <span></span>
          </div>
          {filtered.map(t => {
            const tint = PHASE_TINT[t.phase] || "#B0B5BE";
            return (
              <div
                key={t.id}
                className={`q-row ${t.urgent ? "urgent" : ""}`}
                style={{gridTemplateColumns:"32px 84px 1.2fr 1fr 130px 0.9fr 90px 32px"}}
                onClick={() => openTicket(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}</div>
                <div>
                  <span className="phase-pill-quiet">
                    <span className="d" style={{background: tint}}/>
                    {t.sub}
                  </span>
                </div>
                <div className="handler">
                  {t.owner === "sofia" ? (
                    <><div className="handler-avatar sofia">S</div><span>SOF.IA</span></>
                  ) : (
                    <><div className="handler-avatar">OP</div><span>{t.handler}</span></>
                  )}
                </div>
                <div style={{textAlign:"right"}}>
                  <span className={`sla-chip ${t.slaPct >= 75 ? "danger" : t.slaPct >= 50 ? "warn" : "ok"}`}>{t.slaPct === 100 ? "OK" : `${t.slaPct}%`}</span>
                </div>
                <div className="arr"><NavIcon name="arrow"/></div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

window.LifecycleScreen = LifecycleScreen;
