// src/shell.jsx — left nav + topbar + toasts. Wraps every signed-in screen.

// Nav agrupado por la arquitectura de 3 vistas: el "Trabajo del día"
// (Eventos = el cuándo · Pendientes = el qué atiendo · Cumplimiento = el qué falta),
// proyecciones de un mismo motor, separadas de los "Datos" (libro y configuración).
const NAV_SECTIONS = [
  { items: [
    { id: 'inicio', label: 'Inicio', path: '/inicio', icon: 'home' },
  ] },
  { label: 'Trabajo del día', items: [
    { id: 'eventos',      label: 'Eventos',      path: '/eventos',      icon: 'cal'    },
    { id: 'pendientes',   label: 'Pendientes',   path: '/pendientes',   icon: 'inbox', badge: 'pendientes' },
    { id: 'operaciones',  label: 'Operaciones',  path: '/operaciones',  icon: 'folder' },
    { id: 'cumplimiento', label: 'Cumplimiento', path: '/cumplimiento', icon: 'shield' },
  ] },
  { label: 'Datos', items: [
    { id: 'importar',     label: 'Importar',     path: '/importar',     icon: 'upload', badge: 'revision' },
    { id: 'polizas',      label: 'Pólizas',      path: '/polizas',      icon: 'book'   },
    { id: 'clientes',     label: 'Clientes',     path: '/clientes',     icon: 'user'   },
    { id: 'contactos',    label: 'Contactos',    path: '/contactos',    icon: 'mail'   },
    { id: 'catalogo',     label: 'Catálogo',     path: '/catalogo',     icon: 'tag'    },
  ] },
  { items: [
    { id: 'ajustes', label: 'Ajustes', path: '/ajustes', icon: 'settings' },
  ] },
];

function AxLogo({ size = 22 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
      <div style={{
        fontFamily: 'var(--font-logo)', fontWeight: 800,
        fontSize: size, color: 'var(--ax-fg-strong)', letterSpacing: '-0.02em',
        lineHeight: 1, display: 'inline-flex', alignItems: 'baseline',
      }}>
        piixi
        <span style={{ color: 'var(--ax-accent)', marginLeft: 1 }}>.</span>
      </div>
    </div>
  );
}

function AxNavButton({ item, counts }) {
  const { path, navigate } = useHashRoute();
  const active = path === item.path || path.startsWith(item.path + '/');
  const badgeCount = item.badge ? (counts[item.badge] || 0) : 0;
  return (
    <button
      onClick={() => navigate(item.path)}
      style={{
        appearance: 'none', border: 0,
        background: active ? 'var(--ax-bg-3)' : 'transparent',
        color: active ? 'var(--ax-fg-strong)' : 'var(--ax-fg-muted)',
        padding: '8px 10px',
        borderRadius: 6,
        fontSize: 13,
        display: 'flex', alignItems: 'center', gap: 10,
        textAlign: 'left',
        fontWeight: active ? 500 : 400,
        position: 'relative',
        transition: 'background 120ms, color 120ms',
        cursor: 'default',
      }}
      onMouseEnter={(e) => { if (!active) { e.currentTarget.style.background = 'var(--ax-bg-2)'; e.currentTarget.style.color = 'var(--ax-fg)'; } }}
      onMouseLeave={(e) => { if (!active) { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ax-fg-muted)'; } }}
    >
      {active ? <span style={{
        position: 'absolute', left: -12, top: 7, bottom: 7, width: 2,
        background: 'var(--ax-accent)', borderRadius: 0,
      }}/> : null}
      <AxIcon name={item.icon} size={15}/>
      <span style={{ flex: 1 }}>{item.label}</span>
      {badgeCount > 0 ? (
        <span style={{
          fontFamily: 'var(--font-mono)', fontSize: 10,
          padding: '1px 6px', borderRadius: 4,
          background: active ? 'var(--ax-warm-soft)' : 'var(--ax-bg-3)',
          border: '1px solid ' + (active ? 'var(--ax-warm-line)' : 'var(--ax-border-strong)'),
          color: 'var(--ax-warm)',
          letterSpacing: '0.04em',
        }}>{badgeCount}</span>
      ) : null}
    </button>
  );
}

function AxLeftNav() {
  const { state } = useAxStore();
  const { navigate } = useHashRoute();
  const counts = {
    pendientes: window.AdmixDerive ? AdmixDerive.derivePendientes(state.policies).length : 0,
    revision: state.pendientes.length,
  };

  return (
    <nav style={{
      width: 'var(--ax-nav-w)', flexShrink: 0,
      background: 'var(--ax-bg-1)',
      borderRight: '1px solid var(--ax-border)',
      display: 'flex', flexDirection: 'column',
      padding: '18px 12px 12px',
    }}>
      <div style={{ padding: '4px 10px 18px' }}>
        <AxLogo/>
        <div style={{
          marginTop: 4, fontSize: 10, color: 'var(--ax-fg-faint)',
          fontFamily: 'var(--font-mono)', letterSpacing: '0.18em', textTransform: 'uppercase',
        }}>local · v1.0.0</div>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {NAV_SECTIONS.map((section, si) => (
          <React.Fragment key={si}>
            {section.label ? (
              <div style={{
                padding: si === 0 ? '6px 10px 4px' : '14px 10px 4px',
                fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.18em',
                textTransform: 'uppercase', color: 'var(--ax-fg-faint)',
              }}>{section.label}</div>
            ) : null}
            {section.items.map((item) => (
              <AxNavButton key={item.id} item={item} counts={counts}/>
            ))}
          </React.Fragment>
        ))}
      </div>

      <div style={{ marginTop: 'auto', padding: '10px 6px 4px', borderTop: '1px solid var(--ax-border)' }}>
        <button
          onClick={() => navigate('/ajustes/doctor')}
          style={{
            appearance: 'none', border: 0, background: 'transparent',
            color: 'var(--ax-fg-muted)', fontSize: 12,
            padding: '8px 10px', borderRadius: 6,
            display: 'flex', alignItems: 'center', gap: 10, width: '100%',
            textAlign: 'left', cursor: 'default',
          }}
        >
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span className="ax-pulse" style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--ax-accent)' }}/>
            <span>Diagnóstico</span>
          </span>
          <span style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--ax-fg-faint)', fontFamily: 'var(--font-mono)' }}>OK</span>
        </button>
        <div style={{ padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <AxAvatar name={state.user.name} size={26}/>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ fontSize: 12, color: 'var(--ax-fg-strong)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {state.user.name}
            </div>
            <div style={{ fontSize: 10, color: 'var(--ax-fg-faint)', fontFamily: 'var(--font-mono)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {state.user.orgName}
            </div>
          </div>
        </div>
      </div>
    </nav>
  );
}

function AxTopbar({ rightContent }) {
  return (
    <div style={{
      height: 'var(--ax-topbar-h)', flexShrink: 0,
      background: 'var(--ax-bg-1)',
      borderBottom: '1px solid var(--ax-border)',
      display: 'flex', alignItems: 'center', padding: '0 24px', gap: 16,
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        color: 'var(--ax-fg-faint)', fontSize: 12, fontFamily: 'var(--font-mono)',
      }}>
        <span className="ax-pulse" style={{
          width: 6, height: 6, borderRadius: '50%', background: 'var(--ax-accent)',
        }}/>
        <span style={{ letterSpacing: '0.12em', textTransform: 'uppercase' }}>localhost:7878</span>
      </div>
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
        <div style={{
          width: 320, height: 30, borderRadius: 6,
          background: 'var(--ax-bg-3)',
          border: '1px solid var(--ax-border)',
          display: 'flex', alignItems: 'center', padding: '0 10px', gap: 8,
          color: 'var(--ax-fg-faint)', fontSize: 12,
        }}>
          <AxIcon name="search" size={13}/>
          <span style={{ flex: 1 }}>Buscar póliza, cliente, RFC…</span>
          <span className="ax-kbd">⌘K</span>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        {rightContent}
        <button className="ax-btn ax-btn--tertiary" style={{ height: 30, width: 30, padding: 0 }} title="Notificaciones">
          <AxIcon name="bell" size={14}/>
        </button>
        <button className="ax-btn ax-btn--tertiary" style={{ height: 30, width: 30, padding: 0 }} title="Ayuda">
          <AxIcon name="help" size={14}/>
        </button>
      </div>
    </div>
  );
}

// ─── Toast surface ───────────────────────────────────────────
function AxToastDeck() {
  const { state, dismissToast } = useAxStore();
  return (
    <div style={{
      position: 'fixed', right: 24, bottom: 24, zIndex: 800,
      display: 'flex', flexDirection: 'column-reverse', gap: 10, maxWidth: 380,
    }}>
      {state.toasts.map((t) => {
        const tone =
          t.kind === 'success' ? { bg: 'var(--ax-accent-soft)', line: 'var(--ax-accent-line)', color: 'var(--ax-accent)' }
          : t.kind === 'warn'  ? { bg: 'var(--ax-warm-soft)', line: 'var(--ax-warm-line)', color: 'var(--ax-warm)' }
          : t.kind === 'error' ? { bg: 'var(--ax-danger-soft)', line: 'rgba(233,76,77,0.22)', color: 'var(--ax-danger)' }
          : { bg: 'var(--ax-bg-3)', line: 'var(--ax-border-strong)', color: 'var(--ax-fg)' };
        return (
          <div key={t.id} className="ax-fade-in" style={{
            background: 'var(--ax-bg-2)',
            border: '1px solid var(--ax-border-strong)',
            borderLeft: '2px solid ' + tone.color,
            borderRadius: 8,
            padding: '12px 14px',
            display: 'flex', alignItems: 'flex-start', gap: 12,
            boxShadow: '0 12px 32px rgba(0,0,0,0.5)',
          }}>
            <div style={{
              width: 24, height: 24, borderRadius: 4, flexShrink: 0,
              background: tone.bg, color: tone.color,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <AxIcon name={t.kind === 'success' ? 'check' : t.kind === 'warn' ? 'alert' : 'info'} size={14}/>
            </div>
            <div style={{ flex: 1, fontSize: 13, color: 'var(--ax-fg)', lineHeight: 1.45 }}>
              {t.title ? <div style={{ fontWeight: 500, color: 'var(--ax-fg-strong)', marginBottom: 2 }}>{t.title}</div> : null}
              <div>{t.message}</div>
              {t.action ? (
                <div style={{ marginTop: 8 }}>
                  <button className="ax-btn ax-btn--sm ax-btn--secondary" onClick={() => { t.action.onClick && t.action.onClick(); dismissToast(t.id); }}>
                    {t.action.label}
                  </button>
                </div>
              ) : null}
            </div>
            <button onClick={() => dismissToast(t.id)} style={{
              appearance: 'none', border: 0, background: 'transparent',
              color: 'var(--ax-fg-faint)', cursor: 'default', padding: 2,
            }}><AxIcon name="x" size={12}/></button>
          </div>
        );
      })}
    </div>
  );
}

// ─── Crumb helper ────────────────────────────────────────────
function AxCrumb({ items }) {
  const { navigate } = useHashRoute();
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ax-fg-muted)' }}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 ? <AxIcon name="chevron-right" size={11} style={{ color: 'var(--ax-fg-faint)' }}/> : null}
          {it.to ? (
            <button onClick={() => navigate(it.to)} style={{
              appearance: 'none', border: 0, background: 'transparent', color: 'var(--ax-fg-muted)',
              padding: 0, cursor: 'default', fontSize: 12,
            }}
            onMouseEnter={(e) => e.currentTarget.style.color = 'var(--ax-fg-strong)'}
            onMouseLeave={(e) => e.currentTarget.style.color = 'var(--ax-fg-muted)'}
            >{it.label}</button>
          ) : (
            <span style={{ color: 'var(--ax-fg)' }}>{it.label}</span>
          )}
        </React.Fragment>
      ))}
    </div>
  );
}

Object.assign(window, { AxLogo, AxLeftNav, AxTopbar, AxToastDeck, AxCrumb });
