import { Icon } from "@iconify/react";
import { Box, Chip, LinearProgress, Typography, useTheme } from "@mui/material";
import PropTypes from "prop-types";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import styled, { css, keyframes } from "styled-components";
import { getClientes } from "../../../api/clientes.service";
import { getProductos } from "../../../api/productos.service";
import { getSucursales } from "../../../api/sucursales.service";
import { getSesionActiva } from "../../../api/tesoreria.service";
import { ASSETS } from "../../../config/assets";
import { useMenuAcceso } from "../../../hooks/useMenuAcceso";
import { useAuthStore } from "../../../store/AuthStore";
import { useRubroStore } from "../../../store/RubroStore";
import { useAlertasEmpresaQuery } from "../../../tanstack/AlertasEmpresaStack";
import { AlertaEmpresaItem } from "../../_standards/AlertaEmpresaItem";
import { AlertasCampanaPanel } from "../../_standards/AlertasCampanaPanel";
import { getUnreadNovedades } from "../../../utils/novedadesSeen";
import { LinksArray } from "../../../utils/dataEstatica";

/** Naranja de marca Novasis, ya usado en toda la app. */
const MARCA = "#f88533";
/** Verde semántico de "operativo" (mismo que usan los chips de estado activo). */
const OPERATIVO = "#10b981";

/**
 * Atajos destacados: rutas del catálogo del menú que son el trabajo diario.
 * Se declaran por `to` y el resto (label, ícono, permisos) sale de
 * `dataEstatica.jsx`, así nunca se desincronizan del sidebar.
 */
const DESTACADOS = [
  { to: "/pos", desc: "Abrí caja y vendé" },
  { to: "/ventas", desc: "Comprobantes y SIFEN" },
  { to: "/cobranzas/recibos", desc: "Recibos y cobros" },
  { to: "/inventario", desc: "Catálogo y stock" },
];

/** Pasos de alta inicial. Solo se muestran mientras falte alguno. */
const pasosDe = ({
  tieneEmpresa,
  tieneSucursales,
  tieneProductos,
  tieneClientes,
}) => [
  {
    label: "Configurá tu empresa",
    desc: "Logo, datos fiscales y timbrado",
    path: "/configuracion",
    listo: tieneEmpresa,
  },
  {
    label: "Creá una sucursal",
    desc: "Punto de venta y cajas",
    path: "/configuracion?seccion=sucursales-cajas",
    listo: tieneSucursales,
  },
  {
    label: "Cargá productos",
    desc: "Tu catálogo de productos o servicios",
    path: "/inventario",
    listo: tieneProductos,
  },
  {
    label: "Registrá clientes",
    desc: "Los que comprán seguido",
    path: "/contactos",
    listo: tieneClientes,
  },
];

/**
 * Reloj de turno. Vive en su propio componente a propósito: si el `setInterval`
 * estuviera en el home, toda la pantalla se re-renderizaría una vez por segundo.
 */
const RelojTurno = () => {
  const [ahora, setAhora] = useState(() => new Date());

  useEffect(() => {
    const id = setInterval(() => setAhora(new Date()), 1000);
    return () => clearInterval(id);
  }, []);

  return (
    <Reloj>
      <Hora>
        {ahora.toLocaleTimeString("es-PY", {
          hour: "2-digit",
          minute: "2-digit",
          second: "2-digit",
          hour12: false,
        })}
      </Hora>
      <Fecha>
        {ahora.toLocaleDateString("es-PY", {
          weekday: "long",
          day: "numeric",
          month: "long",
        })}
      </Fecha>
    </Reloj>
  );
};

/** "hace 2 h 15 min" a partir de la apertura de la sesión. */
const transcurrido = (desde) => {
  if (!desde) return null;
  const min = Math.floor((Date.now() - new Date(desde).getTime()) / 60000);
  if (!Number.isFinite(min) || min < 0) return null;
  if (min < 60) return `hace ${min} min`;
  const h = Math.floor(min / 60);
  const resto = min % 60;
  return resto ? `hace ${h} h ${resto} min` : `hace ${h} h`;
};

/** Chips visibles por módulo antes de plegar el resto en "+N". */
const MAX_SECCIONES = 3;
/** Módulos visibles antes de "Ver todos": el inicio debe entrar sin scroll. */
const MAX_MODULOS = 8;

const saludo = () => {
  const hora = new Date().getHours();
  if (hora < 12) return "Buenos días";
  if (hora < 18) return "Buenas tardes";
  return "Buenas noches";
};

/**
 * Tarjeta de un módulo con sus secciones. Es su propio componente porque cada
 * una maneja si está expandida; con el estado en el home, abrir una tarjeta
 * re-renderizaría toda la pantalla.
 */
const TarjetaModulo = ({ grupo, onIr }) => {
  const [expandida, setExpandida] = useState(false);
  const titulo = grupo.meta?.label || grupo.items[0]?.label || "Otros";
  const icono = grupo.meta?.icon || grupo.items[0]?.icon || "lucide:box";

  // Con una sola sección el chip no aporta nada: la tarjeta entera ya navega
  // ahí. Se dibuja como tile, sin importar si el nombre de la sección coincide
  // con el del módulo ("Cobranzas → Cobros" se veía distinto a "Compras →
  // Compras" solo por ese detalle, y no hay motivo para que difieran).
  const soloCabecera = grupo.items.length === 1;
  const visibles =
    expandida || soloCabecera
      ? grupo.items
      : grupo.items.slice(0, MAX_SECCIONES);
  const ocultas = grupo.items.length - visibles.length;

  return (
    <Modulo $centrada={soloCabecera}>
      <ModuloCabecera
        type="button"
        $centrada={soloCabecera}
        onClick={() => onIr(grupo.items[0].to)}
      >
        <ModuloIcono $centrada={soloCabecera}>
          <Icon icon={icono} width={soloCabecera ? 22 : 18} />
        </ModuloIcono>
        <strong>{titulo}</strong>
      </ModuloCabecera>

      {!soloCabecera && (
        <ModuloSecciones>
          {visibles.map((it) => (
            <Seccional key={it.to} type="button" onClick={() => onIr(it.to)}>
              {it.label}
            </Seccional>
          ))}
          {ocultas > 0 && (
            <Seccional
              type="button"
              $tenue
              onClick={() => setExpandida(true)}
              aria-label={`Ver ${ocultas} secciones más de ${titulo}`}
            >
              +{ocultas}
            </Seccional>
          )}
        </ModuloSecciones>
      )}
    </Modulo>
  );
};

TarjetaModulo.propTypes = {
  grupo: PropTypes.object.isRequired,
  onIr: PropTypes.func.isRequired,
};

export const WelcomeDashboard = () => {
  const navigate = useNavigate();
  const muiTheme = useTheme();
  const { user, empresa, hasPermission } = useAuthStore();

  const { data: sucursalesData } = useQuery({
    queryKey: ["sucursales-check"],
    queryFn: () => getSucursales(),
    refetchOnWindowFocus: false,
  });
  const sucursales = sucursalesData?.data || [];
  const tieneSucursales = sucursales.length > 0;

  // Productos del rubro en el que trabaja (el backend además recorta a los
  // rubros permitidos del usuario).
  const rubroId = useRubroStore((s) => s.rubroId);

  // Bloque "Atención": alertas abiertas de la empresa para este usuario
  // (docs/plan-alertas-empresa.md en el backend). Sin alertas no se dibuja.
  const { data: alertas = [] } = useAlertasEmpresaQuery();
  const [panelAlertas, setPanelAlertas] = useState(false);
  const { data: productosData } = useQuery({
    queryKey: ["productos-check", rubroId],
    queryFn: () => getProductos(1, 1, null, false, null, null, null, null, { rubro_id: rubroId }),
    refetchOnWindowFocus: false,
  });
  const totalProductos =
    productosData?.total || productosData?.data?.length || 0;

  const { data: clientesData } = useQuery({
    queryKey: ["clientes-check"],
    queryFn: () => getClientes(1, 1),
    refetchOnWindowFocus: false,
  });
  const totalClientes = clientesData?.total || clientesData?.data?.length || 0;

  // El endpoint exige TES_CAJ_CAJA_VER; si el perfil no lo tiene ni se pide,
  // así nadie come un 403 por una tarjeta informativa.
  const puedeVerCaja = hasPermission("TESORERIA", "TES_CAJ_CAJA_VER");
  const { data: sesionCaja } = useQuery({
    queryKey: ["sesion-caja-home"],
    queryFn: () => getSesionActiva(),
    enabled: puedeVerCaja,
    refetchOnWindowFocus: true,
    staleTime: 60_000,
  });
  const cajaAbierta = !!sesionCaja?.id;

  const datosEmpresa = empresa || user?.empresa || null;
  const tieneEmpresa = !!datosEmpresa;
  const pasos = pasosDe({
    tieneEmpresa,
    tieneSucursales,
    tieneProductos: totalProductos > 0,
    tieneClientes: totalClientes > 0,
  });
  const pasosListos = pasos.filter((p) => p.listo).length;
  const configurado = pasosListos === pasos.length;
  const avance = Math.round((pasosListos / pasos.length) * 100);

  // El nombre real vive en `nombres` (el store nunca tuvo `nombre`, por eso el
  // saludo mostraba siempre "Usuario").
  const nombreUsuario =
    user?.nombres?.trim().split(" ")[0] || user?.email || "";

  // Mismo filtro que el sidebar: si el usuario lo ve en el menú, lo ve acá.
  const { puedeVer, agrupar } = useMenuAcceso();
  // Se excluye el propio inicio: no tiene sentido listarlo como módulo acá.
  const visibles = LinksArray.filter((l) => l.to !== "/" && puedeVer(l));

  const destacados = DESTACADOS.map((d) => {
    const entrada = visibles.find((v) => v.to === d.to);
    return entrada ? { ...entrada, desc: d.desc } : null;
  }).filter(Boolean);

  // El resto del sistema, agrupado por módulo como en el menú. Escala solo:
  // un perfil con acceso amplio llena la pantalla, uno acotado ve poco.
  const rutasDestacadas = new Set(destacados.map((d) => d.to));
  const grupos = agrupar(visibles.filter((v) => !rutasDestacadas.has(v.to)));

  // El inicio tiene que entrar en pantalla: se muestran los primeros módulos y
  // el resto queda detrás de "Ver todos", en vez de estirar la página.
  const [verTodosModulos, setVerTodosModulos] = useState(false);
  const modulosVisibles = verTodosModulos
    ? grupos
    : grupos.slice(0, MAX_MODULOS);
  const modulosOcultos = grupos.length - modulosVisibles.length;

  const marcaNovasis =
    muiTheme.palette.mode === "dark" ? ASSETS.logo.dark : ASSETS.logo.light;

  // El logo vive en un bucket externo: si la URL quedó rota, mostramos el
  // placeholder en vez del ícono de imagen fallida del navegador.
  const [logoFallido, setLogoFallido] = useState(false);
  const mostrarLogo = !!datosEmpresa?.logo && !logoFallido;

  return (
    <Contenedor>
      {/* ── La placa: identidad fiscal de la empresa ───────────────────────
          Es el equivalente digital de la placa de habilitación que cuelga
          detrás del mostrador. Usa el logo y el RUC reales, que es lo que
          hace que el sistema se lea como el de un negocio de verdad. */}
      <Placa>
        <PlacaCabecera>
          {mostrarLogo ? (
            <LogoEmpresa
              src={datosEmpresa.logo}
              alt={datosEmpresa?.razon_social || "Logo de la empresa"}
              loading="lazy"
              decoding="async"
              onError={() => setLogoFallido(true)}
            />
          ) : (
            <LogoPlaceholder aria-hidden="true">
              <Icon icon="lucide:building-2" width={26} />
            </LogoPlaceholder>
          )}

          <IdentidadEmpresa>
            <RazonSocial title={datosEmpresa?.razon_social || ""}>
              {datosEmpresa?.razon_social || "Tu empresa"}
            </RazonSocial>
            {datosEmpresa?.ruc && (
              <Ruc>
                RUC {datosEmpresa.ruc}
                {datosEmpresa?.dv ? `-${datosEmpresa.dv}` : ""}
              </Ruc>
            )}
          </IdentidadEmpresa>

          {configurado && (
            <EstadoOperativo>
              <Pulso aria-hidden="true" />
              Operativo
            </EstadoOperativo>
          )}
        </PlacaCabecera>

        <PlacaDatos>
          {configurado && (
            <>
              <Dato>
                <DatoLabel>Sucursales</DatoLabel>
                <DatoValor>{sucursales.length}</DatoValor>
              </Dato>
              <Dato>
                <DatoLabel>Productos</DatoLabel>
                <DatoValor>{totalProductos.toLocaleString("es-PY")}</DatoValor>
              </Dato>
              <Dato>
                <DatoLabel>Clientes</DatoLabel>
                <DatoValor>{totalClientes.toLocaleString("es-PY")}</DatoValor>
              </Dato>
            </>
          )}
          <Turno>
            {/* El chip de caja depende del permiso; el reloj no, así que
                  cualquier perfil conserva el dato vivo de la pantalla. */}
            {puedeVerCaja && (
              <EstadoCaja $abierta={cajaAbierta}>
                <Icon
                  icon={cajaAbierta ? "lucide:lock-open" : "lucide:lock"}
                  width={15}
                />
                {cajaAbierta ? (
                  <span>
                    {sesionCaja?.cajas?.descripcion || "Caja"} abierta
                    {transcurrido(sesionCaja?.fecha_apertura)
                      ? ` · ${transcurrido(sesionCaja.fecha_apertura)}`
                      : ""}
                  </span>
                ) : (
                  <span>Sin caja abierta</span>
                )}
              </EstadoCaja>
            )}
            <RelojTurno />
          </Turno>
        </PlacaDatos>
      </Placa>

      <Saludo>
        <Typography
          variant="h5"
          fontWeight={800}
          sx={{ letterSpacing: "-0.02em" }}
        >
          {saludo()}
          {nombreUsuario ? `, ${nombreUsuario}` : ""}
        </Typography>
      </Saludo>

      {/* Mientras falte configuración, el alta manda: se muestra el avance
          y los pasos que quedan. Una vez completa, desaparece por completo
          en vez de quedar como una lista de tildes verdes para siempre. */}
      {!configurado && (
        <Seccion>
          <SeccionTitulo>
            <Icon icon="lucide:rocket" width={18} color={MARCA} />
            Puesta en marcha
            <Chip
              label={`${avance}% listo`}
              size="small"
              sx={{ ml: "auto", fontWeight: 600 }}
            />
          </SeccionTitulo>

          <LinearProgress
            variant="determinate"
            value={avance}
            sx={{
              height: 6,
              borderRadius: 3,
              mb: 2.5,
              backgroundColor: `${MARCA}25`,
              "& .MuiLinearProgress-bar": {
                backgroundColor: MARCA,
                borderRadius: 3,
              },
            }}
          />

          <Pasos>
            {pasos.map((paso, i) => (
              <Paso
                key={paso.label}
                $listo={paso.listo}
                onClick={() => !paso.listo && navigate(paso.path)}
                as={paso.listo ? "div" : "button"}
                type={paso.listo ? undefined : "button"}
                disabled={paso.listo || undefined}
              >
                <PasoMarca $listo={paso.listo}>
                  {paso.listo ? <Icon icon="lucide:check" width={15} /> : i + 1}
                </PasoMarca>
                <PasoTexto>
                  <strong>{paso.label}</strong>
                  <span>{paso.desc}</span>
                </PasoTexto>
              </Paso>
            ))}
          </Pasos>
        </Seccion>
      )}

      {alertas.length > 0 && (
        <Seccion>
          <SeccionTitulo>
            <Icon icon="lucide:alert-triangle" width={18} color="#ef4444" />
            Atención
            {alertas.length > 3 && (
              <Chip
                label={`Ver todas (${alertas.length})`}
                size="small"
                onClick={() => setPanelAlertas(true)}
                sx={{ ml: "auto", fontWeight: 600, cursor: "pointer" }}
              />
            )}
          </SeccionTitulo>
          <AlertasAtencion>
            {alertas.slice(0, 3).map((a) => (
              <AlertaEmpresaItem key={a.id} alerta={a} compacto />
            ))}
          </AlertasAtencion>
          <AlertasCampanaPanel
            open={panelAlertas}
            onClose={() => setPanelAlertas(false)}
            alertas={alertas}
            novedadesSinLeer={getUnreadNovedades()}
          />
        </Seccion>
      )}

      {destacados.length > 0 && (
        <Seccion>
          <SeccionTitulo>
            <Icon icon="lucide:zap" width={18} />
            Tu trabajo
          </SeccionTitulo>

          <Accesos>
            {destacados.map((a, i) => (
              <Acceso
                key={a.to}
                type="button"
                onClick={() => navigate(a.to)}
                $destacado={i === 0}
              >
                <AccesoIcono $destacado={i === 0}>
                  <Icon icon={a.icon} width={20} />
                </AccesoIcono>
                <AccesoTexto>
                  <strong>{a.label}</strong>
                  <span>{a.desc}</span>
                </AccesoTexto>
                <Icon icon="lucide:arrow-right" width={16} className="flecha" />
              </Acceso>
            ))}
          </Accesos>
        </Seccion>
      )}

      {/* El mapa del sistema. Cada tarjeta es un módulo con las secciones que
          este perfil puede abrir; clic en una sección entra directo. */}
      {grupos.length > 0 && (
        <Seccion>
          <SeccionTitulo>
            <Icon icon="lucide:layout-grid" width={18} />
            Módulos
            {(modulosOcultos > 0 || verTodosModulos) && (
              <VerTodos
                type="button"
                onClick={() => setVerTodosModulos((v) => !v)}
              >
                {verTodosModulos ? "Ver menos" : `Ver todos (${grupos.length})`}
              </VerTodos>
            )}
          </SeccionTitulo>

          <Modulos>
            {modulosVisibles.map((g) => (
              <TarjetaModulo key={g.codigo} grupo={g} onIr={navigate} />
            ))}
          </Modulos>
        </Seccion>
      )}

      {destacados.length === 0 && grupos.length === 0 && (
        <Seccion>
          <SinAccesos>
            <Icon icon="lucide:lock" width={20} />
            <Box>
              <Typography variant="subtitle2" fontWeight={600}>
                Todavía no tenés módulos habilitados
              </Typography>
              <Typography variant="caption" color="text.secondary">
                Pedile a un administrador que te asigne un perfil con permisos.
              </Typography>
            </Box>
          </SinAccesos>
        </Seccion>
      )}

      {/* El piso de la pantalla. Antes el contenido cortaba a media altura y
          dejaba un vacío enorme; acá la marca cierra la página y de paso el
          logo aparece a un tamaño legible, no apretado en una esquina. */}
      <Piso>
        <PisoMarca>
          <img src={marcaNovasis} alt="Novasis" loading="lazy" />
          <span>Sistema de gestión y facturación electrónica</span>
        </PisoMarca>
      </Piso>
    </Contenedor>
  );
};

/* ── Estilos ───────────────────────────────────────────────────────────── */

const Contenedor = styled.div`
  display: flex;
  flex-direction: column;
  /* Alto disponible bajo la cabecera de la app: suficiente para que el piso
     quede abajo, sin forzar scroll cuando el contenido es corto. */
  min-height: calc(100vh - 230px);
  padding: 18px 24px 6px;
  max-width: 1180px;
  margin: 0 auto;

  @media (max-width: 600px) {
    padding: 16px;
    min-height: 0;
  }
`;

/* La placa lleva un canto de marca a la izquierda: es el único lugar donde el
   naranja aparece como masa de color, para que el resto quede tranquilo. */
const Placa = styled.section`
  position: relative;
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.borderColor};
  border-left: 3px solid ${MARCA};
  border-radius: 10px;
  padding: 16px 22px;
  margin-bottom: 18px;
  overflow: hidden;

  @media (max-width: 600px) {
    padding: 18px 16px;
  }
`;

const PlacaCabecera = styled.div`
  display: flex;
  align-items: center;
  gap: 18px;

  @media (max-width: 600px) {
    gap: 14px;
    flex-wrap: wrap;
  }
`;

const LogoEmpresa = styled.img`
  width: 58px;
  height: 58px;
  object-fit: contain;
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.borderColor};
  padding: 6px;
  flex-shrink: 0;
`;

const LogoPlaceholder = styled.div`
  width: 58px;
  height: 58px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  background: ${({ theme }) => theme.bg3};
  border: 1px dashed ${({ theme }) => theme.borderColor};
  color: ${({ theme }) => theme.textSecondary};
  flex-shrink: 0;
`;

const IdentidadEmpresa = styled.div`
  min-width: 0;
  flex: 1;
`;

const RazonSocial = styled.h1`
  margin: 0;
  font-size: clamp(1.15rem, 2.4vw, 1.6rem);
  font-weight: 800;
  line-height: 1.15;
  letter-spacing: -0.02em;
  color: ${({ theme }) => theme.text};
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

  /* En pantallas chicas hay lugar de sobra a lo alto: cortar la razón social a
     "MOVIMIEN..." es peor que dejarla envolver en dos líneas. */
  @media (max-width: 600px) {
    white-space: normal;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
`;

/* Monoespaciada a propósito: el RUC es un identificador fiscal que se lee
   dígito por dígito, no una frase. */
const Ruc = styled.div`
  margin-top: 5px;
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  font-size: 0.82rem;
  letter-spacing: 0.08em;
  color: ${({ theme }) => theme.textSecondary};
`;

const EstadoOperativo = styled.div`
  display: inline-flex;
  align-items: center;
  gap: 7px;
  margin-left: auto;
  padding: 6px 12px;
  border-radius: 999px;
  border: 1px solid ${OPERATIVO}55;
  background: ${OPERATIVO}12;
  color: ${OPERATIVO};
  font-size: 0.72rem;
  font-weight: 700;
  letter-spacing: 0.1em;
  text-transform: uppercase;
  white-space: nowrap;

  /* En móvil el badge baja a su propia línea: si comparte fila con el nombre,
     le come el ancho y la razón social termina cortada en dos elipsis. */
  @media (max-width: 600px) {
    order: 3;
    flex-basis: 100%;
    margin-left: 0;
    justify-content: center;
  }
`;

const latido = keyframes`
  0%, 100% { opacity: 1; transform: scale(1); }
  50%      { opacity: 0.45; transform: scale(0.82); }
`;

const Pulso = styled.span`
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: ${OPERATIVO};
  animation: ${latido} 2.4s ease-in-out infinite;

  @media (prefers-reduced-motion: reduce) {
    animation: none;
  }
`;

const PlacaDatos = styled.div`
  display: flex;
  align-items: flex-end;
  gap: 30px;
  margin-top: 15px;
  padding-top: 13px;
  border-top: 1px solid ${({ theme }) => theme.borderColor};

  @media (max-width: 600px) {
    gap: 20px;
    flex-wrap: wrap;
  }
`;

const Dato = styled.div`
  display: flex;
  flex-direction: column;
  gap: 3px;
`;

const DatoLabel = styled.span`
  font-size: 0.63rem;
  font-weight: 700;
  letter-spacing: 0.14em;
  text-transform: uppercase;
  color: ${({ theme }) => theme.textSecondary};
`;

const DatoValor = styled.span`
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  font-size: 1.05rem;
  font-weight: 600;
  color: ${({ theme }) => theme.text};
`;

const Turno = styled.div`
  display: flex;
  align-items: center;
  gap: 18px;
  margin-left: auto;

  @media (max-width: 900px) {
    margin-left: 0;
    width: 100%;
    justify-content: space-between;
  }

  @media (max-width: 600px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
`;

const EstadoCaja = styled.div`
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 7px 13px;
  border-radius: 8px;
  font-size: 0.78rem;
  font-weight: 600;
  border: 1px solid
    ${({ theme, $abierta }) => ($abierta ? `${OPERATIVO}45` : theme.borderColor)};
  background: ${({ theme, $abierta }) =>
    $abierta ? `${OPERATIVO}12` : theme.bg3};
  color: ${({ theme, $abierta }) =>
    $abierta ? OPERATIVO : theme.textSecondary};
`;

const Reloj = styled.div`
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  line-height: 1.1;

  @media (max-width: 600px) {
    align-items: flex-start;
  }
`;

/* Cifras tabulares: sin esto los dígitos bailan de ancho a cada segundo. */
const Hora = styled.span`
  font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
  font-variant-numeric: tabular-nums;
  font-size: 1.35rem;
  font-weight: 600;
  letter-spacing: 0.02em;
  color: ${({ theme }) => theme.text};
`;

const Fecha = styled.span`
  margin-top: 3px;
  font-size: 0.68rem;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  color: ${({ theme }) => theme.textSecondary};
`;

const Piso = styled.footer`
  margin-top: auto;
  padding-top: 4px;
  display: flex;
  justify-content: center;
`;

const PisoMarca = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 7px;
  padding: 10px 32px 0;
  border-top: 1px solid ${({ theme }) => theme.borderColor};
  width: 100%;
  position: relative;

  /* Acento de marca sobre la línea divisoria: convierte el pie en una firma
     y no en un simple separador. */
  &::before {
    content: "";
    position: absolute;
    top: -1px;
    left: 50%;
    transform: translateX(-50%);
    width: 88px;
    height: 2px;
    border-radius: 2px;
    background: ${MARCA};
  }

  img {
    height: 66px;
    width: auto;
    max-width: 100%;
    object-fit: contain;
  }

  span {
    font-size: 0.72rem;
    font-weight: 600;
    letter-spacing: 0.16em;
    text-transform: uppercase;
    color: ${({ theme }) => theme.textSecondary};
    text-align: center;
  }
`;

const Saludo = styled.div`
  margin-bottom: 14px;
`;

const Seccion = styled.section`
  margin-bottom: 16px;
`;

// Por ancho del contenedor: una columna en angosto, varias si entra.
const AlertasAtencion = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(100%, 340px), 1fr));
  gap: 10px;
  align-items: start;
`;

const SeccionTitulo = styled.h2`
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 11px;
  font-size: 0.78rem;
  font-weight: 700;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: ${({ theme }) => theme.textSecondary};
`;

const Pasos = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 12px;
`;

const Paso = styled.button`
  display: flex;
  align-items: center;
  gap: 13px;
  width: 100%;
  text-align: left;
  font: inherit;
  padding: 14px 16px;
  border-radius: 10px;
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.borderColor};
  transition: border-color 0.15s, transform 0.15s;

  ${({ $listo }) =>
    !$listo &&
    css`
      cursor: pointer;

      &:hover {
        border-color: ${MARCA}80;
        transform: translateY(-1px);
      }
    `}

  &:focus-visible {
    outline: 2px solid ${MARCA};
    outline-offset: 2px;
  }

  @media (prefers-reduced-motion: reduce) {
    transition: none;
    &:hover {
      transform: none;
    }
  }
`;

const PasoMarca = styled.span`
  width: 26px;
  height: 26px;
  flex-shrink: 0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.78rem;
  font-weight: 700;
  color: #fff;
  background: ${({ $listo }) => ($listo ? OPERATIVO : MARCA)};
`;

const PasoTexto = styled.div`
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;

  strong {
    font-size: 0.86rem;
    font-weight: 600;
    color: ${({ theme }) => theme.text};
  }

  span {
    font-size: 0.75rem;
    color: ${({ theme }) => theme.textSecondary};
  }
`;

const Accesos = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(258px, 1fr));
  gap: 10px;
`;

/* Sin la paleta de un color por tarjeta: uniformes y tranquilas, con el naranja
   reservado al acceso principal. Es lo que hace que se lea como herramienta de
   trabajo y no como una app de consumo. */
const Acceso = styled.button`
  display: flex;
  align-items: center;
  gap: 13px;
  width: 100%;
  text-align: left;
  font: inherit;
  cursor: pointer;
  padding: 12px 15px;
  border-radius: 10px;
  background: ${({ theme }) => theme.bg2};
  border: 1px solid
    ${({ theme, $destacado }) => ($destacado ? `${MARCA}70` : theme.borderColor)};
  transition: border-color 0.15s, transform 0.15s;

  .flecha {
    margin-left: auto;
    flex-shrink: 0;
    color: ${({ theme }) => theme.textSecondary};
    opacity: 0;
    transition: opacity 0.15s;
  }

  &:hover {
    border-color: ${MARCA};
    transform: translateY(-1px);

    .flecha {
      opacity: 1;
    }
  }

  &:focus-visible {
    outline: 2px solid ${MARCA};
    outline-offset: 2px;

    .flecha {
      opacity: 1;
    }
  }

  @media (prefers-reduced-motion: reduce) {
    transition: none;
    &:hover {
      transform: none;
    }
  }
`;

const AccesoIcono = styled.span`
  width: 38px;
  height: 38px;
  flex-shrink: 0;
  border-radius: 9px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: ${({ theme, $destacado }) =>
    $destacado ? `${MARCA}18` : theme.bg3};
  color: ${({ theme, $destacado }) => ($destacado ? MARCA : theme.textSecondary)};
  border: 1px solid
    ${({ theme, $destacado }) => ($destacado ? `${MARCA}35` : theme.borderColor)};
`;

const AccesoTexto = styled.span`
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;

  strong {
    font-size: 0.88rem;
    font-weight: 600;
    color: ${({ theme }) => theme.text};
  }

  span {
    font-size: 0.75rem;
    color: ${({ theme }) => theme.textSecondary};
  }
`;

const VerTodos = styled.button`
  margin-left: auto;
  font: inherit;
  font-size: 0.7rem;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: none;
  cursor: pointer;
  padding: 4px 10px;
  border-radius: 6px;
  color: ${MARCA};
  background: ${MARCA}12;
  border: 1px solid ${MARCA}40;

  &:hover {
    background: ${MARCA}22;
  }

  &:focus-visible {
    outline: 2px solid ${MARCA};
    outline-offset: 2px;
  }
`;

/* `grid-auto-rows: 1fr` + stretch: todas las tarjetas quedan exactamente de la
   misma altura. Funciona porque el tope de chips evita que una descuelle. */
const Modulos = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  grid-auto-rows: 1fr;
  align-items: stretch;
  gap: 10px;
`;

const Modulo = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: ${({ $centrada }) => ($centrada ? "center" : "flex-start")};
  gap: 9px;
  padding: 12px 14px;
  border-radius: 10px;
  background: ${({ theme }) => theme.bg2};
  border: 1px solid ${({ theme }) => theme.borderColor};
  transition: border-color 0.15s;

  &:hover {
    border-color: ${MARCA}55;
  }
`;

const ModuloCabecera = styled.button`
  display: flex;
  align-items: center;
  gap: 10px;
  font: inherit;
  text-align: left;
  cursor: pointer;
  background: none;
  border: none;
  padding: 0;

  ${({ $centrada }) =>
    $centrada &&
    css`
      flex: 1;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      gap: 12px;
    `}

  strong {
    font-size: 0.86rem;
    font-weight: 700;
    color: ${({ theme }) => theme.text};
  }

  &:focus-visible {
    outline: 2px solid ${MARCA};
    outline-offset: 3px;
    border-radius: 4px;
  }
`;

const ModuloIcono = styled.span`
  width: ${({ $centrada }) => ($centrada ? "38px" : "28px")};
  height: ${({ $centrada }) => ($centrada ? "38px" : "28px")};
  flex-shrink: 0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: ${({ theme }) => theme.bg3};
  border: 1px solid ${({ theme }) => theme.borderColor};
  color: ${({ theme }) => theme.textSecondary};
`;

const ModuloSecciones = styled.div`
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
`;

/* Las secciones son texto clickeable, no botones pesados: son muchas por
   módulo y con relleno sólido la tarjeta se volvería un bloque de color. */
const Seccional = styled.button`
  font: inherit;
  font-size: 0.74rem;
  cursor: pointer;
  padding: 4px 9px;
  border-radius: 6px;
  color: ${({ theme }) => theme.textSecondary};
  background: ${({ theme }) => theme.bg3};
  border: 1px solid transparent;
  transition: color 0.15s, border-color 0.15s;

  ${({ $tenue }) =>
    $tenue &&
    css`
      font-weight: 700;
      opacity: 0.75;
    `}

  &:hover {
    color: ${({ theme }) => theme.text};
    border-color: ${MARCA}55;
  }

  &:focus-visible {
    outline: 2px solid ${MARCA};
    outline-offset: 2px;
  }
`;

const SinAccesos = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px 20px;
  border-radius: 10px;
  background: ${({ theme }) => theme.bg2};
  border: 1px dashed ${({ theme }) => theme.borderColor};
  color: ${({ theme }) => theme.textSecondary};
`;

export default WelcomeDashboard;
