// mnm-views.jsx — App shell, Sidebar (global + empresa nav), routing

/* ─── ICONS ──────────────────────────────────────────────────────────────── */
const IcSun    = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="2.5" stroke="currentColor" strokeWidth="1.3"/><path d="M7 1v1.5M7 11.5V13M1 7h1.5M11.5 7H13M2.93 2.93l1.06 1.06M10.01 10.01l1.06 1.06M10.01 3.99l1.06-1.06M2.93 11.07l1.06-1.06" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const IcMoon   = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M12 8.5A5.5 5.5 0 015.5 2 5.5 5.5 0 1012 8.5z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>;
const IcLogout = ()=><svg width="13" height="13" viewBox="0 0 13 13" fill="none"><path d="M5 2H3a1 1 0 00-1 1v7a1 1 0 001 1h2M8.5 4L11 6.5l-2.5 2.5M4.5 6.5h6.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>;
const IcCtx    = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2 7h10M2 4h7M2 10h5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>;

/* Global nav icons */
const IcPortfolio = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1.5" y="1.5" width="4.5" height="4.5" rx="1" stroke="currentColor" strokeWidth="1.3"/><rect x="8" y="1.5" width="4.5" height="4.5" rx="1" stroke="currentColor" strokeWidth="1.3"/><rect x="1.5" y="8" width="4.5" height="4.5" rx="1" stroke="currentColor" strokeWidth="1.3"/><rect x="8" y="8" width="4.5" height="4.5" rx="1" stroke="currentColor" strokeWidth="1.3"/></svg>;
const IcLab      = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M5 2v5L2 12a1 1 0 00.9 1.5h8.2A1 1 0 0012 12L9 7V2" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/><path d="M4.5 2h5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/></svg>;
const IcBell     = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1.5a4.5 4.5 0 014.5 4.5v2.5l1 2H1.5l1-2V6A4.5 4.5 0 017 1.5z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/><path d="M5.5 11.5a1.5 1.5 0 003 0" stroke="currentColor" strokeWidth="1.3"/></svg>;
const IcGear     = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="7" cy="7" r="2" stroke="currentColor" strokeWidth="1.3"/><path d="M7 1.5v1M7 11.5v1M1.5 7h1M11.5 7h1M3.4 3.4l.7.7M9.9 9.9l.7.7M10.6 3.4l-.7.7M4.1 9.9l-.7.7" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;

/* Empresa nav icons */
const IcResumen = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1.5" y="1.5" width="11" height="11" rx="2" stroke="currentColor" strokeWidth="1.3"/><path d="M4 5h6M4 7.5h4M4 10h3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const IcBuild  = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1.5" y="5" width="5" height="7" rx="1" stroke="currentColor" strokeWidth="1.3"/><rect x="7" y="2" width="5.5" height="10" rx="1" stroke="currentColor" strokeWidth="1.3"/><path d="M3 8.5h2M3 11h2M9 5h2M9 7.5h2M9 10h2" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round"/></svg>;
const IcFinance= ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M1.5 10L5 6.5l3 2.5 4-5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round"/></svg>;
const IcTx     = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1.5" y="3" width="11" height="8" rx="1.5" stroke="currentColor" strokeWidth="1.3"/><path d="M1.5 6h11" stroke="currentColor" strokeWidth="1.2"/><path d="M4 8.5h2M9 8.5h.5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const IcBox2   = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M12.5 4.5L7 7.5L1.5 4.5M7 7.5V13.5M12.5 4.5L7 1.5L1.5 4.5L7 7.5Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>;
const IcAlert2 = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M7 1.5L13 12H1L7 1.5Z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/><path d="M7 6v2.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/><circle cx="7" cy="10" r=".6" fill="currentColor"/></svg>;
const IcCheck2 = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7l3 3 6-6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>;
const IcVault  = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><rect x="1.5" y="2" width="11" height="10" rx="2" stroke="currentColor" strokeWidth="1.3"/><circle cx="7" cy="7" r="2" stroke="currentColor" strokeWidth="1.2"/><circle cx="7" cy="7" r=".6" fill="currentColor"/><path d="M4 2V1M10 2V1" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;
const IcTeam   = ()=><svg width="14" height="14" viewBox="0 0 14 14" fill="none"><circle cx="5" cy="4.5" r="2" stroke="currentColor" strokeWidth="1.3"/><path d="M1 11.5c0-2.2 1.8-4 4-4s4 1.8 4 4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/><circle cx="10.5" cy="4.5" r="1.5" stroke="currentColor" strokeWidth="1.2"/><path d="M12.5 11.5c0-1.7-1.3-3-3-3" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>;

/* ─── NAV DATA ───────────────────────────────────────────────────────────── */
const GLOBAL_NAV = [
  {id:'consolidado',   label:'Mi Portafolio',  Icon:IcPortfolio},
  {id:'laboratorio',   label:'Laboratorio',    Icon:IcLab},
  {id:'notificaciones',label:'Notificaciones', Icon:IcBell},
  {id:'configuracion', label:'Configuración',  Icon:IcGear},
];
const EMPRESA_NAV = [
  {id:'resumen',       label:'Resumen ejecutivo',    Icon:IcResumen},
  {id:'estructura',    label:'Estructura',            Icon:IcBuild},
  {id:'financiero',    label:'Financiero',            Icon:IcFinance},
  {id:'transacciones', label:'Transacciones',         Icon:IcTx},
  {id:'productos',     label:'Productos y Servicios', Icon:IcBox2},
  {id:'hallazgos',     label:'Hallazgos',             Icon:IcAlert2, badge:1},
  {id:'plan',          label:'Plan de Acción',        Icon:IcCheck2},
  {id:'boveda',        label:'Bóveda',                Icon:IcVault},
  {id:'team',          label:'Team',                  Icon:IcTeam},
];

/* ─── SIDEBAR ────────────────────────────────────────────────────────────── */
function Sidebar({ view, setView, empresaId, empresaSection, setEmpresaSection, onBack, darkMode, onToggleDark, onLogout, period }) {
  var isInEmpresa = !!empresaId;
  var company = isInEmpresa ? (COMPANIES_DATA.find(function(c){return c.id===empresaId;})||null) : null;

  function NavBtn({ item, active, onClick }) {
    return (
      <button onClick={onClick} style={{
        display:'flex',alignItems:'center',gap:'9px',
        padding:'7px 10px',borderRadius:'9px',border:'none',
        background:active?'var(--glass-bg-atmo)':'none',
        color:active?'var(--orange,#F97316)':'var(--t2)',
        cursor:'pointer',textAlign:'left',width:'100%',
        fontSize:'12.5px',fontWeight:active?600:400,
        fontFamily:'var(--font)',transition:'background 0.1s,color 0.1s',position:'relative',
      }}
      onMouseEnter={function(e){if(!active){e.currentTarget.style.background='var(--glass-bg-atmo)';e.currentTarget.style.color='var(--t1)';}}}
      onMouseLeave={function(e){if(!active){e.currentTarget.style.background='none';e.currentTarget.style.color='var(--t2)';}}}>
        {active&&<span style={{position:'absolute',left:0,top:'20%',bottom:'20%',width:'2.5px',background:'var(--orange,#F97316)',borderRadius:'0 2px 2px 0'}}/>}
        <item.Icon/>
        <span style={{flex:1}}>{item.label}</span>
        {item.badge&&!active&&<span style={{width:'16px',height:'16px',borderRadius:'50%',background:'rgba(220,38,38,0.12)',color:'#DC2626',fontSize:'9px',fontWeight:700,display:'flex',alignItems:'center',justifyContent:'center'}}>{item.badge}</span>}
      </button>
    );
  }

  return (
    <div className="sidebar" style={{width:'216px',flexShrink:0,height:'100vh',
      background:'rgba(245,240,234,0.82)',backdropFilter:'var(--glass-blur)',WebkitBackdropFilter:'var(--glass-blur)',
      borderRight:'0.5px solid rgba(255,255,255,0.5)',boxShadow:'1px 0 0 rgba(0,0,0,0.04)',
      display:'flex',flexDirection:'column',position:'relative',zIndex:10}}>

      {/* Logo */}
      <div style={{padding:'16px 14px 12px',borderBottom:'0.5px solid rgba(0,0,0,0.06)'}}>
        <div style={{display:'flex',alignItems:'center',gap:'8px'}}>
          <div style={{width:'28px',height:'28px',background:'var(--accent)',borderRadius:'8px',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0}}>
            <svg width="11" height="11" viewBox="0 0 12 12" fill="none"><path d="M6 1v10M1 6h10" stroke="var(--accent-text)" strokeWidth="2" strokeLinecap="round"/></svg>
          </div>
          <div>
            <div style={{fontSize:'12px',fontWeight:600,color:'var(--t1)',lineHeight:1.35}}>Mi Negocio</div>
            <div style={{fontSize:'10px',color:'var(--t3)',lineHeight:1.35}}>en Números</div>
          </div>
        </div>
      </div>

      <div style={{flex:1,overflowY:'auto',padding:'10px 8px 6px'}}>
        {/* Global nav */}
        <p style={{fontSize:'9px',fontWeight:600,letterSpacing:'0.1em',textTransform:'uppercase',color:'var(--t3)',marginBottom:'4px',paddingLeft:'10px'}}>GLOBAL</p>
        <nav style={{display:'flex',flexDirection:'column',gap:'1px',marginBottom:'10px'}}>
          {GLOBAL_NAV.map(function(item){
            return <NavBtn key={item.id} item={item} active={!isInEmpresa&&view===item.id} onClick={function(){setView(item.id);}} />;
          })}
        </nav>

        {/* Empresa nav */}
        {isInEmpresa && company && (
          <>
            <div style={{margin:'6px 0 6px',height:'0.5px',background:'var(--border)'}}/>
            <div style={{padding:'6px 10px',marginBottom:'4px'}}>
              <p style={{fontSize:'9px',fontWeight:600,letterSpacing:'0.09em',textTransform:'uppercase',color:'var(--t3)',margin:'0 0 4px'}}>EMPRESA</p>
              <div style={{display:'flex',alignItems:'center',gap:'6px'}}>
                {company.logo
                  ? <img src={company.logo} alt="" style={{width:'16px',height:'16px',borderRadius:'4px',objectFit:'cover'}}/>
                  : <div style={{width:'16px',height:'16px',borderRadius:'4px',background:company.color+'22',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'7px',fontWeight:800,color:company.color}}>{company.initials}</div>
                }
                <span style={{fontSize:'11.5px',fontWeight:600,color:'var(--t2)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{company.nombre}</span>
              </div>
            </div>
            <nav style={{display:'flex',flexDirection:'column',gap:'1px'}}>
              {EMPRESA_NAV.map(function(item){
                return <NavBtn key={item.id} item={item} active={empresaSection===item.id} onClick={function(){setEmpresaSection(item.id);}} />;
              })}
            </nav>
          </>
        )}
      </div>

      {/* Bottom */}
      <div style={{borderTop:'0.5px solid rgba(0,0,0,0.06)',padding:'8px 8px'}}>
        <a href="Lista de Espera.html" style={{display:'flex',alignItems:'center',gap:'7px',padding:'6px 10px',borderRadius:'8px',background:'rgba(249,115,22,0.08)',border:'0.5px solid rgba(249,115,22,0.22)',color:'#F97316',fontSize:'11.5px',textDecoration:'none',fontFamily:'var(--font)',marginBottom:'6px'}}>
          <svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M7.5 2.5L4 6l3.5 3.5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
          Lista de espera
        </a>

        <div style={{display:'flex',alignItems:'center',gap:'7px',padding:'4px 6px'}}>
          <div style={{width:'24px',height:'24px',borderRadius:'50%',background:'var(--glass-bg-atmo)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:'9px',fontWeight:700,color:'var(--t3)',flexShrink:0}}>IS</div>
          <div style={{minWidth:0,flex:1}}>
            <p style={{fontSize:'11px',fontWeight:600,color:'var(--t1)',margin:0,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>Isai Campo</p>
            <p style={{fontSize:'10px',color:'var(--t3)',margin:0}}>{period}</p>
          </div>
          <button onClick={onLogout} style={{background:'none',border:'none',cursor:'pointer',color:'var(--t3)',padding:'2px',lineHeight:0,flexShrink:0,transition:'color 0.1s'}}
            onMouseEnter={function(e){e.currentTarget.style.color='#DC2626';}}
            title="Volver a la lista de espera" onMouseLeave={function(e){e.currentTarget.style.color='var(--t3)';}}>
            <IcLogout/>
          </button>
        </div>
      </div>
    </div>
  );
}

/* ─── MOBILE FLOATING NAV ────────────────────────────────────────────────── */
function MobileNav({ view, empresaId, onNav, onAdd, onMenu }) {
  var IcBars = function(){ return <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M2.5 4.5h11M2.5 8h11M2.5 11.5h11" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>; };
  var items = [
    {id:'consolidado', label:'Portafolio', Icon:function(){return <Ic.Dashboard/>;}},
    {id:'hallazgos',   label:'Hallazgos',  Icon:function(){return <Ic.Alert/>;}},
    {id:'plan',        label:'Plan',       Icon:function(){return <Ic.List/>;}},
    {id:'__menu',      label:'Más',        Icon:function(){return <IcBars/>;}},
  ];
  function cell(it){
    var active = !empresaId && view===it.id;
    return (
      <button key={it.id} onClick={function(){ if(it.id==='__menu'){ onMenu(); } else { onNav(it.id); } }}
        style={{flex:1,display:'flex',flexDirection:'column',alignItems:'center',gap:'3px',padding:'7px 2px 5px',background:'none',border:'none',cursor:'pointer',color:active?'var(--accent)':'var(--t3)',fontFamily:'var(--font)',fontSize:'9px',fontWeight:active?600:400,transition:'color 0.14s'}}>
        <it.Icon/>
        <span>{it.label}</span>
      </button>
    );
  }
  return (
    <nav className="mobile-nav" style={{display:'none',position:'fixed',left:'12px',right:'12px',bottom:'12px',zIndex:120,alignItems:'center',height:'58px',padding:'0 6px',borderRadius:'100px',background:'var(--glass-sidebar-bg)',backdropFilter:'blur(24px) saturate(170%)',WebkitBackdropFilter:'blur(24px) saturate(170%)',border:'0.5px solid rgba(255,255,255,0.55)',boxShadow:'0 10px 34px rgba(0,0,0,0.16),0 0 0 0.5px rgba(255,255,255,0.4) inset'}}>
      {cell(items[0])}
      {cell(items[1])}
      <button onClick={onAdd} aria-label="Registrar"
        style={{flex:'0 0 auto',width:'50px',height:'50px',margin:'0 4px',borderRadius:'50%',background:'var(--accent)',border:'none',color:'var(--accent-text)',cursor:'pointer',display:'flex',alignItems:'center',justifyContent:'center',boxShadow:'0 6px 18px rgba(0,0,0,0.22)',transition:'transform 0.15s'}}>
        <svg width="20" height="20" viewBox="0 0 20 20" fill="none"><path d="M10 4v12M4 10h12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
      </button>
      {cell(items[2])}
      {cell(items[3])}
    </nav>
  );
}

/* ─── MOBILE DRAWER ──────────────────────────────────────────────────────── */
function MobileDrawer({ view, setView, empresaId, empresaSection, setEmpresaSection, darkMode, onToggleDark, onLogout, open, onClose }) {
  return (
    <>
      {open&&<div onClick={onClose} style={{position:'fixed',inset:0,background:'rgba(0,0,0,0.45)',zIndex:150,backdropFilter:'blur(2px)'}}/>}
      <div style={{position:'fixed',top:0,left:0,bottom:0,width:'256px',
        background:'var(--glass-sidebar-bg)',backdropFilter:'var(--glass-blur)',WebkitBackdropFilter:'var(--glass-blur)',
        borderRight:'0.5px solid rgba(255,255,255,0.5)',zIndex:160,
        transform:open?'translateX(0)':'translateX(-100%)',
        transition:'transform 0.25s cubic-bezier(0.4,0,0.2,1)',
        display:'flex',flexDirection:'column',boxShadow:open?'8px 0 28px rgba(0,0,0,0.12)':'none'}}>
        <div style={{padding:'16px',borderBottom:'0.5px solid rgba(0,0,0,0.06)',display:'flex',alignItems:'center',justifyContent:'space-between'}}>
          <div style={{display:'flex',alignItems:'center',gap:'8px'}}>
            <div style={{width:'28px',height:'28px',background:'var(--accent)',borderRadius:'8px',display:'flex',alignItems:'center',justifyContent:'center'}}><svg width="11" height="11" viewBox="0 0 12 12" fill="none"><path d="M6 1v10M1 6h10" stroke="var(--accent-text)" strokeWidth="2" strokeLinecap="round"/></svg></div>
            <span style={{fontSize:'12px',fontWeight:600,color:'var(--t1)'}}>Mi Negocio en Números</span>
          </div>
          <button onClick={onClose} style={{background:'none',border:'none',cursor:'pointer',color:'var(--t3)',fontSize:'18px',lineHeight:1}}>×</button>
        </div>
        <div style={{flex:1,overflowY:'auto',padding:'10px 8px'}}>
          <p style={{fontSize:'9px',fontWeight:600,letterSpacing:'0.1em',textTransform:'uppercase',color:'var(--t3)',marginBottom:'4px',paddingLeft:'10px'}}>GLOBAL</p>
          {GLOBAL_NAV.map(function(item){
            var active=!empresaId&&view===item.id;
            return <button key={item.id} onClick={function(){setView(item.id);onClose();}} style={{display:'flex',alignItems:'center',gap:'9px',padding:'8px 10px',borderRadius:'9px',border:'none',background:active?'var(--glass-bg-atmo)':'none',color:active?'var(--t1)':'var(--t2)',cursor:'pointer',textAlign:'left',width:'100%',fontSize:'12.5px',fontWeight:active?600:400,fontFamily:'var(--font)',marginBottom:'1px'}}><item.Icon/>{item.label}</button>;
          })}
          {empresaId&&<>
            <div style={{margin:'8px 0',height:'0.5px',background:'var(--border)'}}/>
            <p style={{fontSize:'9px',fontWeight:600,letterSpacing:'0.1em',textTransform:'uppercase',color:'var(--t3)',marginBottom:'4px',paddingLeft:'10px'}}>EMPRESA</p>
            {EMPRESA_NAV.map(function(item){
              var active=empresaSection===item.id;
              return <button key={item.id} onClick={function(){setEmpresaSection(item.id);onClose();}} style={{display:'flex',alignItems:'center',gap:'9px',padding:'8px 10px',borderRadius:'9px',border:'none',background:active?'var(--glass-bg-atmo)':'none',color:active?'var(--t1)':'var(--t2)',cursor:'pointer',textAlign:'left',width:'100%',fontSize:'12.5px',fontWeight:active?600:400,fontFamily:'var(--font)',marginBottom:'1px'}}><item.Icon/>{item.label}</button>;
            })}
          </>}
        </div>
        <div style={{borderTop:'0.5px solid rgba(0,0,0,0.06)',padding:'10px 8px'}}>
          
          <button onClick={function(){onLogout();onClose();}} style={{display:'flex',alignItems:'center',gap:'6px',padding:'6px 10px',borderRadius:'8px',background:'none',border:'none',color:'var(--t3)',fontSize:'11.5px',cursor:'pointer',fontFamily:'var(--font)'}}><IcLogout/>Cerrar sesión</button>
        </div>
      </div>
    </>
  );
}

/* ─── PAGE SHELL ─────────────────────────────────────────────────────────── */
function PageShell({ children, header }) {
  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',overflow:'hidden'}}>
      {header}
      <div style={{flex:1,overflowY:'auto',padding:'20px 24px'}} className="main-scroll">{children}</div>
    </div>
  );
}

/* ─── HALLAZGOS VIEW ─────────────────────────────────────────────────────── */
function HallazgosView({ period, setView }) {
  var data = APP_DATA.getPeriod(period||'Diciembre 2024');
  var hallazgos = data.hallazgos;
  var [expanded,setExpanded] = React.useState(null);
  var [filter,setFilter]     = React.useState('todos');
  var filtered = filter==='todos'?hallazgos:hallazgos.filter(function(h){return h.severity===filter;});
  var tabs = [{id:'todos',label:'Todos'},{id:'critico',label:'Crítico'},{id:'advertencia',label:'Advertencia'},{id:'info',label:'Informativo'}];
  var SEV_COLOR = {critico:'#DC2626',advertencia:'#D97706',info:'#797776'};
  var header = (
    <div style={{padding:'14px 20px',borderBottom:'0.5px solid var(--border)',flexShrink:0}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:'12px',flexWrap:'wrap',gap:'8px'}}>
        <div><h2 style={{fontSize:'15px',fontWeight:600,color:'var(--t1)',margin:0}}>Hallazgos IA</h2><p style={{fontSize:'11.5px',color:'var(--t3)',margin:'2px 0 0'}}>{period} · {hallazgos.length} encontrados</p></div>
        <div style={{display:'flex',gap:'6px',alignItems:'center'}}>
          {[['critico','#DC2626'],['advertencia','#D97706']].map(function(row){var n=hallazgos.filter(function(h){return h.severity===row[0];}).length;return n>0?<span key={row[0]} style={{fontSize:'10px',fontWeight:600,padding:'2px 8px',borderRadius:'var(--radius-tag)',background:row[1]+'15',color:row[1]}}>{SEV[row[0]].label}: {n}</span>:null;})}
        </div>
      </div>
      <div style={{display:'flex',gap:'3px',padding:'3px',background:'var(--glass-bg)',backdropFilter:'var(--glass-blur)',border:'0.5px solid var(--glass-border)',borderRadius:'var(--radius-tag)',width:'fit-content'}}>
        {tabs.map(function(t){return <button key={t.id} onClick={function(){setFilter(t.id);}} style={{padding:'5px 12px',borderRadius:'var(--radius-tag)',fontSize:'11.5px',fontWeight:filter===t.id?600:400,background:filter===t.id?'var(--glass-bg-atmo)':'none',border:'none',color:filter===t.id?'var(--t1)':'var(--t3)',cursor:'pointer',fontFamily:'var(--font)'}}>{t.label}</button>;})}
      </div>
    </div>
  );
  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',overflow:'hidden'}}>
      {header}
      <div style={{flex:1,overflowY:'auto',padding:'16px 20px'}} className="main-scroll">
        <div style={{maxWidth:'680px',display:'flex',flexDirection:'column',gap:'10px'}}>
          {filtered.map(function(h){return <FindingCard key={h.id} h={h} expanded={expanded===h.id} onToggle={function(){setExpanded(expanded===h.id?null:h.id);}} onPlan={setView?function(){setView('plan');}:null}/>;} )}
        </div>
      </div>
    </div>
  );
}

/* ─── PLAN ACCION VIEW ───────────────────────────────────────────────────── */
function PlanAccionView({ period, setView, acciones, setAcciones }) {
  var hallazgos = (APP_DATA.getPeriod(period||'Diciembre 2024')).hallazgos;
  var [regen,setRegen] = React.useState(false);
  var changeStatus = function(id,ns){setAcciones(function(prev){return prev.map(function(a){return a.id===id?Object.assign({},a,{status:ns}):a;});});};
  var done   = (acciones||BASE_ACCIONES).filter(function(a){return a.status==='completado';}).length;
  var inProg = (acciones||BASE_ACCIONES).filter(function(a){return a.status==='en-progreso';}).length;
  var list   = acciones||BASE_ACCIONES;
  return (
    <div style={{display:'flex',flexDirection:'column',height:'100%',overflow:'hidden'}}>
      <div style={{padding:'14px 20px',borderBottom:'0.5px solid var(--border)',flexShrink:0,display:'flex',alignItems:'center',justifyContent:'space-between',gap:'12px',flexWrap:'wrap'}}>
        <div><h2 style={{fontSize:'15px',fontWeight:600,color:'var(--t1)',margin:0}}>Plan de Acción</h2><p style={{fontSize:'11.5px',color:'var(--t3)',margin:'2px 0 0'}}>{done} completadas · {inProg} en progreso</p></div>
        <button onClick={function(){setRegen(true);}} style={{display:'flex',alignItems:'center',gap:'5px',padding:'6px 12px',borderRadius:'var(--radius-tag)',background:'var(--glass-bg)',backdropFilter:'var(--glass-blur)',border:'0.5px solid var(--glass-border)',color:'var(--t2)',fontSize:'12px',fontWeight:400,cursor:'pointer',fontFamily:'var(--font)'}}>↻ Regenerar</button>
      </div>
      <div style={{flex:1,overflowY:'auto',padding:'16px 20px'}} className="main-scroll">
        <div style={{maxWidth:'660px'}}>
          {regen&&<div style={{display:'flex',alignItems:'center',gap:'10px',background:'var(--glass-bg-atmo)',backdropFilter:'var(--glass-blur)',border:'0.5px solid var(--glass-border)',borderRadius:'var(--radius-card)',padding:'11px 14px',marginBottom:'14px',animation:'fadeInUp 0.2s ease'}}><div style={{width:'14px',height:'14px',borderRadius:'50%',border:'2px solid var(--accent)',borderTopColor:'transparent',animation:'spin 0.9s linear infinite',flexShrink:0}}/><p style={{fontSize:'12.5px',color:'var(--t2)',margin:0,flex:1}}>Analizando hallazgos...</p><button onClick={function(){setRegen(false);}} style={{color:'var(--t3)',background:'none',border:'none',cursor:'pointer',flexShrink:0}}>✕</button></div>}
          <div style={{display:'flex',flexDirection:'column',gap:'8px'}}>
            {list.map(function(a){return <ActionRow key={a.id} action={a} hallazgos={hallazgos} onChange={changeStatus}/>;} )}
          </div>
        </div>
      </div>
    </div>
  );
}

/* ─── NOTIFICACIONES VIEW ────────────────────────────────────────────────── */
function NotificacionesView() {
  var items = [
    {id:1,icon:'warn',title:'Runway bajo — Consultoría RRHH',desc:'Con el burn rate actual, quedan 6.8 meses de runway.',time:'Hace 2h',urgent:true},
    {id:2,icon:'lab',title:'Sesión de Laboratorio mañana 14:00',desc:'Con Ana Gómez · Cafetería El Roble. Brief pre-llenado listo.',time:'Hace 3h',urgent:true},
    {id:3,icon:'user',title:'Carlos Pérez aceptó la invitación',desc:'Ahora tiene acceso colaborador a Cafetería El Roble.',time:'Ayer',urgent:false},
    {id:4,icon:'ai',title:'Nuevos hallazgos detectados',desc:'3 hallazgos nuevos en Cafetería El Roble — AR Days subieron.',time:'Hace 2 días',urgent:false},
  ];
  var [dismissed,setDismissed] = React.useState([]);
  var visible = items.filter(function(n){return dismissed.indexOf(n.id)<0;});
  return (
    <div style={{padding:'20px 24px',maxWidth:'640px'}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:'16px'}}>
        <h2 style={{fontSize:'15px',fontWeight:600,color:'var(--t1)',margin:0}}>Notificaciones</h2>
        <button onClick={function(){setDismissed(items.map(function(i){return i.id;}));}} style={{fontSize:'12px',color:'var(--t3)',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font)'}}>Descartar todas</button>
      </div>
      {visible.length===0?<div style={{textAlign:'center',padding:'48px 0'}}><p style={{fontSize:'13px',color:'var(--t3)'}}>Sin notificaciones pendientes.</p></div>:
        <div style={{display:'flex',flexDirection:'column',gap:'8px'}}>
          {visible.map(function(n){return(
            <div key={n.id} style={{display:'flex',gap:'12px',padding:'14px 16px',background:'var(--glass-bg)',backdropFilter:'var(--glass-blur)',border:'0.5px solid '+(n.urgent?'rgba(217,119,6,0.3)':'var(--glass-border)'),borderRadius:'var(--radius-card)',animation:'fadeInUp 0.2s ease'}}>
              <span style={{lineHeight:0,flexShrink:0,marginTop:'2px',color:'var(--t2)'}}>
  {n.icon==='warn'&&<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9 2.5L16.5 15H1.5L9 2.5Z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/><path d="M9 7.5v3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/><circle cx="9" cy="12.5" r=".75" fill="currentColor"/></svg>}
  {n.icon==='lab'&&<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M7.5 3v5.5L2.5 16a.8.8 0 00.7 1.2h11.6a.8.8 0 00.7-1.2L11 8.5V3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/><path d="M7 3h4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>}
  {n.icon==='user'&&<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><circle cx="9" cy="6" r="3.5" stroke="currentColor" strokeWidth="1.4"/><path d="M3 16c0-3.3 2.7-6 6-6s6 2.7 6 6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>}
  {n.icon==='ai'&&<svg width="18" height="18" viewBox="0 0 18 18" fill="none"><path d="M9 1.5l1.5 4.8L15.5 5l-2.5 3.5L17 10l-4.5 1.2L14.5 16 9 13.5l-5.5 2.5 2-4.8L1 10l4.5-1.5L3 5l4.5 1.3L9 1.5z" stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round"/></svg>}
</span>
              <div style={{flex:1}}>
                <p style={{fontSize:'13px',fontWeight:600,color:'var(--t1)',margin:'0 0 3px'}}>{n.title}</p>
                <p style={{fontSize:'12px',color:'var(--t2)',margin:'0 0 6px',lineHeight:1.5}}>{n.desc}</p>
                <span style={{fontSize:'10.5px',color:'var(--t3)'}}>{n.time}</span>
              </div>
              <button onClick={function(){setDismissed(function(d){return d.concat([n.id]);});}} style={{background:'none',border:'none',cursor:'pointer',color:'var(--t3)',fontSize:'16px',lineHeight:1,padding:'2px',flexShrink:0}}>×</button>
            </div>
          );})}
        </div>
      }
    </div>
  );
}

/* ─── CONFIGURACION VIEW ─────────────────────────────────────────────────── */
function ConfiguracionView({ onLogout }) {
  return (
    <div style={{padding:'20px 24px',maxWidth:'560px'}}>
      <h2 style={{fontSize:'15px',fontWeight:600,color:'var(--t1)',marginBottom:'16px'}}>Configuración de cuenta</h2>
      {[['Nombre','Isai Campo'],['Email','isai@negocio.com'],['Plan','Profesional · $29/mes'],['Moneda base','USD'],].map(function(row){return(
        <div key={row[0]} style={{display:'flex',justifyContent:'space-between',alignItems:'center',padding:'13px 0',borderBottom:'0.5px solid var(--border)'}}>
          <span style={{fontSize:'13px',color:'var(--t2)'}}>{row[0]}</span>
          <div style={{display:'flex',gap:'10px',alignItems:'center'}}>
            <span style={{fontSize:'13px',fontWeight:500,color:'var(--t1)'}}>{row[1]}</span>
            <button style={{fontSize:'12px',color:'var(--accent)',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font)',fontWeight:500}}>Editar</button>
          </div>
        </div>
      );})}
      <div style={{marginTop:'20px'}}>
        <button onClick={onLogout} style={{padding:'10px 20px',borderRadius:'var(--radius-tag)',background:'none',border:'0.5px solid rgba(220,38,38,0.3)',color:'#DC2626',fontSize:'13px',cursor:'pointer',fontFamily:'var(--font)',fontWeight:500}}>Cerrar sesión</button>
      </div>
    </div>
  );
}

/* ─── APP ROOT ───────────────────────────────────────────────────────────── */
function WaitlistToast() {
  var [show,setShow] = React.useState(false);
  React.useEffect(function(){
    var hideTimer;
    var showTimer = setTimeout(function(){
      setShow(true);
      hideTimer = setTimeout(function(){ setShow(false); }, 10000);
    }, 10000);
    return function(){ clearTimeout(showTimer); clearTimeout(hideTimer); };
  },[]);
  if(!show) return null;
  return (
    <a href="Lista de Espera.html#unirme" style={{position:'fixed',left:'12px',right:'12px',bottom:'82px',zIndex:130,display:'flex',alignItems:'center',gap:'10px',padding:'12px 14px',borderRadius:'100px',background:'#F97316',border:'0.5px solid rgba(255,255,255,0.28)',boxShadow:'0 12px 36px rgba(249,115,22,0.34),0 0 0 0.5px rgba(255,255,255,0.20) inset',textDecoration:'none',animation:'fadeInUp 0.3s ease',maxWidth:'460px',margin:'0 auto'}}>
      <span style={{width:'7px',height:'7px',borderRadius:'50%',background:'#1a1206',flexShrink:0,marginLeft:'4px'}}/>
      <span style={{flex:1,fontSize:'12.5px',color:'#1a1206',lineHeight:1.35,letterSpacing:'-0.01em'}}>¿Te interesa? <strong style={{fontWeight:600}}>Agrégame a la lista de espera</strong></span>
      <button onClick={function(e){e.preventDefault();e.stopPropagation();setShow(false);}} aria-label="Cerrar" style={{background:'none',border:'none',cursor:'pointer',color:'rgba(26,18,6,0.55)',fontSize:'17px',lineHeight:1,padding:'2px 6px',flexShrink:0,fontFamily:'var(--font)'}}>×</button>
    </a>
  );
}

function App() {
  var [tweaks,setTweak]               = useTweaks(window.TWEAK_DEFAULTS);  var [screen,setScreen]              = React.useState('app');
  var [authView,setAuthView]          = React.useState(null);
  var [view,setView]                  = React.useState('consolidado');
  var [empresaId,setEmpresaId]        = React.useState(null);
  var [empresaSection,setEmpresaSection] = React.useState('resumen');
  var [acciones,setAcciones]          = React.useState(BASE_ACCIONES);
  var [period]                        = React.useState('Diciembre 2024');
  var [drawerOpen,setDrawerOpen]      = React.useState(false);
  var [quickAdd,setQuickAdd]          = React.useState(false);

  var darkMode = tweaks.oscuro === true;

  React.useEffect(function(){
    document.body.className = '';
  },[]);

  var goToApp  = function(){ setScreen('app'); setAuthView(null); };
  var goLogout = function(){ window.location.href = 'Lista de Espera.html'; };

  var enterEmpresa = function(id){ setEmpresaId(id); setEmpresaSection('resumen'); };
  var exitEmpresa  = function(){   setEmpresaId(null); setView('consolidado'); };

  /* ── Public routes ── */
  if(screen==='landing'&&!authView) return <LandingPage onLogin={function(){setAuthView('login');}} onRegister={function(){setAuthView('register');}} onConsultores={function(){setAuthView('consultores');}} onDemo={goToApp}/>;
  if(authView==='consultores')  return <ConsultoresPage onBack={function(){setAuthView(null);}}/>;
  if(authView==='login')        return <LoginPage    onBack={function(){setAuthView(null);}} onSuccess={goToApp}    onRegister={function(){setAuthView('register');}}/>;
  if(authView==='register')     return <RegisterPage onBack={function(){setAuthView(null);}} onSuccess={function(){setAuthView('onboarding');}} onLogin={function(){setAuthView('login');}}/>;
  if(authView==='onboarding')   return <OnboardingPage onComplete={goToApp} onSkip={goToApp}/>;

  /* ── App shell ── */
  return (
    <div style={{display:'flex',height:'100vh',overflow:'hidden'}}>
      <Sidebar
        view={view} setView={function(v){setView(v);setEmpresaId(null);}}
        empresaId={empresaId} empresaSection={empresaSection} setEmpresaSection={setEmpresaSection}
        onBack={exitEmpresa} darkMode={darkMode}
        onToggleDark={function(){setTweak('oscuro',!darkMode);}}
        onLogout={goLogout} period={period}/>
      <div className="app-main" style={{flex:1,overflow:'hidden',display:'flex',flexDirection:'column'}}>
        {/* Main content */}
        {empresaId
          ? <EmpresaShell companyId={empresaId} section={empresaSection} setSection={setEmpresaSection} onBack={exitEmpresa} setView={setView}/>
          : <>
              {view==='consolidado'    && <ConsolidadoView onSelectEmpresa={enterEmpresa} setView={setView}/>}
              {view==='laboratorio'    && <LaboratorioView setView={setView}/>}
              {view==='notificaciones' && <NotificacionesView/>}
              {view==='configuracion'  && <ConfiguracionView onLogout={goLogout}/>}
              {view==='ingresar'       && <IngresoView setView={setView}/>}
              {view==='hallazgos'      && <HallazgosView period={period} setView={setView}/>}
              {view==='plan'           && <PlanAccionView period={period} setView={setView} acciones={acciones} setAcciones={setAcciones}/>}
              {view==='contexto'       && <ContextoView/>}
            </>
        }
      </div>

      {/* Mobile drawer + topbar */}
      <MobileDrawer view={view} setView={function(v){setView(v);setEmpresaId(null);}} empresaId={empresaId} empresaSection={empresaSection} setEmpresaSection={setEmpresaSection} darkMode={darkMode} onToggleDark={function(){setTweak('oscuro',!darkMode);}} onLogout={goLogout} open={drawerOpen} onClose={function(){setDrawerOpen(false);}}/>
      <div className="mobile-topbar" style={{display:'none',position:'fixed',top:0,left:0,right:0,height:'50px',background:'var(--glass-sidebar-bg)',backdropFilter:'var(--glass-blur)',WebkitBackdropFilter:'var(--glass-blur)',borderBottom:'0.5px solid rgba(255,255,255,0.5)',zIndex:90,alignItems:'center',padding:'0 16px',gap:'12px',justifyContent:'space-between'}}>
        <a href="Lista de Espera.html" title="Volver a la página inicial" style={{width:'32px',height:'32px',borderRadius:'50%',display:'flex',alignItems:'center',justifyContent:'center',color:'var(--t2)',textDecoration:'none',background:'var(--glass-bg-atmo)',border:'0.5px solid var(--glass-border)',flexShrink:0}}>
          <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M8.5 3L4.5 7l4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
        </a>
        <div style={{display:'flex',alignItems:'center',gap:'7px'}}>
          <div style={{width:'24px',height:'24px',background:'var(--accent)',borderRadius:'7px',display:'flex',alignItems:'center',justifyContent:'center'}}><svg width="10" height="10" viewBox="0 0 12 12" fill="none"><path d="M6 1v10M1 6h10" stroke="var(--accent-text)" strokeWidth="2" strokeLinecap="round"/></svg></div>
          <span style={{fontSize:'12.5px',fontWeight:600,color:'var(--t1)'}}>Mi Negocio en Números</span>
        </div>
        <button onClick={function(){setDrawerOpen(true);}} style={{background:'none',border:'none',cursor:'pointer',color:'var(--t2)',display:'flex',flexDirection:'column',gap:'3.5px',padding:'4px',flexShrink:0}}>
          {[0,1,2].map(function(i){return <span key={i} style={{display:'block',width:'17px',height:'1.5px',background:'currentColor',borderRadius:'1px'}}/>;} )}
        </button>
      </div>

      {/* Floating + (desktop) */}
      {quickAdd && <QuickAddModal companyId={empresaId} onClose={function(){setQuickAdd(false);}}/>}
      <button className="desktop-fab" onClick={function(){setQuickAdd(true);}} style={{position:'fixed',bottom:'24px',right:'24px',width:'50px',height:'50px',borderRadius:'50%',background:'rgba(36,36,36,0.88)',backdropFilter:'blur(16px)',WebkitBackdropFilter:'blur(16px)',border:'0.5px solid rgba(255,255,255,0.15)',color:'#f6f3f1',fontSize:'24px',fontWeight:300,cursor:'pointer',boxShadow:'0 8px 28px rgba(0,0,0,0.22),0 0 0 0.5px rgba(255,255,255,0.08) inset',zIndex:100,display:'flex',alignItems:'center',justifyContent:'center',lineHeight:1,transition:'transform 0.15s,box-shadow 0.15s'}}
        onMouseEnter={function(e){e.currentTarget.style.transform='scale(1.08)';e.currentTarget.style.boxShadow='0 12px 36px rgba(0,0,0,0.3),0 0 0 0.5px rgba(255,255,255,0.12) inset';}}
        onMouseLeave={function(e){e.currentTarget.style.transform='none';e.currentTarget.style.boxShadow='0 8px 28px rgba(0,0,0,0.22),0 0 0 0.5px rgba(255,255,255,0.08) inset';}}>+</button>

      {/* Floating mobile nav */}
      <MobileNav view={view} empresaId={empresaId} onNav={function(v){setEmpresaId(null);setView(v);}} onAdd={function(){setQuickAdd(true);}} onMenu={function(){setDrawerOpen(true);}}/>

      <WaitlistToast/>
    </div>
  );
}

/* ─── MOUNT ──────────────────────────────────────────────────────────────── */
var root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App/>);
