// Menu lateral branco colapsável — componente ÚNICO usado por Configurações, Rebanhos e Maquinário.
// groups: [{ label?, icon?, items: [{ id, label, icon?, active, onClick, tag?, children?: [{ id, label, active, onClick }] }] }]
// Expandido: grupos com título colapsável. Recolhido (64px): 1 ícone por grupo (ou por item, se o grupo não tem título);
// Recolhido: se todos os itens do grupo têm ícone, cada item vira um ícone clicável no rail (item com children abre flyout
// com as subseções). Se não têm ícone (Configurações), o grupo vira 1 ícone e o hover abre flyout com os itens.
// hover/foco abre um flyout com os itens do grupo — navega sem precisar expandir o menu. Estado salvo em localStorage[storageKey].
(() => {
  if (document.getElementById('fg-sidemenu-kf')) return
  const st = document.createElement('style'); st.id = 'fg-sidemenu-kf'
  st.textContent = '@keyframes fgFlyIn{from{opacity:0;transform:translateX(-6px)}to{opacity:1;transform:none}}'
  document.head.appendChild(st)
})()

const FGSM = { bg: '#f7f9f5', fg: 'var(--color-grayish-dark)', icon: 'var(--color-grayish)', active: 'var(--color-primary)', activeBg: 'var(--color-primary-30)', hover: 'rgba(65, 94, 63, 0.06)', line: '1px solid rgba(65, 94, 63, 0.10)' }
// Ícones que a fonte do sistema não tem, no mesmo traço outline (stroke ~1.6 em 24px).
const FG_SVG_ICONS = {
  tractor: <g fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><circle cx="7" cy="16" r="4"></circle><circle cx="7" cy="16" r="1.2"></circle><circle cx="18.5" cy="17.5" r="2.5"></circle><path d="M4.5 12.6V5h6.2l1.3 5.5"></path><path d="M12 10.5h6.6c.8 0 1.4.6 1.4 1.4v3.4"></path><path d="M11 16h5"></path><path d="M16.5 10.5V6.5"></path></g>,
}
const FGI = ({ n, size = 18, color }) => FG_SVG_ICONS[n]
  ? <svg viewBox="0 0 24 24" width={size} height={size} style={{ color, flexShrink: 0, display: 'block' }} aria-hidden="true">{FG_SVG_ICONS[n]}</svg>
  : <i className={'icon-font-' + n} style={{ fontSize: size, color, lineHeight: 1 }}></i>
const fgHov = (on) => (e) => { if (!e.currentTarget.dataset.active) e.currentTarget.style.background = on ? FGSM.hover : 'transparent' }

function FGRow({ it, sub, indent, onPick, open, onToggle }) {
  const hasKids = it.children && it.children.length
  const kidActive = hasKids && it.children.some((c) => c.active)
  const on = it.active || (kidActive && !open)
  return (
    <button data-active={on ? '1' : undefined} onClick={hasKids ? onToggle : () => { it.onClick && it.onClick(); onPick && onPick() }} onMouseEnter={fgHov(true)} onMouseLeave={fgHov(false)}
      style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 12, width: 'calc(100% - 16px)', minHeight: sub ? 34 : 40, margin: '1px 8px', padding: sub ? '7px 12px 7px 42px' : (it.icon ? '9px 12px' : '8px 12px 8px ' + indent + 'px'), border: 0, borderRadius: 8, cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-family)', fontSize: sub ? 14 : 15,
        fontWeight: on ? 'var(--font-weight-semibold)' : 'var(--font-weight-medium)', color: on ? FGSM.active : FGSM.fg, background: on ? FGSM.activeBg : 'transparent', transition: 'background .12s' }}>
      {on && <span style={{ position: 'absolute', left: -8, top: 8, bottom: 8, width: 3, borderRadius: '0 3px 3px 0', background: FGSM.active }}></span>}
      {it.icon && !sub && <FGI n={it.icon} color={on ? FGSM.active : FGSM.icon} />}
      <span style={{ flex: 1, minWidth: 0, textWrap: 'pretty', lineHeight: 1.3 }}>{it.label}</span>
      {it.badge != null && <span style={{ background: 'var(--color-alert)', color: 'var(--color-alert-dark)', borderRadius: 10, padding: '1px 7px', fontSize: 12, fontWeight: 'var(--font-weight-bold)', lineHeight: '16px', minWidth: 18, textAlign: 'center', flexShrink: 0 }}>{it.badge}</span>}
      {it.tag && <span style={{ padding: '1px 6px', borderRadius: 'var(--border-radius-chip)', border: '1px solid var(--color-neutral-200)', color: 'var(--color-grayish)', fontSize: 10, fontWeight: 'var(--font-weight-semibold)', lineHeight: '14px', letterSpacing: '.04em' }}>{it.tag}</span>}
      {hasKids && <FGI n={open ? 'chevron-up' : 'chevron-down'} size={16} color="var(--color-neutral-300)" />}
    </button>
  )
}

function FGSideMenu({ groups, storageKey = 'fg_menu_mini', title, titleIcon, itemIndent = 12, ariaLabel }) {
  const [mini, setMini] = React.useState(() => localStorage.getItem(storageKey) === '1')
  const [fechados, setFechados] = React.useState({})
  const [subAberto, setSubAberto] = React.useState({})
  const [fly, setFly] = React.useState(null) // { key, top, left, title, items }
  const navRef = React.useRef(null)
  const tOpen = React.useRef(0), tClose = React.useRef(0)
  React.useEffect(() => { localStorage.setItem(storageKey, mini ? '1' : '0'); setFly(null) }, [mini])
  React.useEffect(() => () => { clearTimeout(tOpen.current); clearTimeout(tClose.current) }, [])

  const abrir = (e, key, titulo, items) => {
    clearTimeout(tClose.current); clearTimeout(tOpen.current)
    const r = e.currentTarget.getBoundingClientRect(), n = navRef.current.getBoundingClientRect()
    const fn = () => setFly({ key, top: r.top - (items ? 6 : 0), left: n.right + 8, h: r.height, title: titulo, items })
    if (fly) fn(); else tOpen.current = setTimeout(fn, 90)
  }
  const fechar = () => { clearTimeout(tOpen.current); tClose.current = setTimeout(() => setFly(null), 160) }
  const manter = () => clearTimeout(tClose.current)
  const toggleSub = (id) => setSubAberto((s) => ({ ...s, [id]: !s[id] }))
  const subOpen = (it) => subAberto[it.id] ?? it.children.some((c) => c.active)
  const anyActive = (items) => items.some((i) => i.active || (i.children && i.children.some((c) => c.active)))
  const primeiro = (items) => { const a = items.find((i) => i.active) || items[0]; const f = a.children ? (a.children.find((c) => c.active) || a.children[0]) : a; f.onClick && f.onClick() }

  // Chamado como função (não <RailBtn/>) para não remontar o botão a cada render do hover.
  const RailBtn = ({ k, icon, label, active, items, onClick }) => {
    const badge = items && items.reduce((n, i) => n + (i.badge || 0), 0)
    return (
    <button aria-label={label} data-active={active ? '1' : undefined} onClick={() => { onClick(); setFly(null) }}
      onMouseEnter={(e) => { fgHov(true)(e); abrir(e, k, label, items) }} onMouseLeave={(e) => { fgHov(false)(e); fechar() }}
      onFocus={(e) => abrir(e, k, label, items)} onBlur={fechar}
      style={{ position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', width: 44, height: 40, margin: '2px auto', border: 0, borderRadius: 8, cursor: 'pointer', background: active ? FGSM.activeBg : (fly && fly.key === k ? FGSM.hover : 'transparent'), transition: 'background .12s' }}>
      {active && <span style={{ position: 'absolute', left: -10, top: 8, bottom: 8, width: 3, borderRadius: '0 3px 3px 0', background: FGSM.active }}></span>}
      <FGI n={icon} size={20} color={active ? FGSM.active : FGSM.icon} />
      {badge > 0 && <span style={{ position: 'absolute', top: 3, right: 1, minWidth: 16, height: 16, padding: '0 4px', borderRadius: 8, background: 'var(--color-alert)', color: 'var(--color-alert-dark)', fontSize: 10, fontWeight: 'var(--font-weight-bold)', lineHeight: '16px', textAlign: 'center' }}>{badge}</span>}
    </button>
  )}

  return (
    <nav ref={navRef} aria-label={ariaLabel || title || 'Menu'} style={{ width: mini ? 64 : 'var(--menu-width-default)', minWidth: mini ? 64 : 'var(--menu-width-default)', transition: 'width .2s ease, min-width .2s ease', height: '100%', overflowY: 'auto', overflowX: 'hidden', flexShrink: 0,
      background: FGSM.bg, borderRight: '1px solid rgba(0, 0, 0, 0.08)', boxShadow: '2px 0 4px rgba(0, 0, 0, 0.12)', position: 'relative', zIndex: 15, paddingBottom: 16, fontFamily: 'var(--font-family)' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: mini ? 'center' : (title ? 'space-between' : 'flex-end'), gap: 8, minHeight: 28, padding: mini ? '12px 0 6px' : (title ? '12px 10px 6px 20px' : '12px 10px 6px') }}>
        {!mini && title && <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 'var(--font-size-xl)', fontWeight: 'var(--font-weight-bold)', color: FGSM.active, whiteSpace: 'nowrap' }}>{titleIcon && <FGI n={titleIcon} size={20} color="inherit" />}{title}</span>}
        <button onClick={() => setMini(!mini)} title={mini ? 'Expandir menu' : 'Recolher menu'} aria-label={mini ? 'Expandir menu' : 'Recolher menu'}
          onMouseEnter={(e) => { e.currentTarget.style.background = FGSM.hover }} onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent' }}
          style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 28, height: 28, padding: 0, flexShrink: 0, border: 0, borderRadius: '50%', background: 'transparent', cursor: 'pointer', transition: 'background .12s' }}>
          <FGI n={mini ? 'chevron-forward' : 'chevron-back'} size={14} color={FGSM.icon} />
        </button>
      </div>

      {groups.map((g, gi) => {
        const key = g.label || 'g' + gi
        if (mini) return (
          <div key={key} style={{ padding: '4px 0', margin: '0 10px', borderTop: gi ? FGSM.line : 'none' }}>
            {g.label && (g.rail === 'group' || g.items.some((i) => !i.icon))
              ? RailBtn({ k: key, icon: g.icon || (g.items[0] && g.items[0].icon) || 'folder', label: g.label, active: anyActive(g.items), items: g.items, onClick: () => primeiro(g.items) })
              : g.items.map((it) => <React.Fragment key={it.id}>{RailBtn({ k: key + it.id, icon: it.icon, label: it.label, active: anyActive([it]), items: it.children, onClick: () => primeiro([it]) })}</React.Fragment>)}
          </div>
        )
        const aberto = !g.label || !fechados[g.label]
        return (
          <div key={key} style={{ padding: '6px 0 8px', borderTop: gi ? FGSM.line : 'none' }}>
            {g.label && (
              <button onClick={() => setFechados({ ...fechados, [g.label]: !fechados[g.label] })} aria-expanded={aberto} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: '0 20px', margin: '8px 0 6px', border: 0, background: 'transparent', cursor: 'pointer', fontFamily: 'inherit' }}>
                <span style={{ fontSize: 'var(--font-size-xsm)', fontWeight: 'var(--font-weight-semibold)', letterSpacing: '0.08em', textTransform: 'uppercase', color: FGSM.active }}>{g.label}</span>
                <FGI n={aberto ? 'chevron-up' : 'chevron-down'} size={14} color="var(--color-primary-200)" />
              </button>
            )}
            <div style={{ display: 'grid', gridTemplateRows: aberto ? '1fr' : '0fr', transition: 'grid-template-rows .22s ease' }}>
              <div style={{ overflow: 'hidden' }}>
                {g.items.map((it) => (
                  <React.Fragment key={it.id}>
                    <FGRow it={it} indent={itemIndent} open={it.children && subOpen(it)} onToggle={() => toggleSub(it.id)} />
                    {it.children && subOpen(it) && it.children.map((c) => <FGRow key={c.id} it={c} sub />)}
                  </React.Fragment>
                ))}
              </div>
            </div>
          </div>
        )
      })}

      {mini && fly && ReactDOM.createPortal(
        <div onMouseEnter={manter} onMouseLeave={fechar} role="menu" aria-label={fly.title}
          style={{ position: 'fixed', top: fly.top, left: fly.left, zIndex: 1000, animation: 'fgFlyIn .14s ease-out', fontFamily: 'var(--font-family)' }}>
          <span style={{ position: 'absolute', left: -10, top: 0, bottom: 0, width: 10 }}></span>
          {fly.items ? (
            <div style={{ minWidth: 240, maxWidth: 300, padding: '10px 0 6px', background: '#fff', border: '1px solid rgba(0, 0, 0, 0.06)', borderRadius: 10, boxShadow: '0 8px 24px rgba(0, 0, 0, 0.14), 0 2px 4px rgba(0, 0, 0, 0.06)' }}>
              <div style={{ padding: '0 20px 6px', fontSize: 'var(--font-size-xsm)', fontWeight: 'var(--font-weight-semibold)', letterSpacing: '0.08em', textTransform: 'uppercase', color: FGSM.active, whiteSpace: 'nowrap' }}>{fly.title}</div>
              {fly.items.map((it) => (
                <React.Fragment key={it.id}>
                  {it.children
                    ? <div style={{ padding: '8px 20px 2px', fontSize: 13, fontWeight: 'var(--font-weight-medium)', color: FGSM.icon }}>{it.label}</div>
                    : <FGRow it={it} indent={itemIndent} onPick={() => setFly(null)} />}
                  {it.children && it.children.map((c) => <FGRow key={c.id} it={{ ...c, icon: undefined }} indent={20} onPick={() => setFly(null)} />)}
                </React.Fragment>
              ))}
            </div>
          ) : (
            <div style={{ display: 'flex', alignItems: 'center', height: fly.h, padding: '0 12px', background: 'var(--color-grayish-dark)', color: '#fff', borderRadius: 6, fontSize: 13, fontWeight: 'var(--font-weight-medium)', whiteSpace: 'nowrap', boxShadow: '0 4px 12px rgba(0, 0, 0, 0.18)' }}>{fly.title}</div>
          )}
        </div>, document.body)}
    </nav>
  )
}
window.FGSideMenu = FGSideMenu
