// Layout — Full OM GROUP logo in sidebar
const { useState: uSt, useEffect: uEf, useContext: uCtx, useRef: uRf } = React;

const Icons = {
  dashboard: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg>,
  reports:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 20V10M12 20V4M6 20v-6"/></svg>,
  materials: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/></svg>,
  customers: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75"/></svg>,
  vendors:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>,
  crusher:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 010 14.14M4.93 4.93a10 10 0 000 14.14"/></svg>,
  sales:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/></svg>,
  purchases: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>,
  transport: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="1" y="3" width="15" height="13" rx="1"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>,
  rates:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>,
  diesel:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2.69l5.66 5.66a8 8 0 11-11.31 0z"/></svg>,
  companies: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 21h18M9 8h1m-1 4h1m4-4h1m-1 4h1M5 21V5a2 2 0 012-2h10a2 2 0 012 2v16"/></svg>,
  users:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>,
  audit:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>,
  datahealth: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M8 12h2l1.5 3 2-6L15 12h1"/></svg>,
  transfers:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 014-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 01-4 4H3"/></svg>,
  stockyard:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/></svg>,
  rmcplants:  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="7" width="20" height="14" rx="1"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/><line x1="12" y1="12" x2="12" y2="16"/><line x1="10" y1="14" x2="14" y2="14"/></svg>,
  debris:     <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>,
  tmmaster:   <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="1" y="3" width="15" height="13" rx="1"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/><line x1="4" y1="8" x2="11" y2="8"/><line x1="4" y1="11" x2="9" y2="11"/></svg>,
  calendar:    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><rect x="7" y="14" width="3" height="3" rx="0.5"/><rect x="13" y="14" width="3" height="3" rx="0.5"/></svg>,
  priceorders:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="12" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/></svg>,
  settlement:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M16 10c0 1.1-.9 2-2 2H10a2 2 0 010-4h4a2 2 0 012 2z"/><line x1="2" y1="10" x2="22" y2="10"/></svg>,
  settlementpolicy:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 2a5 5 0 00-5 5v2H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2v-9a2 2 0 00-2-2h-2V7a5 5 0 00-5-5z"/><circle cx="12" cy="16" r="1.5" fill="currentColor"/><line x1="12" y1="12" x2="12" y2="14"/></svg>,
  analytics: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 3v16a2 2 0 002 2h16"/><path d="M7 15l3.5-4.5 3 2.5L18 7"/><circle cx="18" cy="7" r="1.6" fill="currentColor" stroke="none"/></svg>,
  vendorsettlement:<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><path d="M9 22V12h6v10"/><path d="M9 15h6"/></svg>,
};

const NAV = [
  { id:'dashboard',  label:'Dashboard',      icon:'dashboard'  },
  { id:'calendar',   label:'Calendar',       icon:'calendar'   },
  { id:'analytics',  label:'Analytics',      icon:'analytics', guard:'IntelCenterPage' },
  { id:'reports',    label:'Reports',        icon:'reports'    },
  { id:'materials',  label:'Materials',      icon:'materials'  },
  { id:'customers',  label:'Customers',      icon:'customers'  },
  { id:'vendors',    label:'Vendors',        icon:'vendors'    },
  { id:'crusher',    label:'Crusher',        icon:'crusher'    },
  { id:'priceorders',label:'Price Orders',    icon:'priceorders'},
  { id:'sales',      label:'Sales Orders',   icon:'sales'      },
  { id:'purchases',  label:'Purchases',        icon:'purchases'  },
  { id:'vendorsettlement', label:'Vendor Settlement', icon:'vendorsettlement' },
  { id:'transfers',  label:'Internal Transfers',icon:'transfers'  },
  { id:'debris',     label:'Debris Movement',   icon:'debris'     },
  { id:'stockyard',  label:'Stockyard',          icon:'stockyard'  },
  { id:'rmcplants',        label:'RMC Plants',         icon:'rmcplants'  },
  { id:'transportermaster', label:'Transporter Master', icon:'tmmaster'   },
  { id:'transport',          label:'Transporter Reports',   icon:'transport'   },
  { id:'transportsettlement', label:'Transporter Settlement', icon:'settlement'  },
  { id:'settlementpolicy',    label:'Settlement Policy',      icon:'settlementpolicy'},
  { id:'rates',               label:'Transport Rates',        icon:'rates'       },
  { id:'diesel',     label:'Diesel',         icon:'diesel'     },
  { id:'companies',  label:'Companies',      icon:'companies'  },
  { id:'users',      label:'Users',          icon:'users'      },
  { id:'audit',      label:'Audit Logs',     icon:'audit'      },
  { id:'datahealth', label:'Data Health',    icon:'datahealth', guard:'DataHealthPage' },
];

function Sidebar({ page, navigate, open, onClose }) {
  const { setCompany } = uCtx(window.AppCtx);
  function goToGroup() { setCompany('group'); navigate('dashboard'); onClose(); }
  return (
    <>
      {open && <div className="sb-overlay open" onClick={onClose} />}
      <aside className={`sb${open ? ' open' : ''}`}>
        {/* Full OM GROUP logo */}
        <div className="sb-brand om-logo-wrap" style={{padding:'12px 8px 8px',cursor:'pointer'}} onClick={goToGroup} title="Go to OM Group Dashboard">
          <img
            src="uploads/OM GROUP FULL LOGO-61ed36bc.png"
            alt="OM Group"
            style={{width:'90px',height:'auto',objectFit:'contain',display:'block'}}
            onError={e => {
              e.target.style.display='none';
              e.target.nextSibling.style.display='block';
            }}
          />
          <span style={{display:'none',fontSize:11,fontWeight:700,color:'var(--or)',textAlign:'center'}}>OM GROUP</span>
        </div>
        <nav className="sb-nav">
          {NAV.filter(n => !n.guard || window[n.guard]).map(n => (
            <div key={n.id} className={`nav-it${page===n.id?' act':''}`}
              onClick={()=>{navigate(n.id);onClose();}} title={n.label}>
              {Icons[n.icon]}
              <span>{n.label}</span>
            </div>
          ))}
        </nav>
        <div className="sb-foot">OM ERP v1.0</div>
      </aside>
    </>
  );
}

function TopBar({ page, session, onHam, onLogout }) {
  const { companyId, setCompany } = uCtx(window.AppCtx);
  const [coOpen, setCoOpen] = uSt(false);
  const [udOpen, setUdOpen] = uSt(false);
  const [undoAvail, setUndoAvail] = uSt(false);
  const [companies, setCompanies] = uSt(()=>Store.all('companies'));
  const coRef = uRf(); const udRef = uRf();
  const coPanelRef = uRf(); const udPanelRef = uRf();
  const [profileOpen, setProfileOpen] = uSt(false);

  // Keep company list in sync with store (create/update/delete)
  uEf(()=>{
    const unsub = Store.on(()=>setCompanies(Store.all('companies')));
    return unsub;
  },[]);

  // If currently selected company was deleted, fall back to group
  uEf(()=>{
    if(companyId && companyId!=='group' && !companies.find(c=>c.id===companyId)){
      setCompany('group');
    }
  },[companies, companyId, setCompany]);
  const userCos = session?.userRole==='SUPER_ADMIN'
    ? companies
    : companies.filter(c=>{const u=Store.byId('users',session?.userId);return u?.companies?.includes(c.id);});
  const currentCo = Store.currentCompany;
  const isGroupMode = companyId === 'group';
  const allDisplayCos = session?.userRole==='SUPER_ADMIN'
    ? [{id:'group',name:'OM GROUP',isGroup:true}, ...userCos]
    : userCos;
  const initials = session?.userName?.split(' ').map(w=>w[0]).join('').slice(0,2)||'U';

  const PAGE_LABELS = {
    dashboard: isGroupMode ? 'OM Group Dashboard' : 'Dashboard',
    calendar: 'OM Group Calendar',
    analytics: 'Analytics & Intelligence Center',
    reports:'Reports',materials:'Materials',customers:'Customers',
    vendors:'Vendors',crusher:'Crusher',priceorders:'Price Orders',sales:'Sales Orders',purchases:'Purchases',
    transfers:'Internal Transfers',stockyard:'Stockyard Management',transportermaster:'Transporter Master',transport:'Transporter Reports',rates:'Transport Rates',diesel:'Diesel',
    rmcplants:'RMC Plants',debris:'Debris Movement',
    companies:'Companies',users:'Users',audit:'Audit Logs',
  };

  uEf(()=>{
    const unsub = Store.on(()=>setUndoAvail(!!(Store.data._lastDeleted)));
    return unsub;
  },[]);

  uEf(()=>{
    const h = e => {
      if (coRef.current&&!coRef.current.contains(e.target)&&coPanelRef.current&&!coPanelRef.current.contains(e.target)) setCoOpen(false);
      if (udRef.current&&!udRef.current.contains(e.target)&&udPanelRef.current&&!udPanelRef.current.contains(e.target)) setUdOpen(false);
    };
    document.addEventListener('mousedown',h);
    return ()=>document.removeEventListener('mousedown',h);
  },[]);

  function handleUndo() {
    const last = Store.data._lastDeleted;
    if (!last) return;
    Store.add(last.entity, last.item);
    Store.data._lastDeleted = null;
    Store.save('_lastDeleted');
    window.toast&&window.toast('Record restored','ok');
  }

  return (
    <header className="topbar">
      <button className="ham" onClick={onHam}>
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
        </svg>
      </button>
      <img src="./new-project-2--mr6p8rg2.png" alt="logo" style={{maxWidth:'100%',height:'35px',display:'block',objectFit:'cover',width:'36px',alignSelf:'center',opacity:0.4}}/>
      <div className="topbar-brand" style={{display:'flex',alignItems:'flex-end',gap:'10px',alignSelf:'flex-end',paddingBottom:'14px'}}>
        <div style={{display:'flex',flexDirection:'column',gap:'5px',lineHeight:1}}>
          <span style={{fontFamily:"'Inter','SF Pro Display',system-ui,sans-serif",fontSize:'15px',fontWeight:800,color:'#111111',letterSpacing:'0.05em',whiteSpace:'nowrap',lineHeight:1}}>OM GROUP ERP</span>
          <span style={{fontFamily:"'Inter','SF Pro Display',system-ui,sans-serif",fontSize:'8px',fontWeight:400,color:'#6B7280',letterSpacing:'0.005em',whiteSpace:'nowrap',lineHeight:1,fontStyle:'italic'}}>Enterprise Resource Platform</span>
        </div>
      </div>
      <div className="topbar-right">
        <button className="undo-btn" onClick={handleUndo} disabled={!undoAvail}>
          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 14L4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 010 11H11"/></svg>
          Undo Delete
        </button>
        <div ref={coRef} style={{position:'relative'}}>
          <div className={`co-chip${coOpen?' open':''}`} onClick={()=>setCoOpen(p=>!p)} title={isGroupMode ? 'OM Group' : currentCo?.name}>
            <div className="co-chip-logo">
              {isGroupMode
                ? <img src="uploads/OM GROUP ONLY LOGO-9de09387.png" alt="OM Group"/>
                : currentCo?.logo
                  ? <img src={currentCo.logo} alt=""/>
                  : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 21h18M9 8h1m-1 4h1m4-4h1m-1 4h1M5 21V5a2 2 0 012-2h10a2 2 0 012 2v16"/></svg>
              }
            </div>
            <span className="co-chip-name" style={{fontWeight:800}}>{isGroupMode ? 'OM GROUP' : currentCo?.name}</span>
            <svg className="co-chip-chevron" width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
          </div>
          <window.FloatingLayer anchorRef={coRef} open={coOpen} align="right" offset={6} minWidth={220} panelRef={coPanelRef}
            style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:14,boxShadow:'var(--sh-drop)',overflow:'hidden',maxWidth:'calc(100vw - 20px)',maxHeight:'min(70vh, 420px)',overflowY:'auto',WebkitOverflowScrolling:'touch',paddingBottom:'env(safe-area-inset-bottom)'}}>
              <div className="co-drop-hd">Switch Company</div>
              {allDisplayCos.map(c=>(
                <div key={c.id} className={`co-drop-it${c.id===companyId?' cur':''}`}
                  style={c.isGroup?{background:c.id===companyId?'var(--or-lt)':'#FFFBF5',borderBottom:'1px solid var(--bdr)',fontWeight:700}:{}}
                  onClick={()=>{setCompany(c.id);setCoOpen(false);}}>
                  {c.id===companyId&&<svg className="co-drop-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--or)" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 13l4 4L19 7"/></svg>}
                  <div className="co-drop-logo">
                    {c.isGroup&&<img src="uploads/OM GROUP ONLY LOGO-9de09387.png" alt="OM Group"/>}
                    {!c.isGroup&&c.logo&&<img src={c.logo} alt=""/>}
                  </div>
                  <span className="co-chip-name">{c.name}</span>
                </div>
              ))}
          </window.FloatingLayer>
        </div>
        <div className="ud-wrap" ref={udRef}>
          <div className="av" onClick={()=>setUdOpen(p=>!p)}>{initials}</div>
          <window.FloatingLayer anchorRef={udRef} open={udOpen} align="right" offset={6} minWidth={180} panelRef={udPanelRef}
            style={{background:'#fff',border:'1px solid var(--bdr)',borderRadius:14,boxShadow:'var(--sh-drop)',overflow:'hidden'}}>
              <div className="ud-hd"><div className="ud-name">{session?.userName}</div><div className="ud-role">{session?.userRole?.replace('_',' ')}</div></div>
              <AgentPrefRow />
              <div className="ud-it" onClick={()=>{setUdOpen(false);setProfileOpen(true);}}><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>My Profile</div>
              <div className="ud-it red" onClick={()=>{setUdOpen(false);onLogout();}}><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9"/></svg>Sign Out</div>
          </window.FloatingLayer>
        </div>
      </div>
      {profileOpen&&<UserProfileModal session={session} onClose={()=>setProfileOpen(false)}/>}
    </header>
  );
}

// ── Profile menu → OM Group AI Agent preference ──────────────────────────────
// Reads and writes the shared preference store; the agent listens on the same
// event, so nothing here knows anything about the agent's internals or emotion.
function AgentPrefRow() {
  const [on, setOn] = uSt(() => (window.OMAgentPref ? window.OMAgentPref.get() : true));
  // Derive from the store rather than holding an independent copy: the switch
  // always renders what is actually stored, so UI and preference cannot diverge.
  uEf(() => {
    if (!window.OMAgentPref) return;
    setOn(window.OMAgentPref.get());
    return window.OMAgentPref.subscribe(setOn);
  }, []);
  function toggle(e) {
    e.stopPropagation();
    // The store flips from its own stored value; we never send it a stale one.
    if (window.OMAgentPref) setOn(window.OMAgentPref.toggle());
  }
  return (
    <div className="ud-pref" role="switch" aria-checked={on} tabIndex={0} onClick={toggle}
      onKeyDown={e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle(e);}}}>
      <div className="ud-pref-l">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="4" y="8" width="16" height="12" rx="3"/><path d="M12 8V4M9 14h.01M15 14h.01"/></svg>
        <span>OM Group AI Agent</span>
      </div>
      <div className={'ud-sw' + (on ? ' on' : '')} />
    </div>
  );
}

function AppLayout({ children, page, navigate, session, onLogout }) {
  const [sbOpen, setSbOpen] = uSt(false);
  return (
    <div className="shell">
      <Sidebar page={page} navigate={navigate} open={sbOpen} onClose={()=>setSbOpen(false)} />
      <div className="main">
        <TopBar page={page} session={session} onHam={()=>setSbOpen(p=>!p)} onLogout={onLogout} />
        <main className="pg-body">{children}</main>
      </div>
    </div>
  );
}
window.AppLayout = AppLayout;

// ── User Profile Modal Components ────────────────────────────────────────────
function ProfileSection({ title, children }) {
  return (
    <div style={{marginBottom:14}}>
      <div style={{fontSize:10.5,fontWeight:700,color:'var(--txt2)',textTransform:'uppercase',letterSpacing:'.05em',marginBottom:7,paddingLeft:2}}>{title}</div>
      <div style={{border:'1px solid var(--bdr)',borderRadius:6,overflow:'hidden',background:'#fff'}}>{children}</div>
    </div>
  );
}

function ProfileRow({ label, value, mono, highlight, badge, last }) {
  return (
    <div style={{display:'flex',alignItems:'flex-start',padding:'9px 14px',borderBottom:last?'none':'1px solid #F3F4F6',gap:8,minHeight:38}}>
      <div style={{fontSize:11.5,color:'var(--txt2)',minWidth:130,flexShrink:0,paddingTop:1,lineHeight:1.4}}>{label}</div>
      {badge
        ? <span className={`bdg ${badge}`}>{value||'—'}</span>
        : <div style={{fontSize:12,fontWeight:highlight?600:500,color:highlight?'var(--or)':'var(--txt)',fontFamily:'var(--font)',wordBreak:'break-all',flex:1,lineHeight:1.5}}>{value||'—'}</div>
      }
    </div>
  );
}

function UserProfileModal({ session, onClose }) {
  const [user,   setUser]   = uSt(()=>Store.all('users').find(u=>u.id===session?.userId)||null);
  const [edit,   setEdit]   = uSt(false);
  const [form,   setForm]   = uSt({});
  const [saving, setSaving] = uSt(false);
  const [notifSpeed, setNotifSpeedState] = uSt(()=>window.getNotifSpeed?window.getNotifSpeed():'fast');
  function pickSpeed(v){ window.setNotifSpeed&&window.setNotifSpeed(v); setNotifSpeedState(v); }

  // Stay in sync with store (admin edits user record → profile reflects instantly)
  uEf(()=>{
    const unsub = Store.on(()=>{
      const u = Store.all('users').find(u=>u.id===session?.userId);
      if (u) setUser(u);
    });
    return unsub;
  },[session?.userId]);

  const ROLE_LABELS = {SUPER_ADMIN:'Super Admin',ADMIN:'Admin',MANAGER:'Manager',ACCOUNTANT:'Accountant',OPERATOR:'Operator',VIEWER:'Staff'};
  const companies    = Store.all('companies','group')||[];
  const userCompNames = (user?.companies||[]).map(cid=>companies.find(c=>c.id===cid)?.name).filter(Boolean);
  const initials     = (user?.name||'?').split(' ').filter(Boolean).map(w=>w[0]).join('').slice(0,2).toUpperCase();

  function startEdit(){ setForm({name:user?.name||'',email:user?.email||''}); setEdit(true); }
  function cancelEdit(){ setEdit(false); setForm({}); }

  function saveEdit(){
    if(!(form.name||'').trim()){ window.toast&&window.toast('Name is required','er'); return; }
    if(!(form.email||'').trim()){ window.toast&&window.toast('Email is required','er'); return; }
    setSaving(true);
    setTimeout(()=>{
      Store.update('users',user.id,{name:form.name.trim(),email:form.email.trim()});
      Store.addLog('UPDATE','User Profile','Updated own profile: '+form.name.trim());
      setUser({...user,name:form.name.trim(),email:form.email.trim()});
      setEdit(false); setSaving(false);
      window.toast&&window.toast('Profile updated','ok');
    },400);
  }

  const fmtDt = dt => {
    if(!dt) return '—';
    const date = dt.slice(0,10);
    const time = dt.slice(11,16);
    return (window.fmtDate?window.fmtDate(date):date) + (time?' · '+time:'');
  };

  if(!user) return null;

  return (
    <div className="mbg">
      <div className="mod mod-md">
        <div className="mod-hd">
          <h2>My Profile</h2>
          <button className="mod-x" onClick={onClose}>×</button>
        </div>
        <div className="mod-bd">

          {/* ─ Avatar Header ─ */}
          <div style={{display:'flex',alignItems:'center',gap:14,marginBottom:20,padding:'14px 16px',background:'#FFF7ED',borderRadius:8,border:'1px solid var(--or-bdr)'}}>
            <div style={{width:52,height:52,borderRadius:'50%',background:'var(--or)',color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',fontSize:18,fontWeight:700,flexShrink:0,letterSpacing:'.02em'}}>
              {initials}
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:15,fontWeight:700,color:'var(--txt)',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{user.name}</div>
              <div style={{fontSize:12,color:'var(--or)',fontWeight:600,marginTop:2}}>{ROLE_LABELS[user.role]||user.role}</div>
              <div style={{fontSize:11.5,color:'var(--txt2)',marginTop:1,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>{user.email}</div>
            </div>
            <span className={`bdg ${user.status==='Active'?'bg-gn':'bg-rd'}`} style={{flexShrink:0}}>{user.status||'Active'}</span>
          </div>

          {!edit ? (
            <>
              <ProfileSection title="Personal Information">
                <ProfileRow label="Full Name"     value={user.name}/>
                <ProfileRow label="Email Address" value={user.email} mono last/>
              </ProfileSection>

              <ProfileSection title="Account Information">
                <ProfileRow label="Role"           value={ROLE_LABELS[user.role]||user.role} highlight/>
                <ProfileRow label="Account Status" value={user.status||'Active'} badge={user.status==='Active'?'bg-gn':'bg-rd'}/>
                <ProfileRow label="User ID"        value={(user.id||'').slice(0,12).toUpperCase()} mono last/>
              </ProfileSection>

              <ProfileSection title={`Company Access — ${userCompNames.length} ${userCompNames.length===1?'company':'companies'}`}>
                <div style={{padding:'10px 14px',display:'flex',flexWrap:'wrap',gap:6,minHeight:38}}>
                  {userCompNames.length>0
                    ? userCompNames.map((c,i)=><span key={i} className="bdg bg-or" style={{fontSize:11}}>{c}</span>)
                    : <span style={{fontSize:12,color:'var(--txt3)',fontStyle:'italic'}}>No company access assigned</span>}
                </div>
              </ProfileSection>

              <ProfileSection title="Activity">
                <ProfileRow label="Last Login"   value={fmtDt(user.lastLogin)}/>
                <ProfileRow label="Member Since" value={user.createdAt?(window.fmtDate?window.fmtDate(user.createdAt.slice(0,10)):user.createdAt.slice(0,10)):'—'} last/>
              </ProfileSection>

              <ProfileSection title="Notification Speed">
                <div style={{padding:'10px 14px'}}>
                  <div style={{fontSize:11.5,color:'var(--txt2)',marginBottom:9,lineHeight:1.5}}>How long success confirmations stay on screen. Errors always stay until dismissed.</div>
                  <div style={{display:'flex',gap:6}}>
                    {[{v:'standard',l:'Standard',s:'2.0s'},{v:'fast',l:'Fast',s:'0.8s'},{v:'highspeed',l:'High-Speed Entry',s:'0.55s'}].map(o=>(
                      <button key={o.v} type="button" onClick={()=>pickSpeed(o.v)}
                        style={{flex:1,padding:'8px 6px',borderRadius:7,border:notifSpeed===o.v?'1.5px solid var(--or)':'1.5px solid var(--bdr)',background:notifSpeed===o.v?'#FFF7ED':'#fff',cursor:'pointer',textAlign:'center'}}>
                        <div style={{fontSize:12,fontWeight:700,color:notifSpeed===o.v?'var(--or)':'var(--txt)'}}>{o.l}</div>
                        <div style={{fontSize:10.5,color:'var(--txt3)',marginTop:1}}>{o.s}</div>
                      </button>
                    ))}
                  </div>
                </div>
              </ProfileSection>
            </>
          ) : (
            <div>
              <div style={{color:'var(--or)',fontWeight:700,fontSize:12,marginBottom:12,paddingBottom:7,borderBottom:'2px solid #FEF3E8'}}>Edit Personal Information</div>
              <div className="fld" style={{marginBottom:12}}>
                <label>Full Name <span className="req">*</span></label>
                <input className="inp" value={form.name||''} onChange={e=>setForm(p=>({...p,name:e.target.value}))} placeholder="Full name" autoFocus/>
              </div>
              <div className="fld" style={{marginBottom:16}}>
                <label>Email Address <span className="req">*</span></label>
                <input className="inp" type="email" value={form.email||''} onChange={e=>setForm(p=>({...p,email:e.target.value}))} placeholder="Email address"/>
              </div>
              <div style={{background:'#EFF6FF',border:'1px solid #BFDBFE',borderRadius:5,padding:'9px 12px',fontSize:11.5,color:'#1E40AF',lineHeight:1.6}}>
                <strong>Note:</strong> Role, permissions, and company access can only be modified by an administrator.
              </div>
            </div>
          )}
        </div>

        <div className="mod-ft">
          {!edit ? (
            <>
              <button className="btn btn-wh" onClick={onClose}>Close</button>
              <button className="btn btn-or" onClick={startEdit}>
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                Edit Profile
              </button>
            </>
          ) : (
            <>
              <button className="btn btn-gh" onClick={cancelEdit}>Cancel</button>
              <button className="btn btn-or" onClick={saveEdit} disabled={saving}>{saving?'Saving…':'Save Changes'}</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
