// App shell: sidebar with expandable groups + topbar with sub-tab strip

function Sidebar({ route, onNav, collapsed, onToggle, mobileOpen, onMobileClose }) {
  const { mod: currentMod, sub: currentSub } = parseRoute(route);
  // Which groups are open; current module always forced open
  const [open, setOpen] = useState(() => {
    try {
      return JSON.parse(localStorage.getItem('optima.navopen') || '{}');
    } catch {
      return {};
    }
  });
  useEffect(() => {
    localStorage.setItem('optima.navopen', JSON.stringify(open));
  }, [open]);

  // Detectar viewport desktop (lg breakpoint de Tailwind = 1024px)
  const [isDesktop, setIsDesktop] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia('(min-width: 1024px)').matches : true,
  );
  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const handler = (e) => setIsDesktop(e.matches);
    mq.addEventListener('change', handler);
    return () => mq.removeEventListener('change', handler);
  }, []);

  // En mobile ignoramos `collapsed` — el drawer siempre se muestra expandido
  const effectiveCollapsed = isDesktop && collapsed;

  function go(modId, subId) {
    onNav(buildRoute(modId, subId || defaultSub(modId)));
  }

  return (
    <>
      {/* Backdrop solo en mobile */}
      {mobileOpen && (
        <div
          className="lg:hidden fixed inset-0 z-40 bg-slate-900/50 overlay-in"
          onClick={onMobileClose}
        />
      )}
      <aside
        className={cn(
          'flex flex-col border-r border-slate-800/60 bg-slate900 text-slate-100',
          // Mobile: drawer fixeado con slide
          'fixed inset-y-0 left-0 z-50 w-[280px] transition-transform duration-200',
          mobileOpen ? 'translate-x-0' : '-translate-x-full',
          // Desktop: vuelve al flujo normal y empuja el contenido
          'lg:static lg:translate-x-0 lg:shrink-0 lg:transition-all',
          effectiveCollapsed ? 'lg:w-16' : 'lg:w-[268px]',
        )}
      >
      {/* brand */}
      <div
        className={cn(
          'h-16 flex items-center border-b border-slate-800/60',
          effectiveCollapsed ? 'justify-center' : 'px-4 gap-3',
        )}
      >
        <div
          className="h-9 w-9 rounded-lg flex items-center justify-center shrink-0"
          style={{
            background: 'linear-gradient(135deg,#EB6B1E 0%,#C9521A 100%)',
            boxShadow: 'inset 0 -2px 0 rgba(0,0,0,.25)',
          }}
        >
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M12 2 L16 8 L12 14 L8 8 Z" fill="#fff" />
            <path d="M12 14 L12 22" stroke="#fff" strokeWidth="2" strokeLinecap="round" />
          </svg>
        </div>
        {!effectiveCollapsed && (
          <div className="min-w-0 flex-1">
            <div className="text-[13px] font-bold tracking-tight">Optima Drilling</div>
            <div className="text-[10.5px] text-slate-400 mt-0.5">Plataforma · v2.4.1</div>
          </div>
        )}
        {/* Close button visible solo en mobile */}
        <button
          onClick={onMobileClose}
          className="lg:hidden text-slate-400 hover:text-white shrink-0"
          title="Cerrar menú"
          aria-label="Cerrar menú"
        >
          <Icon name="x" size={18} />
        </button>
      </div>

      {/* Well switcher */}
      {!effectiveCollapsed && (
        <div className="px-3 py-3 border-b border-slate-800/60">
          <button className="w-full flex items-center gap-2 px-2.5 py-2 rounded-md bg-slate800 hover:bg-slate700 transition text-left">
            <div className="h-7 w-7 rounded bg-slate700 flex items-center justify-center text-[11px] font-bold">
              N-4
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[12px] font-semibold truncate">Pozo NETTO-4H</div>
              <div className="text-[10px] text-slate-400 truncate">San Juan · Rig-1</div>
            </div>
            <Icon name="chevronDown" size={12} className="text-slate-400" />
          </button>
        </div>
      )}

      {/* nav groups */}
      <nav className="flex-1 overflow-y-auto px-2 py-3">
        <div
          className={cn(
            'text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-2',
            effectiveCollapsed ? 'text-center' : 'px-2',
          )}
        >
          {effectiveCollapsed ? '·' : 'Módulos'}
        </div>
        <div className="flex flex-col gap-0.5">
          {NAV.map((m) => {
            const isActive = currentMod === m.id;
            const hasChildren = !!m.children;
            const isOpen = hasChildren && (isActive || open[m.id]);
            return (
              <div key={m.id}>
                <button
                  onClick={() => {
                    if (hasChildren) {
                      if (isActive) {
                        // toggle collapse without navigating
                        setOpen((o) => ({ ...o, [m.id]: !(o[m.id] ?? true) }));
                      } else {
                        go(m.id);
                        setOpen((o) => ({ ...o, [m.id]: true }));
                      }
                    } else {
                      go(m.id);
                    }
                  }}
                  className={cn(
                    'group w-full flex items-center gap-3 px-2.5 py-2 rounded-md transition text-left relative',
                    isActive
                      ? 'bg-slate800 text-white'
                      : 'text-slate-300 hover:bg-slate800/60 hover:text-white',
                  )}
                >
                  {isActive && (
                    <span className="absolute left-0 top-1.5 bottom-1.5 w-[3px] bg-amber rounded-r" />
                  )}
                  <Icon
                    name={m.icon}
                    size={16}
                    className={isActive ? 'text-amber' : 'text-slate-400'}
                  />
                  {!effectiveCollapsed && (
                    <>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="text-[13px] font-medium truncate">
                            {m.short || m.label}
                          </span>
                          {m.pinned && <span className="text-[9px] text-slate-500 ml-auto">★</span>}
                        </div>
                        <div className="text-[10.5px] text-slate-500 truncate">{m.subtitle}</div>
                      </div>
                      {hasChildren && (
                        <Icon
                          name="chevronDown"
                          size={12}
                          className={cn(
                            'text-slate-500 shrink-0 transition-transform',
                            isOpen && 'rotate-180',
                          )}
                        />
                      )}
                    </>
                  )}
                </button>

                {/* children */}
                {!effectiveCollapsed && hasChildren && isOpen && (
                  <div className="ml-[11px] pl-3 border-l border-slate-800/70 my-0.5 flex flex-col gap-0.5">
                    {m.children.map((c) => {
                      const isSubActive = isActive && currentSub === c.id;
                      return (
                        <button
                          key={c.id}
                          onClick={() => go(m.id, c.id)}
                          className={cn(
                            'flex items-center gap-2 px-2.5 py-1.5 rounded-md text-left transition text-[12px]',
                            isSubActive
                              ? 'bg-slate800 text-white'
                              : 'text-slate-400 hover:bg-slate800/50 hover:text-white',
                          )}
                        >
                          <Icon
                            name={c.icon}
                            size={12}
                            className={isSubActive ? 'text-amber' : 'text-slate-500'}
                          />
                          <span className="flex-1 truncate">{c.label}</span>
                          {c.sensor && (
                            <span
                              className="relative flex h-1.5 w-1.5 shrink-0"
                              title="Sensor conectado"
                            >
                              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald opacity-75" />
                              <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald" />
                            </span>
                          )}
                        </button>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {!effectiveCollapsed && (
          <div className="mt-6">
            <div className="text-[10px] font-semibold text-slate-500 uppercase tracking-wider mb-2 px-2">
              Equipos
            </div>
            <div className="px-2.5 py-2 rounded-md bg-slate800/40 border border-slate-800">
              <div className="flex items-center gap-2">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald live-dot" />
                <span className="text-[12px] font-medium">Rig-1</span>
                <span className="text-[10px] text-slate-400 ml-auto mono">NETTO</span>
              </div>
              <div className="text-[10.5px] text-slate-500 mt-1">Conectado · 1 Hz · 7 canales</div>
            </div>
          </div>
        )}
      </nav>

      {/* user */}
      <div
        className={cn(
          'border-t border-slate-800/60 p-3',
          effectiveCollapsed ? 'flex justify-center' : '',
        )}
      >
        {effectiveCollapsed ? (
          <div className="h-8 w-8 rounded-full bg-slate700 flex items-center justify-center text-[11px] font-bold">
            MR
          </div>
        ) : (
          <div className="flex items-center gap-3">
            <div className="h-8 w-8 rounded-full bg-slate700 flex items-center justify-center text-[11px] font-bold shrink-0">
              MR
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-[12px] font-semibold truncate">Martín Rojas</div>
              <div className="text-[10.5px] text-slate-400 truncate">Supervisor · Optima</div>
            </div>
            <button className="text-slate-400 hover:text-white" title="Cerrar sesión">
              <Icon name="logout" size={14} />
            </button>
          </div>
        )}
      </div>
      </aside>
    </>
  );
}

function Topbar({ route, onNav, onOpenCmd, onOpenNotif, onOpenMobileNav, notifCount }) {
  const { mod, sub } = parseRoute(route);
  const modDef = NAV.find((m) => m.id === mod);
  const [modLabel, subLabel] = routeLabels(route);

  return (
    <header className="border-b border-border bg-bg sticky top-0 z-30">
      <div className="min-h-16 px-5 sm:px-6 py-2 sm:py-0 sm:h-16 flex items-center gap-3 sm:gap-4">
        <button
          onClick={onOpenMobileNav}
          className="lg:hidden h-9 w-9 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-ink shrink-0"
          title="Abrir menú"
          aria-label="Abrir menú"
        >
          <Icon name="menu" size={16} />
        </button>
        <div className="flex-1 min-w-0">
          <div className="hidden md:flex items-center gap-2 text-[11px] text-muted">
            <span>Optima Drilling</span>
            <Icon name="chevronRight" size={10} />
            <span>Pozo NETTO-4H</span>
            <Icon name="chevronRight" size={10} />
            <span className={cn(sub ? '' : 'text-ink font-medium')}>{modLabel}</span>
            {sub && (
              <>
                <Icon name="chevronRight" size={10} />
                <span className="text-ink font-medium">{subLabel}</span>
              </>
            )}
          </div>
          <h1 className="text-[14.5px] sm:text-[15px] font-semibold tracking-tight mt-0.5 truncate">
            {sub ? subLabel : modLabel}
            <span className="hidden sm:inline text-muted font-normal ml-2 text-[12px]">
              {sub ? modLabel : modDef?.subtitle || ''}
            </span>
          </h1>
        </div>

        <button
          onClick={onOpenCmd}
          className="hidden xl:flex items-center gap-2 h-9 px-3 rounded-md border border-border bg-slate-50 text-muted hover:bg-slate-100 text-[12.5px] w-56 shrink-0"
        >
          <Icon name="search" size={14} />
          <span className="truncate">Buscar módulos, pozos…</span>
          <span className="ml-auto mono text-[10px] px-1.5 py-0.5 rounded bg-white border border-border">
            ⌘K
          </span>
        </button>
        <button
          onClick={onOpenCmd}
          className="xl:hidden h-9 w-9 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-ink shrink-0"
          title="Buscar (⌘K)"
        >
          <Icon name="search" size={15} />
        </button>

        <button
          onClick={onOpenNotif}
          className="relative h-9 w-9 rounded-md border border-border bg-white hover:bg-slate-50 flex items-center justify-center text-ink shrink-0"
        >
          <Icon name="bell" size={15} />
          {notifCount > 0 && (
            <span className="absolute -top-1 -right-1 h-4 min-w-4 px-1 rounded-full bg-red text-white text-[9px] font-bold flex items-center justify-center">
              {notifCount}
            </span>
          )}
        </button>

        <div className="hidden sm:block h-9 w-px bg-border shrink-0" />
        <div className="flex items-center gap-2 shrink-0">
          <div className="h-7 w-7 rounded-full bg-slate800 text-white flex items-center justify-center text-[10px] font-bold">
            MR
          </div>
          <div className="hidden 2xl:block">
            <div className="text-[12px] font-semibold leading-tight">Martín Rojas</div>
            <div className="text-[10.5px] text-muted leading-tight">Supervisor</div>
          </div>
        </div>
      </div>

      {/* Sub-tab strip */}
      {modDef?.children && (
        <div className="px-6 flex items-end gap-0 border-t border-border/60 bg-white overflow-x-auto">
          {modDef.children.map((c) => {
            const isActive = c.id === sub;
            return (
              <button
                key={c.id}
                onClick={() => onNav(buildRoute(mod, c.id))}
                className={cn(
                  'relative shrink-0 flex items-center gap-2 px-3.5 h-11 text-[12.5px] font-medium transition border-b-2 -mb-px',
                  isActive
                    ? 'text-ink border-amber'
                    : 'text-muted border-transparent hover:text-ink hover:bg-slate-50',
                )}
              >
                <Icon
                  name={c.icon}
                  size={13}
                  className={isActive ? 'text-amber' : 'text-slate-400'}
                />
                <span>{c.label}</span>
                {c.sensor && (
                  <span className="relative flex h-1.5 w-1.5 shrink-0">
                    <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald opacity-75" />
                    <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald" />
                  </span>
                )}
              </button>
            );
          })}
        </div>
      )}
    </header>
  );
}

// Command palette
function CommandPalette({ open, onClose, onNav }) {
  const [q, setQ] = useState('');
  const inputRef = useRef(null);
  useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50);
    else setQ('');
  }, [open]);

  // Build commands from NAV
  const cmds = [];
  NAV.forEach((m) => {
    if (!m.children) {
      cmds.push({
        id: m.id,
        route: m.id,
        label: `Ir a ${m.label}`,
        icon: m.icon,
        group: 'Navegación',
      });
    } else {
      m.children.forEach((c) => {
        cmds.push({
          id: `${m.id}/${c.id}`,
          route: `${m.id}/${c.id}`,
          label: `${m.short || m.label} · ${c.label}`,
          icon: c.icon,
          group: m.label,
        });
      });
    }
  });
  cmds.push(
    { id: 'parte-new', label: 'Nuevo reporte diario', icon: 'plus', group: 'Acciones' },
    { id: 'export-pdf', label: 'Exportar reporte PDF', icon: 'download', group: 'Acciones' },
    { id: 'send-client', label: 'Enviar reporte al cliente', icon: 'send', group: 'Acciones' },
  );
  const filtered = cmds.filter((c) => c.label.toLowerCase().includes(q.toLowerCase()));
  const groups = {};
  filtered.forEach((c) => (groups[c.group] = groups[c.group] || []).push(c));

  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[55] flex items-start justify-center pt-24 p-4">
      <div className="absolute inset-0 bg-slate-900/40 overlay-in" onClick={onClose} />
      <div className="relative w-full max-w-xl bg-white rounded-xl shadow-pop sheet-in overflow-hidden">
        <div className="flex items-center gap-3 px-4 border-b border-border h-12">
          <Icon name="search" size={16} className="text-muted" />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Buscar módulo o acción…"
            className="flex-1 h-full bg-transparent outline-none text-[13px]"
          />
          <kbd className="mono text-[10px] px-1.5 py-0.5 rounded bg-slate-100 border border-border">
            Esc
          </kbd>
        </div>
        <div className="max-h-[50vh] overflow-y-auto py-2">
          {Object.keys(groups).length === 0 ? (
            <div className="px-4 py-10 text-center text-sm text-muted">Sin resultados.</div>
          ) : (
            Object.entries(groups).map(([g, list]) => (
              <div key={g}>
                <div className="px-4 py-1.5 text-[10px] font-semibold text-muted uppercase tracking-wider">
                  {g}
                </div>
                {list.map((c) => (
                  <button
                    key={c.id}
                    onClick={() => {
                      if (c.route) {
                        onNav(c.route);
                        onClose();
                      } else {
                        onClose();
                      }
                    }}
                    className="w-full flex items-center gap-3 px-4 py-2 hover:bg-slate-50 text-left"
                  >
                    <Icon name={c.icon} size={15} className="text-muted" />
                    <span className="text-[13px] flex-1">{c.label}</span>
                    <Icon name="chevronRight" size={12} className="text-slate-300" />
                  </button>
                ))}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

// Notifications panel
function NotifPanel({ open, onClose, alerts }) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[55]">
      <div className="absolute inset-0 overlay-in" onClick={onClose} />
      <div className="absolute top-16 right-6 w-96 bg-white border border-border rounded-xl shadow-pop sheet-in">
        <div className="px-4 py-3 border-b border-border flex items-center justify-between">
          <h3 className="text-[13px] font-semibold">Alertas del período</h3>
          <span className="text-[11px] text-muted">{alerts.length} activas</span>
        </div>
        <div className="max-h-[60vh] overflow-y-auto">
          {alerts.map((a) => (
            <div key={a.id} className="px-4 py-3 border-b border-border last:border-b-0 flex gap-3">
              <Badge variant={a.level === 'high' ? 'red' : a.level === 'med' ? 'amber' : 'default'}>
                {a.level === 'high' ? 'Alta' : a.level === 'med' ? 'Media' : 'Info'}
              </Badge>
              <div className="flex-1 min-w-0">
                <div className="text-[13px] text-ink leading-snug">{a.title}</div>
                <div className="text-[11px] text-muted mt-0.5 tnum">
                  {a.when} · {a.meta}
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="px-4 py-2 border-t border-border text-center">
          <button className="text-[12px] text-amber hover:underline">Ver todas</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, Topbar, CommandPalette, NotifPanel });
