// App shell: sidebar, topbar, MAX panel, footer, role switcher.

const Sidebar = ({ stages, activeKey, onNav, role }) => {
  const STAGE_KEYS = stages.map(s => s.id);
  const items = [
    { key: 'home', label: 'Главный экран', icon: 'home' },
    { key: 'team', label: 'Моя команда', icon: 'users' },
  ];
  const utility = [
    { key: 'materials', label: 'Материалы', icon: 'book' },
    { key: 'feedback',  label: 'Обратная связь', icon: 'chat' },
    { key: 'profile',   label: 'Профиль', icon: 'user' },
  ];
  return (
    <aside className="sidebar">
      <div className="sidebar-brand">
        <BrandMark />
        <div>
          <div style={{fontFamily:'var(--font-display)', fontWeight:700, fontSize:14, lineHeight:1.1, color:'var(--ink-950)'}}>Лаборатория</div>
          <div style={{fontSize:11, color:'var(--ink-600)'}}>стажировок · ЦОПП</div>
        </div>
      </div>

      {items.map(it => (
        <button key={it.key} className={`sidebar-link ${activeKey===it.key?'active':''}`} onClick={() => onNav(it.key)}>
          <Icon name={it.icon} size={18} className="sidebar-link-icon" />
          <span>{it.label}</span>
        </button>
      ))}

      <div className="sidebar-section-label">Этапы программы</div>
      {stages.map(s => {
        const isDone = s.status === 'done';
        const isActive = s.status === 'active';
        const cls = `sidebar-link ${activeKey===s.id?'active':''} ${isDone?'done':''}`;
        return (
          <button key={s.id} className={cls} onClick={() => onNav(s.id)}>
            <span className="sidebar-link-stage">{isDone ? '✓' : s.n}</span>
            <span style={{display:'flex', flexDirection:'column', minWidth:0}}>
              <span style={{fontWeight:600, fontSize:13.5, lineHeight:1.2}}>{s.short}</span>
              <span style={{fontSize:11, color:'var(--ink-500)', lineHeight:1.2, marginTop:2}}>{isActive?'идёт сейчас':isDone?'завершён':'впереди'}</span>
            </span>
          </button>
        );
      })}

      <div className="sidebar-section-label">Сервис</div>
      {utility.map(it => (
        <button key={it.key} className={`sidebar-link ${activeKey===it.key?'active':''}`} onClick={() => onNav(it.key)}>
          <Icon name={it.icon} size={18} className="sidebar-link-icon" />
          <span>{it.label}</span>
        </button>
      ))}

      <div style={{marginTop:'auto', padding:'12px 8px 0'}}>
        <div className="card" style={{padding:12, background:'var(--wine-50)', borderColor:'var(--wine-200)'}}>
          <div style={{display:'flex', alignItems:'center', gap:8}}>
            <Icon name="info" size={16} style={{color:'var(--wine-700)'}} />
            <div style={{fontWeight:600, fontSize:12.5, color:'var(--wine-800)'}}>До защиты 26 мая</div>
          </div>
          <div style={{fontSize:11.5, color:'var(--wine-700)', marginTop:4, lineHeight:1.4}}>
            22 дня · черновик проекта<br/>сдать до 23 мая
          </div>
        </div>
      </div>
    </aside>
  );
};

const BrandMark = () => (
  <div style={{
    width:36, height:36, borderRadius:10,
    background:'linear-gradient(135deg, var(--wine-700), var(--wine-900))',
    display:'inline-flex', alignItems:'center', justifyContent:'center',
    color:'#fff', fontFamily:'var(--font-display)', fontWeight:800, fontSize:15,
    boxShadow:'inset 0 1px 0 rgba(255,255,255,0.18), 0 4px 12px rgba(42,6,18,0.25)'
  }}>
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
      <path d="M3 20L9 4l3 8 3-8 6 16" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  </div>
);

const Topbar = ({ role, onRoleChange, breadcrumb, onMaxOpen, maxCount }) => {
  return (
    <div className="topbar">
      <div className="topbar-crumb">
        {breadcrumb.map((b, i) => (
          <React.Fragment key={i}>
            {i>0 && <Icon name="chevronRight" size={14} style={{color:'var(--ink-400)'}} />}
            <span className={i===breadcrumb.length-1?'':'muted'} style={i===breadcrumb.length-1?{color:'var(--ink-900)', fontWeight:600}:{}}>{b}</span>
          </React.Fragment>
        ))}
      </div>

      <div style={{marginLeft:'auto', display:'flex', alignItems:'center', gap:12}}>
        <RoleSwitcher role={role} onChange={onRoleChange} />
        <button className="btn btn-quiet" style={{padding:8, position:'relative'}} onClick={onMaxOpen} title="Уведомления MAX">
          <Icon name="bell" size={18} />
          {maxCount > 0 && (
            <span style={{
              position:'absolute', top:4, right:4,
              minWidth:16, height:16, padding:'0 4px', borderRadius:8,
              background:'var(--amber-500)', color:'#fff',
              fontSize:10, fontWeight:700, fontFamily:'var(--font-display)',
              display:'inline-flex', alignItems:'center', justifyContent:'center', lineHeight:1,
            }}>{maxCount}</span>
          )}
        </button>
        <UserChip role={role} />
      </div>
    </div>
  );
};

const ROLE_DEFS = [
  { id: 'hr',      label: 'HR (компания)',   sub: 'Елена Гончарова',     initials: 'ЕГ', av:'wine'  },
  { id: 'mentor',  label: 'Наставник',        sub: 'Игорь Савельев',      initials: 'ИС', av:'ink'   },
  { id: 'intern',  label: 'Стажёр',           sub: 'Анастасия Ким',       initials: 'АК', av:'amber' },
  { id: 'curator', label: 'Куратор ЦОПП',    sub: 'Дарья Маратканова',   initials: 'ДМ', av:'wine'  },
  { id: 'dapr',    label: 'Наблюдатель ДАПР', sub: 'Министерство',        initials: 'М',  av:'ink'   },
];

const RoleSwitcher = ({ role, onChange }) => {
  const [open, setOpen] = React.useState(false);
  const cur = ROLE_DEFS.find(r => r.id === role);
  React.useEffect(() => {
    const onClick = (e) => {
      if (!e.target.closest('.role-switcher')) setOpen(false);
    };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);
  return (
    <div className="role-switcher" style={{position:'relative'}}>
      <button className="btn btn-ghost btn-sm" onClick={() => setOpen(o => !o)} style={{padding:'6px 10px 6px 6px', gap:8}}>
        <span className={`avatar avatar-sm avatar-${cur.av}`}>{cur.initials}</span>
        <span style={{display:'flex', flexDirection:'column', alignItems:'flex-start', lineHeight:1.1, gap:2}}>
          <span style={{fontSize:12, color:'var(--ink-600)', fontWeight:500}}>смотрю как</span>
          <span style={{fontSize:13, fontWeight:600}}>{cur.label}</span>
        </span>
        <Icon name="chevronDown" size={14} style={{color:'var(--ink-500)'}} />
      </button>
      {open && (
        <div style={{
          position:'absolute', top:'calc(100% + 6px)', right:0,
          width:280, background:'#fff', border:'1px solid var(--ink-200)',
          borderRadius:'var(--r-lg)', boxShadow:'var(--shadow-lg)', padding:6, zIndex:50
        }}>
          <div style={{fontSize:11, fontWeight:600, color:'var(--ink-500)', padding:'8px 10px 4px', textTransform:'uppercase', letterSpacing:'0.08em'}}>Демо · переключение роли</div>
          {ROLE_DEFS.map(r => (
            <button key={r.id} onClick={() => { onChange(r.id); setOpen(false); }} style={{
              display:'flex', alignItems:'center', gap:10, width:'100%', padding:'8px 10px',
              border:'none', background: role===r.id?'var(--wine-50)':'transparent',
              borderRadius:'var(--r-md)', cursor:'pointer', textAlign:'left',
            }}>
              <span className={`avatar avatar-sm avatar-${r.av}`}>{r.initials}</span>
              <div style={{flex:1}}>
                <div style={{fontWeight:600, fontSize:13.5, color:'var(--ink-900)'}}>{r.label}</div>
                <div style={{fontSize:11.5, color:'var(--ink-600)'}}>{r.sub}</div>
              </div>
              {role===r.id && <Icon name="check" size={16} style={{color:'var(--wine-700)'}} />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const UserChip = ({ role }) => {
  const r = ROLE_DEFS.find(x => x.id === role);
  return (
    <div style={{display:'flex', alignItems:'center', gap:10, paddingLeft:12, borderLeft:'1px solid var(--ink-200)'}}>
      <div style={{textAlign:'right'}}>
        <div style={{fontSize:13, fontWeight:600, color:'var(--ink-900)', lineHeight:1.1}}>{r.sub}</div>
        <div style={{fontSize:11.5, color:'var(--ink-600)'}}>{r.id==='hr'||r.id==='mentor' ? COMPANY_NAME : r.label}</div>
      </div>
      <div className={`avatar avatar-md avatar-${r.av}`}>{r.initials}</div>
    </div>
  );
};
const COMPANY_NAME = 'Восток-Сталь';

const MaxPanel = ({ open, onClose, items }) => {
  if (!open) return null;
  return (
    <div className="max-panel">
      <div className="max-header">
        <div className="max-logo">M</div>
        <div style={{flex:1}}>
          <div style={{fontFamily:'var(--font-display)', fontWeight:700, fontSize:14}}>MAX · уведомления</div>
          <div style={{fontSize:11.5, color:'rgba(255,255,255,0.65)'}}>Бот ЦОПП Приморья · {items.length} новых</div>
        </div>
        <button onClick={onClose} style={{background:'none', border:'none', color:'rgba(255,255,255,0.7)', cursor:'pointer', padding:6}}>
          <Icon name="chevronRight" size={18} />
        </button>
      </div>
      <div className="max-list">
        {items.map((it, i) => (
          <div key={it.id} className="max-item">
            <div className="max-logo" style={{
              background: i===0 ? 'linear-gradient(135deg, var(--wine-500), var(--wine-700))' : 'linear-gradient(135deg, var(--amber-500), var(--amber-700))'
            }}>{i===0?'⏱':'!'}</div>
            <div>
              <div className="max-item-title">{it.title}</div>
              <div className="max-item-body">{it.body}</div>
              <div className="max-item-time">{it.time}</div>
            </div>
          </div>
        ))}
      </div>
      <div style={{padding:'10px 16px', borderTop:'1px solid var(--ink-150)', background:'var(--ink-50)', fontSize:12, color:'var(--ink-600)'}}>
        Уведомления приходят в <b style={{color:'var(--ink-900)'}}>MAX</b>. Можно отключить в Профиле.
      </div>
    </div>
  );
};

const TutorFAB = ({ onClick }) => (
  <button className="tutor-fab" onClick={onClick}>
    <span className="av">ДМ</span>
    <span>Позвать тьютора</span>
  </button>
);

const Footer = () => (
  <footer className="footer">
    <div>
      Реализовано <b style={{color:'var(--ink-900)'}}>ЦОПП Приморского края</b> при методологической поддержке <b style={{color:'var(--ink-900)'}}>Plus Ultra</b>.
      Часть региональной платформы кадров «Профи 25»: <a href="#" onClick={e => e.preventDefault()}>career.plsultra.ru</a>
    </div>
    <div style={{display:'flex', alignItems:'center', gap:16}}>
      <span>© 2026</span>
      <span>·</span>
      <a href="#" onClick={e => e.preventDefault()}>Политика данных</a>
      <a href="#" onClick={e => e.preventDefault()}>Поддержка</a>
    </div>
  </footer>
);

const SupportBadge = () => (
  <div style={{
    display:'inline-flex', alignItems:'center', gap:10,
    padding:'6px 12px 6px 8px',
    background:'#fff',
    border:'1px solid var(--ink-200)',
    borderRadius:'var(--r-pill)',
    fontSize:11.5, color:'var(--ink-700)', fontWeight:500
  }}>
    <span style={{
      width:18, height:18, borderRadius:4,
      background:'linear-gradient(135deg, var(--wine-700), var(--wine-900))',
      display:'inline-block'
    }} />
    При поддержке Министерства профессионального образования Приморского края
  </div>
);

const StageProgress = ({ stages, current }) => {
  return (
    <div className="stack-3">
      <div style={{display:'grid', gridTemplateColumns:`repeat(${stages.length}, 1fr)`, gap:8}}>
        {stages.map((s, i) => {
          const isDone = s.status === 'done';
          const isActive = s.status === 'active';
          return (
            <div key={s.id} style={{position:'relative'}}>
              <div style={{
                height:8, borderRadius:'var(--r-pill)',
                background: isDone ? 'var(--wine-600)' :
                            isActive ? 'linear-gradient(90deg, var(--wine-600) 0%, var(--wine-600) 60%, var(--ink-200) 60%)' :
                            'var(--ink-200)',
                boxShadow: isActive ? '0 0 0 2px rgba(138,24,56,0.12)' : 'none',
              }} />
              <div style={{display:'flex', alignItems:'baseline', gap:6, marginTop:10}}>
                <span style={{
                  fontFamily:'var(--font-display)', fontWeight:700, fontSize:11,
                  color: isDone ? 'var(--wine-700)' : isActive ? 'var(--wine-700)' : 'var(--ink-500)',
                  letterSpacing:'0.06em',
                }}>0{s.n}</span>
                {isActive && <span className="badge badge-amber" style={{padding:'1px 6px', fontSize:10}}>Сейчас</span>}
              </div>
              <div style={{fontFamily:'var(--font-display)', fontWeight:600, fontSize:13.5, marginTop:2, color: isActive?'var(--ink-950)':isDone?'var(--ink-800)':'var(--ink-600)'}}>{s.title}</div>
              <div style={{fontSize:11.5, color:'var(--ink-500)', marginTop:1}}>{s.dates}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { Sidebar, Topbar, MaxPanel, TutorFAB, Footer, SupportBadge, StageProgress, BrandMark, ROLE_DEFS });
