// ── Inova Cotação — Módulo Representante (mobile) ───────────────────────
const ICr = window.IC;
const catR = window.BuyerParts1.catById;

function RepApp({ desktop = false }) {
  const u = window.__inovaped_user || null;
  const real = !!(u && u.role === 'rep');
  const [screen, setScreen] = useState(real ? 'app' : 'login'); // login | signup | app
  const me = real
    ? { id: u.rep_id, name: u.nome, contact: u.nome, lab: '—', color: '#E5142B', cats: [], real: true }
    : ICr.REPS.find(r => r.id === ICr.REP_SESSION);
  const RepSignup = window.RepPart3.RepSignup;
  const RepShell = window.RepPart4.RepShell;
  window.__repDesktop = desktop;

  const inner = (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'radial-gradient(120% 80% at 80% -10%, rgba(255,19,48,0.20), transparent 60%), ' + T.stage, color: T.text }}>
      {screen === 'login'  && <RepLogin desktop={desktop} onEnter={() => setScreen('app')} onSignup={() => setScreen('signup')} />}
      {screen === 'signup' && <RepSignup onDone={() => setScreen('app')} onBack={() => setScreen('login')} />}
      {screen === 'app'    && <RepShell me={me} desktop={desktop} onLogout={() => setScreen('login')} />}
    </div>
  );

  // Desktop (PC) → app web full-width responsivo; Mobile → coluna única com bottom-nav
  if (desktop) return <div style={{ height: '100%', width: '100%' }}>{inner}</div>;
  return <div style={{ height: '100%', maxWidth: 480, margin: '0 auto', boxShadow: '0 0 60px rgba(0,0,0,0.4)' }}>{inner}</div>;
}

// ── header mobile ────────────────────────────────────────────────────────
function MHead({ title, sub, back, right }) {
  const d = window.__repDesktop;
  return (
    <div style={{ padding: d ? '26px 32px 16px' : '54px 20px 14px', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
      {back && <button onClick={back} style={{ width: 36, height: 36, borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name="chevron" size={18} color={T.text} style={{ transform: 'rotate(180deg)' }} /></button>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: d ? 26 : 21, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.4 }}>{title}</div>
        {sub && <div style={{ fontSize: 12.5, color: T.mute, marginTop: 1, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{sub}</div>}
      </div>
      {right}
    </div>
  );
}

// ── LOGIN (e-mail / senha) ──────────────────────────────────────────────
function RepLogin({ onEnter, onSignup, desktop }) {
  const [email, setEmail] = useState('rodrigo@nutrimax.com.br');
  const [pass, setPass] = useState('••••••••');
  const [show, setShow] = useState(false);
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: desktop ? 'center' : 'flex-start', alignItems: desktop ? 'center' : 'stretch', padding: desktop ? 40 : '70px 24px 28px', overflow: 'auto' }}>
     <div style={{ width: '100%', maxWidth: desktop ? 420 : 'none' }}>
      <div style={{ width: 60, height: 60, borderRadius: 17, background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, display:'flex',alignItems:'center',justifyContent:'center', boxShadow: '0 10px 30px rgba(255,19,48,0.5)', marginBottom: 22 }}>
        <Icon name="bolt" size={30} color="#fff" strokeWidth={2.2} />
      </div>
      <div style={{ fontSize: 27, fontWeight: 800, fontFamily: 'var(--display)', letterSpacing: -0.6 }}>Portal do Representante</div>
      <div style={{ color: T.mute, fontSize: 14, marginTop: 6 }}>Entre para responder cotações da Rede Inova</div>

      <div style={{ marginTop: 26 }}>
        <label style={rlLbl()}>E-mail</label>
        <div style={{ position: 'relative' }}>
          <Icon name="user" size={16} color={T.mute2} style={{ position: 'absolute', left: 13, top: 15 }} />
          <input value={email} onChange={e => setEmail(e.target.value)} style={{ ...rlIn(), paddingLeft: 40 }} />
        </div>
      </div>
      <div style={{ marginTop: 14 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <label style={rlLbl()}>Senha</label>
          <a href="#" onClick={e => e.preventDefault()} style={{ fontSize: 12, color: T.redBright, textDecoration: 'none', fontWeight: 600 }}>Esqueci a senha</a>
        </div>
        <div style={{ position: 'relative' }}>
          <Icon name="shield" size={16} color={T.mute2} style={{ position: 'absolute', left: 13, top: 15 }} />
          <input type={show ? 'text' : 'password'} value={pass} onChange={e => setPass(e.target.value)} style={{ ...rlIn(), paddingLeft: 40, paddingRight: 56 }} />
          <button onClick={() => setShow(v => !v)} style={{ position: 'absolute', right: 8, top: 9, padding: '0 8px', height: 30, borderRadius: 8, border: 'none', background: 'transparent', cursor: 'pointer', color: T.mute, fontSize: 11.5, fontWeight: 700 }}>{show ? 'Ocultar' : 'Ver'}</button>
        </div>
      </div>

      <button onClick={onEnter} style={{ marginTop: 22, padding: '15px', borderRadius: 15, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 15.5, color: '#fff', background: `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})`, boxShadow: '0 8px 24px rgba(255,19,48,0.45)', display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}>Entrar <Icon name="chevron" size={17} color="#fff" strokeWidth={2.4} /></button>

      <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '22px 0' }}>
        <div style={{ flex: 1, height: 1, background: T.border }} /><span style={{ fontSize: 12, color: T.mute2 }}>ou</span><div style={{ flex: 1, height: 1, background: T.border }} />
      </div>

      <div style={{ textAlign: 'center', fontSize: 13.5, color: T.mute, marginBottom: 12 }}>Ainda não tem conta?</div>
      <button onClick={onSignup} style={{ padding: '14px', borderRadius: 15, border: `1.5px solid ${T.red}`, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 15, color: '#fff', background: T.redBg, display:'flex',alignItems:'center',justifyContent:'center',gap:8 }}><Icon name="plus" size={18} color={T.redBright} strokeWidth={2.4} /> Criar conta de representante</button>
     </div>
    </div>
  );
}
const rlLbl = () => ({ display: 'block', fontSize: 12, fontWeight: 600, color: T.mute, marginBottom: 7 });
const rlIn = () => ({ width: '100%', boxSizing: 'border-box', padding: '13px 14px', borderRadius: 12, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' });

// ── PORTAL DE OFERTAS ──────────────────────────────────────────────────────
function RepPortal({ me, onOpen, onLogout }) {
  const [liveQuotes, setLiveQuotes] = useState(null);
  useEffect(() => {
    if (me && me.real && window.api) {
      window.api.get('/rep/quotations')
        .then(r => setLiveQuotes(r.items.map(q => ({ id: q.id, cat: q.category_id, title: q.titulo, items: q.itens, deadline: q.prazo || '—', categoria: q.categoria, status: 'aberta', minhas: q.minhas_ofertas }))))
        .catch(() => setLiveQuotes([]));
    }
  }, [me && me.id]);
  // cotações ativas que batem com as categorias do rep
  const myQuotes = (me && me.real)
    ? (liveQuotes || [])
    : ICr.QUOTES.filter(q => q.status === 'aberta' && me.cats.includes(q.cat));
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <MHead title="Ofertas Ativas" sub={`Olá, ${me.contact.split(' ')[0]} · ${me.name}`}
        right={<button onClick={onLogout} style={{ width: 36, height: 36, borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, cursor: 'pointer', display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name="logout" size={17} color={T.mute} /></button>} />

      {/* aviso central interna */}
      <div style={{ margin: window.__repDesktop ? '0 32px 10px' : '0 20px 8px', display: 'flex', alignItems: 'center', gap: 10, padding: '11px 14px', borderRadius: 13, background: 'rgba(0,230,140,0.10)', border: '1px solid rgba(0,230,140,0.30)' }}>
        <Icon name="bell" size={18} color={T.green} /><span style={{ fontSize: 12.5, color: T.green }}>Você foi avisado no sistema sobre {myQuotes.length} nova(s) cotação(ões)</span>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: window.__repDesktop ? '10px 32px 30px' : '8px 20px 30px', display: 'grid', gridTemplateColumns: window.__repDesktop ? 'repeat(auto-fill, minmax(340px, 1fr))' : '1fr', gap: 12, alignContent: 'start' }}>
        {myQuotes.map(q => { const c = catR(q.cat) || { icon: 'box', name: q.categoria || '—' }; return (
          <div key={q.id} onClick={() => onOpen(q)} style={{ padding: 16, borderRadius: 17, background: T.glassGrad, border: `1px solid ${T.border}`, cursor: 'pointer' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
              <div style={{ width: 42, height: 42, borderRadius: 12, background: T.redBg, border:`1px solid rgba(255,19,48,0.3)`, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={c.icon} size={21} color={T.redBright} /></div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 15 }}>{c.name}</div>
                <div style={{ fontSize: 12.5, color: T.mute }}>{q.items} itens p/ cotar</div>
              </div>
              <Pill tone="yellow">Aberta</Pill>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14, paddingTop: 13, borderTop: `1px solid ${T.border}` }}>
              <div style={{ display:'flex', alignItems:'center', gap: 6, fontSize: 12.5, color: T.mute }}><Icon name="clock" size={15} color={T.mute}/> Prazo {q.deadline}</div>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: T.redBright, display:'flex',alignItems:'center',gap:4 }}>Responder <Icon name="chevron" size={15} color={T.redBright}/></span>
            </div>
          </div>
        ); })}
        {!myQuotes.length && <div style={{ textAlign:'center', color: T.mute2, marginTop: 40 }}>Nenhuma cotação ativa nas suas categorias.</div>}
      </div>
    </div>
  );
}

window.RepPart1 = { RepApp, MHead, RepLogin, RepPortal };
