// ── InovaPED — Representante: Shell com abas + Ranking/Desempenho/Mural ──
const ICm = window.IC;
const catM = window.BuyerParts1.catById, repM = window.BuyerParts1.repById;

function RepShell({ me, onLogout, desktop }) {
  const [tab, setTab] = useState('ofertas');
  const [overlay, setOverlay] = useState(null); // { type:'fill'|'done', quote }
  const RepPortal = window.RepPart1.RepPortal;
  const RepFill = window.RepPart2.RepFill, RepDone = window.RepPart2.RepDone;
  const { RepUpload, RepChat, RepConfig } = window.RepPart5;

  const tabs = [['ofertas', 'Ofertas', 'list'], ['mural', 'Mural', 'tag'], ['ranking', 'Ranking', 'trophy'], ['perf', 'Você', 'chart'], ['mais', 'Mais', 'grid']];

  if (overlay?.type === 'fill') return <RepFill me={me} quote={overlay.quote} onBack={() => setOverlay(null)} onSubmit={() => setOverlay({ type: 'done', quote: overlay.quote })} />;
  if (overlay?.type === 'done') return <RepDone quote={overlay.quote} onBack={() => { setOverlay(null); setTab('ofertas'); }} />;
  if (overlay === 'upload') return <RepUpload me={me} onBack={() => setOverlay(null)} />;
  if (overlay === 'chat')   return <RepChat me={me} onBack={() => setOverlay(null)} />;
  if (overlay === 'config') return <RepConfig me={me} onBack={() => setOverlay(null)} />;

  const content = (
    <>
      {tab === 'ofertas' && <RepPortal me={me} onOpen={(q) => setOverlay({ type: 'fill', quote: q })} onLogout={onLogout} />}
      {tab === 'mural'   && <RepMural me={me} />}
      {tab === 'ranking' && <RepRanking me={me} />}
      {tab === 'perf'    && <RepPerf me={me} />}
      {tab === 'mais'    && <RepMore me={me} onLogout={onLogout} go={setOverlay} />}
    </>
  );

  // ── DESKTOP: sidebar à esquerda + conteúdo amplo ──
  if (desktop) {
    return (
      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        <div style={{ width: 230, flexShrink: 0, borderRight: `1px solid ${T.border}`, background: T.panel, display: 'flex', flexDirection: 'column', padding: '22px 14px', gap: 18 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '0 8px' }}>
            <div style={{ width: 42, height: 42, borderRadius: 12, background: me.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, fontSize: 18, color: '#fff', flexShrink: 0 }}>{me.name[0]}</div>
            <div style={{ minWidth: 0 }}><div style={{ fontWeight: 800, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{me.name}</div><div style={{ fontSize: 11.5, color: T.mute }}>{me.lab}</div></div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3, flex: 1 }}>
            {tabs.map(([id, label, icon]) => { const on = tab === id; return (
              <button key={id} onClick={() => setTab(id)} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 13px', borderRadius: 12, border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 14, fontWeight: on ? 700 : 500, color: on ? T.text : T.mute, background: on ? 'linear-gradient(90deg, rgba(255,19,48,0.18), rgba(255,19,48,0.04))' : 'transparent', boxShadow: on ? `inset 2px 0 0 ${T.red}` : 'none' }}>
                <Icon name={icon} size={19} color={on ? T.red : T.mute} /> {label === 'Você' ? 'Desempenho' : label}
              </button>
            ); })}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[['upload', 'Subir tabela / XML', 'box'], ['chat', 'Mensagens', 'send'], ['config', 'Configurações', 'filter']].map(([id, label, icon]) => (
              <button key={id} onClick={() => setOverlay(id)} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 13px', borderRadius: 11, border: 'none', cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, color: T.mute, background: 'transparent' }}>
                <Icon name={icon} size={17} color={T.mute} /> {label}
              </button>
            ))}
            <button onClick={onLogout} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 13px', borderRadius: 11, border: `1px solid ${T.border}`, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', fontSize: 13, fontWeight: 700, color: T.redBright, background: T.redBg, marginTop: 4 }}>
              <Icon name="logout" size={17} color={T.redBright} /> Sair
            </button>
          </div>
        </div>
        <div className="fade-view" key={tab} style={{ flex: 1, overflow: 'auto', minWidth: 0 }}>
          <div style={{ maxWidth: 940, margin: '0 auto' }}>{content}</div>
        </div>
      </div>
    );
  }

  // ── MOBILE: bottom nav ──
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <div style={{ flex: 1, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>{content}</div>
      <div style={{ flexShrink: 0, display: 'flex', borderTop: `1px solid ${T.border}`, background: 'rgba(5,5,6,0.92)', backdropFilter: 'blur(12px)', padding: '8px 6px 26px' }}>
        {tabs.map(([id, label, icon]) => { const on = tab === id; return (
          <button key={id} onClick={() => setTab(id)} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, padding: '6px 0', border: 'none', background: 'transparent', cursor: 'pointer', fontFamily: 'inherit' }}>
            <Icon name={icon} size={21} color={on ? T.redBright : T.mute2} strokeWidth={on ? 2.2 : 1.7} />
            <span style={{ fontSize: 10.5, fontWeight: on ? 700 : 500, color: on ? T.redBright : T.mute2 }}>{label}</span>
          </button>
        ); })}
      </div>
    </div>
  );
}

// ── header simples mobile ───────────────────────────────────────────────
function MH({ title, sub, right }) {
  const d = window.__repDesktop;
  return (
    <div style={{ padding: d ? '26px 32px 14px' : '54px 20px 12px', flexShrink: 0, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 10 }}>
      <div><div style={{ fontSize: d ? 26 : 22, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.4 }}>{title}</div>{sub && <div style={{ fontSize: 12.5, color: T.mute, marginTop: 1 }}>{sub}</div>}</div>
      {right}
    </div>
  );
}

// ── RANKING (gamificação Top Seller) ────────────────────────────────────
function RepRanking({ me }) {
  const ranked = [...ICm.RANKING].sort((a, b) => b.sales - a.sales);
  const myPos = ranked.findIndex(r => r.rep === me.id) + 1;
  const medal = ['#FFC83D', '#C8CDD6', '#CD7F32'];
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <MH title="Ranking" sub="Top sellers da Rede Inova" />
      <div style={{ flex: 1, overflow: 'auto', padding: '6px 18px 20px' }}>
        <div style={{ padding: 18, borderRadius: 18, background: `linear-gradient(135deg, rgba(255,19,48,0.18), rgba(255,19,48,0.04))`, border: `1px solid rgba(255,19,48,0.3)`, marginBottom: 16, textAlign: 'center' }}>
          <div style={{ fontSize: 12, color: T.mute }}>Sua posição</div>
          <div style={{ fontSize: 40, fontWeight: 800, fontFamily: 'var(--display)', color: T.redBright }}>{myPos}º</div>
          <div style={{ fontSize: 13, color: T.mute }}>de {ranked.length} representantes</div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {ranked.map((r, i) => { const rp = repM(r.rep); const mine = r.rep === me.id; return (
            <div key={r.rep} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 15px', borderRadius: 14, background: mine ? T.redBg : T.panel, border: `1.5px solid ${mine ? T.red : T.border}` }}>
              <div style={{ width: 26, textAlign: 'center', fontWeight: 800, fontSize: 15, color: i < 3 ? medal[i] : T.mute, fontFamily: 'var(--display)' }}>{i + 1}</div>
              <div style={{ width: 38, height: 38, borderRadius: 99, background: rp.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, color: '#fff' }}>{rp.name[0]}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 700, fontSize: 14 }}>{rp.name.split(' ')[0]}{mine && <span style={{ color: T.redBright, fontSize: 12 }}> · você</span>}</div>
                <div style={{ fontSize: 11.5, color: T.mute }}>{r.deals} negócios fechados</div>
              </div>
              <div style={{ textAlign: 'right' }}><div style={{ fontWeight: 800, fontSize: 14, fontVariantNumeric: 'tabular-nums' }}>R$ {(r.sales/1000).toFixed(0)}k</div><div style={{ fontSize: 11, color: r.trend.startsWith('-') ? T.redBright : T.green, fontWeight: 700 }}>{r.trend}</div></div>
            </div>
          ); })}
        </div>
      </div>
    </div>
  );
}

// ── DESEMPENHO (eficiência + oportunidades perdidas + selos) ─────────────
function RepPerf({ me }) {
  const p = ICm.PERFORMANCE[me.id] || { sent: 0, closed: 0, lost: [] };
  const rate = p.sent ? Math.round(p.closed / p.sent * 100) : 0;
  const badges = ICm.BADGES[me.id] || [];
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <MH title="Seu Desempenho" sub={me.name} />
      <div style={{ flex: 1, overflow: 'auto', padding: '6px 18px 20px' }}>
        <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
          <PStat label="Cotações" value={p.sent} />
          <PStat label="Fechadas" value={p.closed} color={T.green} />
          <PStat label="Conversão" value={rate + '%'} color={T.redBright} />
        </div>
        {badges.length > 0 && <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: T.mute, marginBottom: 8, textTransform: 'uppercase', letterSpacing: 0.4 }}>Seus selos</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {badges.map(b => { const bi = ICm.BADGE_INFO[b]; return <span key={b} style={{ display:'inline-flex',alignItems:'center',gap:6, padding: '8px 12px', borderRadius: 11, fontSize: 12.5, fontWeight: 700, background: 'rgba(255,255,255,0.05)', color: bi.color, border: `1px solid ${bi.color}50` }}><Icon name={bi.icon} size={15} color={bi.color} />{bi.label}</span>; })}
          </div>
        </div>}
        <div style={{ padding: 16, borderRadius: 15, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 14 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}><span style={{ fontWeight: 700, fontSize: 14 }}>Taxa de conversão</span><span style={{ fontWeight: 800, color: T.green }}>{rate}%</span></div>
          <div style={{ height: 10, borderRadius: 99, background: T.panelHi, overflow: 'hidden' }}><div style={{ width: rate + '%', height: '100%', background: `linear-gradient(90deg, ${T.green}, #0AA968)` }} /></div>
          <div style={{ fontSize: 12, color: T.mute, marginTop: 8 }}>Você enviou {p.sent} cotações e fechou {p.closed}. Parabéns!</div>
        </div>
        <div style={{ padding: 16, borderRadius: 15, background: 'rgba(255,19,48,0.05)', border: `1px solid rgba(255,19,48,0.2)` }}>
          <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 4, display:'flex',alignItems:'center',gap:7 }}><Icon name="arrowDown" size={15} color={T.redBright} /> Oportunidades perdidas</div>
          <div style={{ fontSize: 12, color: T.mute, marginBottom: 10 }}>Itens que a rede comprou de outro fornecedor:</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
            {p.lost.map((it, i) => <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}><Icon name="x" size={13} color={T.redBright} />{it}</div>)}
          </div>
        </div>
      </div>
    </div>
  );
}
function PStat({ label, value, color }) { return <div style={{ flex: 1, padding: 14, borderRadius: 14, background: T.panel, border: `1px solid ${T.border}`, textAlign: 'center' }}><div style={{ fontSize: 24, fontWeight: 800, fontFamily: 'var(--display)', color: color || T.text }}>{value}</div><div style={{ fontSize: 11, color: T.mute2, marginTop: 2 }}>{label}</div></div>; }

// ── MURAL (rep aceita demandas) ─────────────────────────────────────────
function RepMural({ me }) {
  const [accepted, setAccepted] = useState({});
  const mine = ICm.DEMANDS.filter(d => me.cats.includes(d.cat));
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <MH title="Mural de Ofertas" sub="Demandas da rede nas suas categorias" />
      <div style={{ flex: 1, overflow: 'auto', padding: '6px 18px 20px', display: 'flex', flexDirection: 'column', gap: 11 }}>
        {mine.map(d => { const c = catM(d.cat); const acc = accepted[d.id] || d.status === 'aceita'; return (
          <div key={d.id} style={{ padding: 16, borderRadius: 16, background: T.panel, border: `1px solid ${acc ? 'rgba(0,230,140,0.35)' : T.border}` }}>
            <div style={{ display: 'flex', gap: 11, alignItems: 'center' }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: T.redBg, border:`1px solid rgba(255,19,48,0.3)`, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={c.icon} size={20} color={T.redBright} /></div>
              <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14, lineHeight: 1.25 }}>{d.prod}</div><div style={{ fontSize: 12, color: T.mute, marginTop: 1 }}>{c.name} · {d.time}</div></div>
            </div>
            <div style={{ display: 'flex', gap: 20, marginTop: 12 }}>
              <div><div style={{ fontSize: 11, color: T.mute2 }}>Preço-alvo</div><div style={{ fontWeight: 800, fontSize: 17, fontFamily: 'var(--display)', color: T.redBright }}>R$ {ICm.fmt(d.target)}</div></div>
              <div><div style={{ fontSize: 11, color: T.mute2 }}>Quantidade</div><div style={{ fontWeight: 800, fontSize: 17, fontFamily: 'var(--display)' }}>{d.qty} un</div></div>
            </div>
            <button onClick={() => setAccepted(a => ({ ...a, [d.id]: true }))} disabled={acc} style={{ width: '100%', marginTop: 12, padding: '12px', borderRadius: 12, border: 'none', cursor: acc ? 'default' : 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, color: acc ? T.green : '#fff', background: acc ? T.greenBg : `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}>{acc ? <><Icon name="check" size={16} color={T.green} strokeWidth={3} /> Aceita!</> : <>Aceitar pelo preço-alvo</>}</button>
          </div>
        ); })}
        {!mine.length && <div style={{ textAlign: 'center', color: T.mute2, marginTop: 40 }}>Nenhuma demanda nas suas categorias.</div>}
      </div>
    </div>
  );
}

// ── MAIS (menu) ─────────────────────────────────────────────────────────
function RepMore({ me, onLogout, go }) {
  const items = [['upload', 'Subir tabela / XML', 'box', 'CSV, XML da nota — leitura automática'], ['chat', 'Mensagens', 'send', 'Falar com o comprador'], ['config', 'Configurações', 'filter', 'Mix, disponibilidade, automação']];
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <MH title="Mais" sub={me.name} />
      <div style={{ flex: 1, overflow: 'auto', padding: '6px 18px 20px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: 16, borderRadius: 16, background: T.panel, border: `1px solid ${T.border}`, marginBottom: 14 }}>
          <div style={{ width: 48, height: 48, borderRadius: 99, background: me.color, display:'flex',alignItems:'center',justifyContent:'center', fontWeight: 800, fontSize: 20, color: '#fff' }}>{me.name[0]}</div>
          <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15 }}>{me.name}</div><div style={{ fontSize: 12.5, color: T.mute }}>{me.contact} · {me.lab}</div></div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
          {items.map(([id, t, ic, d]) => (
            <button key={id} onClick={() => go(id)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', background: T.panel, border: `1px solid ${T.border}`, color: T.text }}>
              <div style={{ width: 40, height: 40, borderRadius: 11, background: T.redBg, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={ic} size={20} color={T.redBright} /></div>
              <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14.5 }}>{t}</div><div style={{ fontSize: 12, color: T.mute, marginTop: 1 }}>{d}</div></div>
              <Icon name="chevron" size={17} color={T.mute2} />
            </button>
          ))}
          <button onClick={onLogout} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '15px 16px', borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', background: 'transparent', border: `1px solid ${T.border}`, color: T.redBright, marginTop: 6 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: T.redBg, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="logout" size={19} color={T.redBright} /></div>
            <div style={{ fontWeight: 700, fontSize: 14.5 }}>Sair da conta</div>
          </button>
        </div>
      </div>
    </div>
  );
}

window.RepPart4 = { RepShell };
