// Sidebar + topbar shell for the MarketForge app.

const NAV_SECTIONS = [
  {
    group: 'TWIN',
    items: [
      { key: 0, label: 'Overview',    num: '01', icon: 'home' },
      { key: 1, label: 'My role',     num: '02', icon: 'user' },
      { key: 2, label: 'Profile',     num: '03', icon: 'id' },
      { key: 3, label: 'Dashboard',   num: '04', icon: 'grid' },
    ],
  },
  {
    group: 'MATCHING',
    items: [
      { key: 4, label: 'Match report', num: '05', icon: 'link', badge: '1' },
      { key: 5, label: 'Identity reveal', num: '06', icon: 'lock' },
      { key: 6, label: 'Deal brief',   num: '07', icon: 'doc' },
    ],
  },
  {
    group: 'WORKSPACE',
    items: [
      { key: 'sim',  label: 'Simulations',  num: '·',  icon: 'sim',  count: '12' },
      { key: 'ks',   label: 'KnowledgeSlot',num: '·',  icon: 'book', count: '3' },
      { key: 'aud',  label: 'Audit log',    num: '·',  icon: 'hist' },
      { key: 'set',  label: 'Settings',     num: '·',  icon: 'gear' },
    ],
    disabled: true,
  },
];

function NavIcon({ kind }) {
  const props = { width: 13, height: 13, viewBox: '0 0 13 13', fill: 'none', stroke: 'currentColor', strokeWidth: 1.2 };
  switch (kind) {
    case 'home': return <svg {...props}><path d="M2 6 L6.5 2 L11 6 V11 H2 Z"/><path d="M5 11 V8 H8 V11"/></svg>;
    case 'user': return <svg {...props}><circle cx="6.5" cy="4.5" r="2"/><path d="M2.5 11 a4 3 0 0 1 8 0"/></svg>;
    case 'id':   return <svg {...props}><rect x="1.5" y="2.5" width="10" height="8"/><circle cx="4.5" cy="6.2" r="1.2"/><line x1="7" y1="5" x2="10" y2="5"/><line x1="7" y1="7" x2="10" y2="7"/></svg>;
    case 'grid': return <svg {...props}><rect x="1.5" y="1.5" width="4" height="4"/><rect x="7.5" y="1.5" width="4" height="4"/><rect x="1.5" y="7.5" width="4" height="4"/><rect x="7.5" y="7.5" width="4" height="4"/></svg>;
    case 'link': return <svg {...props}><rect x="1.5" y="4" width="5" height="5" rx="1"/><rect x="6.5" y="4" width="5" height="5" rx="1"/><line x1="4" y1="6.5" x2="9" y2="6.5"/></svg>;
    case 'lock': return <svg {...props}><rect x="2.5" y="5.5" width="8" height="6"/><path d="M4 5.5 V3.5 a2.5 2.5 0 0 1 5 0 V5.5"/></svg>;
    case 'doc':  return <svg {...props}><path d="M3 1.5 H8 L10.5 4 V11.5 H3 Z"/><line x1="4.5" y1="6" x2="9" y2="6"/><line x1="4.5" y1="8" x2="9" y2="8"/><line x1="4.5" y1="10" x2="7" y2="10"/></svg>;
    case 'sim':  return <svg {...props}><circle cx="6.5" cy="6.5" r="4.5"/><line x1="6.5" y1="2" x2="6.5" y2="11"/><path d="M2 6.5 a6 2 0 0 0 9 0" /></svg>;
    case 'book': return <svg {...props}><path d="M2 2 H10 V11 H2 Z"/><line x1="2" y1="4" x2="10" y2="4"/></svg>;
    case 'hist': return <svg {...props}><circle cx="6.5" cy="6.5" r="4.5"/><polyline points="6.5,4 6.5,6.5 8.5,8"/></svg>;
    case 'gear': return <svg {...props}><circle cx="6.5" cy="6.5" r="1.6"/><path d="M6.5 1.5 V3 M6.5 10 V11.5 M1.5 6.5 H3 M10 6.5 H11.5 M3 3 L4 4 M9 9 L10 10 M3 10 L4 9 M9 4 L10 3"/></svg>;
    default: return null;
  }
}

function Sidebar({ screen, onGo, role, user, onSwitchRole, onLogout }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const roleOpts = [
    { key: 'shop',      label: 'Machine Shop',  sub: 'Joana Mendes · Ardent' },
    { key: 'buyer',     label: 'Buyer',         sub: 'Lena Park · Helios' },
    { key: 'inspector', label: 'Inspector',     sub: 'Dmitri Volkov · Meridian' },
  ];
  return (
    <aside className="mf-sidebar">
      {NAV_SECTIONS.map(section => (
        <div key={section.group}>
          <div className="sb-group">
            {section.group}
            {section.group === 'TWIN' && (
              <span style={{ float: 'right', color: 'var(--accent)' }}>live</span>
            )}
          </div>
          {section.items.map(item => {
            const active = !section.disabled && screen === item.key;
            return (
              <div
                key={item.key}
                className={`sb-item ${active ? 'active' : ''}`}
                onClick={() => { if (!section.disabled && typeof item.key === 'number') onGo(item.key); }}
                style={{ opacity: section.disabled ? 0.55 : 1, cursor: section.disabled ? 'not-allowed' : 'pointer' }}
              >
                <span className="num">{item.num}</span>
                <span className="icon"><NavIcon kind={item.icon} /></span>
                <span>{item.label}</span>
                {item.badge && <span className="bd">{item.badge}</span>}
                {item.count && (
                  <span style={{
                    marginLeft: 'auto', fontSize: 10, color: 'var(--ink-4)',
                    fontFamily: 'var(--mono)',
                  }}>{item.count}</span>
                )}
              </div>
            );
          })}
        </div>
      ))}

      <div className="sb-foot" style={{ position: 'relative' }}>
        {menuOpen && onSwitchRole && (
          <div className="sb-menu" onClick={(e) => e.stopPropagation()}>
            <div className="sb-menu-hd">
              <span className="mono-lbl">Switch persona · demo</span>
            </div>
            {roleOpts.map(r => (
              <div key={r.key}
                className={`sb-menu-item ${role === r.key ? 'on' : ''}`}
                onClick={() => { onSwitchRole(r.key); setMenuOpen(false); }}>
                <div className="av">{
                  { shop:'JM', buyer:'LP', inspector:'DV' }[r.key]
                }</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="lbl">{r.label}</div>
                  <div className="sub">{r.sub}</div>
                </div>
                {role === r.key && <span style={{ color: 'var(--accent)' }}>●</span>}
              </div>
            ))}
            <div className="sb-menu-divider" />
            <div className="sb-menu-item logout" onClick={() => { setMenuOpen(false); onLogout && onLogout(); }}>
              <div className="av logout-av">↩</div>
              <div style={{ flex: 1 }}>
                <div className="lbl">Log out</div>
                <div className="sub">Return to landing page</div>
              </div>
            </div>
          </div>
        )}
        <div className="usr" onClick={(e) => { e.stopPropagation(); setMenuOpen(o => !o); }}
          style={{ cursor: 'pointer' }}>
          <div className="avatar">{user.initials}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--ink)', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
              {user.name}
            </div>
            <div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 1 }}>
              {user.role}
            </div>
          </div>
          <span style={{ color: 'var(--ink-4)', transform: menuOpen ? 'rotate(180deg)' : 'none', transition: 'transform 160ms' }}>⌄</span>
        </div>
        <div>Org · <span style={{ color: 'var(--ink-2)' }}>{PROFILES[role].name}</span></div>
        <div>Env · <span style={{ color: 'var(--accent)' }}>sim / read-only</span></div>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span>Build 2026.04.22</span>
          {onLogout && (
            <span onClick={onLogout} style={{ color: 'var(--ink-3)', cursor: 'pointer' }}
              onMouseEnter={(e) => e.currentTarget.style.color = 'var(--accent)'}
              onMouseLeave={(e) => e.currentTarget.style.color = 'var(--ink-3)'}>
              log out ↩
            </span>
          )}
        </div>
      </div>
    </aside>
  );
}

function TopBar({ role, screen, user, notifOpen, setNotifOpen }) {
  const crumbTrail = [
    ['Workspace', null],
    [PROFILES[role].name, null],
    [['Overview', 'My role', 'Profile', 'Dashboard', 'Match MF-2026-04-0412', 'Identity reveal', 'Deal brief'][screen], 'current'],
  ];
  return (
    <div className="mf-topbar">
      <div className="logo-slot">
        <span className="mark" />
        <span className="name">MarketForge</span>
        <span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-4)', letterSpacing: '0.1em' }}>
          v2026.04
        </span>
      </div>

      <div className="crumbs">
        {crumbTrail.map(([t, cur], i) => (
          <React.Fragment key={i}>
            {i > 0 && <span className="sep">/</span>}
            <a className={cur ? 'cur' : ''}>{t}</a>
          </React.Fragment>
        ))}
      </div>

      <div className="search">
        <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" strokeWidth="1.2">
          <circle cx="5" cy="5" r="3.5"/><line x1="7.5" y1="7.5" x2="10" y2="10"/>
        </svg>
        <span>Search twin · callsigns, certs, materials</span>
        <span className="kbd">⌘K</span>
      </div>

      <span className="spacer" />

      <span className="session-pill">
        <span className="dot" />
        SIM-4F82A · {PROFILES[role].callsign}
      </span>

      <span className="tb-item" onClick={() => setNotifOpen(!notifOpen)}>
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.2">
          <path d="M3 9 V5.5 a3 3 0 0 1 6 0 V9"/><path d="M2 9 H10"/><path d="M5 10.5 a1 1 0 0 0 2 0"/>
        </svg>
        <span>Activity</span>
        <span className="bd">4</span>
      </span>
      <span className="tb-item">
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.2">
          <circle cx="6" cy="6" r="4.5"/><path d="M4.5 5 a1.5 1.5 0 0 1 3 0 c0 1-1.5 1-1.5 2"/><circle cx="6" cy="9" r="0.4" fill="currentColor"/>
        </svg>
        <span>Help</span>
      </span>
      <span className="tb-item" style={{ paddingRight: 14 }}>
        <div style={{
          width: 20, height: 20, background: 'var(--ink)', color: 'var(--paper)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 9, fontWeight: 600, fontFamily: 'var(--mono)',
        }}>{user.initials}</div>
      </span>
    </div>
  );
}

function NotifPopover({ onClose }) {
  const items = [
    { t: '08:12:04', dot: 'var(--ok)',     title: 'Mutual match opened', body: 'BU-████ cleared all hard requirements · MF-2026-04-0412', tag: 'match' },
    { t: '08:09:18', dot: 'var(--accent)', title: 'KnowledgeSlot applied', body: 'Tolerance field + surface finish signal now scoring', tag: 'ks' },
    { t: '08:04:55', dot: 'var(--info)',   title: 'Identity reveal queued', body: 'Awaiting counterparty consent on MF-2026-04-0388', tag: 'reveal' },
    { t: '07:52:11', dot: 'var(--ink-4)',  title: 'Twin re-simulated', body: '12,478 synthetic entities · 342 deltas since 04:00', tag: 'sync' },
    { t: 'Yday 22:14', dot: 'var(--ink-4)',title: 'New facilitator on market', body: 'Meridian Metrology added ±0.0001" CMM scope', tag: 'facility' },
  ];
  return (
    <div className="notif-pop" onClick={(e) => e.stopPropagation()}>
      <div className="hd">
        <span className="mono-lbl" style={{ color: 'var(--ink)' }}>Activity · last 24h</span>
        <span className="mono-lbl" style={{ color: 'var(--accent)', cursor: 'pointer' }}>mark read</span>
      </div>
      {items.map((n, i) => (
        <div key={i} className="item">
          <span style={{ width: 6, height: 6, background: n.dot, borderRadius: '50%', marginTop: 6 }} />
          <div>
            <div style={{ fontWeight: 500, color: 'var(--ink)', marginBottom: 2 }}>{n.title}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', lineHeight: 1.4 }}>{n.body}</div>
            <div className="mono-lbl" style={{ marginTop: 4, fontSize: 9 }}>{n.tag}</div>
          </div>
          <span className="mono-lbl" style={{ fontSize: 9 }}>{n.t}</span>
        </div>
      ))}
      <div style={{ padding: 10, textAlign: 'center' }}>
        <span className="mono-lbl" style={{ cursor: 'pointer' }}>open full audit log →</span>
      </div>
    </div>
  );
}

Object.assign(window, { Sidebar, TopBar, NotifPopover });
