// ── InovaPED — Representante: Cadastro (multi-etapas) ───────────────────
const ICs = window.IC;
const catS = window.BuyerParts1.catById;

function RepSignup({ onDone, onBack }) {
  const [step, setStep] = useState(1);
  const total = 4;
  const [form, setForm] = useState({ nome: '', empresa: '', fone: '', email: '', senha: '', senha2: '' });
  const [tipo, setTipo] = useState(null);     // 'rep' | 'forn'
  const [tax, setTax] = useState(null);       // 'com' | 'sem'
  const [labs, setLabs] = useState([]);
  const [cats, setCats] = useState([]);
  const [labQ, setLabQ] = useState('');
  const [tried, setTried] = useState(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const emailOk = /.+@.+\..+/.test(form.email);
  const step1Ok = form.nome && form.empresa && form.fone && emailOk && form.senha.length >= 4 && form.senha === form.senha2;
  const step2Ok = tipo && tax;
  const step3Ok = labs.length > 0;
  const step4Ok = cats.length > 0;
  const stepOk = [null, step1Ok, step2Ok, step3Ok, step4Ok][step];

  const next = () => { setTried(true); if (stepOk) { setTried(false); step < total ? setStep(step + 1) : onDone(); } };
  const back = () => { setTried(false); step > 1 ? setStep(step - 1) : onBack(); };
  const toggleLab = (id) => setLabs(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  const toggleCat = (id) => setCats(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  const shownLabs = ICs.LABS.filter(l => l.name.toLowerCase().includes(labQ.toLowerCase()));

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* header + progresso */}
      <div style={{ padding: '54px 22px 12px', flexShrink: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <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' }}><Icon name="chevron" size={18} color={T.text} style={{ transform: 'rotate(180deg)' }} /></button>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 19, fontWeight: 800, fontFamily: 'var(--display)' }}>Criar conta</div>
            <div style={{ fontSize: 12, color: T.mute }}>Passo {step} de {total}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 5, marginTop: 14 }}>
          {[1,2,3,4].map(i => <div key={i} style={{ flex: 1, height: 4, borderRadius: 99, background: i <= step ? `linear-gradient(90deg, ${T.redBright}, ${T.redDeep})` : T.trackNeutral }} />)}
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '8px 22px 20px' }}>
        {step === 1 && (
          <div>
            <STitle>Seus dados</STitle>
            <Field label="Nome completo"><input value={form.nome} onChange={e => set('nome', e.target.value)} placeholder="Ex: Rodrigo Alves" style={suIn()} /></Field>
            <Field label="Empresa / Representação"><input value={form.empresa} onChange={e => set('empresa', e.target.value)} placeholder="Ex: NutriMax Supplements" style={suIn()} /></Field>
            <Field label="WhatsApp / Telefone"><input value={form.fone} onChange={e => set('fone', e.target.value.replace(/[^0-9()\-\s+]/g, ''))} inputMode="tel" placeholder="(11) 99999-9999" style={suIn()} /></Field>
            <Field label="E-mail"><input value={form.email} onChange={e => set('email', e.target.value)} inputMode="email" placeholder="voce@empresa.com.br" style={{ ...suIn(), borderColor: tried && !emailOk ? T.redBright : T.border }} /></Field>
            <div style={{ display: 'flex', gap: 10 }}>
              <Field label="Senha" style={{ flex: 1 }}><input type="password" value={form.senha} onChange={e => set('senha', e.target.value)} placeholder="mín. 4" style={suIn()} /></Field>
              <Field label="Confirmar" style={{ flex: 1 }}><input type="password" value={form.senha2} onChange={e => set('senha2', e.target.value)} placeholder="repita" style={{ ...suIn(), borderColor: tried && form.senha2 && form.senha !== form.senha2 ? T.redBright : T.border }} /></Field>
            </div>
            {tried && !step1Ok && <ErrMsg>Preencha todos os campos. Verifique e-mail e se as senhas coincidem.</ErrMsg>}
          </div>
        )}

        {step === 2 && (
          <div>
            <STitle>Você é representante ou fornecedor?</STitle>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[['rep','Representante','Vendo em nome de laboratórios/marcas','user'],['forn','Fornecedor / Laboratório','Sou indústria ou distribuidora','box']].map(([v, t, d, ic]) => {
                const on = tipo === v;
                return <button key={v} onClick={() => setTipo(v)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: 16, borderRadius: 15, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', background: on ? T.redBg : T.panel, border: `1.5px solid ${on ? T.red : T.border}`, color: T.text }}>
                  <div style={{ width: 42, height: 42, borderRadius: 11, background: on ? 'rgba(255,19,48,0.2)' : T.panelHi, display:'flex',alignItems:'center',justifyContent:'center', flexShrink: 0 }}><Icon name={ic} size={21} color={on ? T.redBright : T.mute} /></div>
                  <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 15 }}>{t}</div><div style={{ fontSize: 12, color: T.mute, marginTop: 1 }}>{d}</div></div>
                  <div style={{ width: 22, height: 22, borderRadius: 99, border: `1.5px solid ${on ? T.red : T.borderHi}`, background: on ? T.red : 'transparent', display:'flex',alignItems:'center',justifyContent:'center' }}>{on && <Icon name="check" size={13} color="#fff" strokeWidth={3} />}</div>
                </button>;
              })}
            </div>
            <div style={{ margintop: 8 }} />
            <STitle style={{ marginTop: 22 }}>Seus preços serão...</STitle>
            <div style={{ display: 'flex', gap: 10 }}>
              {[['com','Com imposto'],['sem','Sem imposto']].map(([v, l]) => {
                const on = tax === v;
                return <button key={v} onClick={() => setTax(v)} style={{ flex: 1, padding: '14px', borderRadius: 13, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 800, fontSize: 14, border: `1.5px solid ${on ? T.red : T.borderHi}`, color: on ? '#fff' : T.text, background: on ? `linear-gradient(135deg, ${T.redBright}, ${T.redDeep})` : T.panel, display:'flex',alignItems:'center',justifyContent:'center',gap:7 }}>{on && <Icon name="check" size={15} color="#fff" strokeWidth={3} />}{l}</button>;
              })}
            </div>
            <div style={{ fontSize: 12, color: T.mute, marginTop: 8, lineHeight: 1.4 }}>Pode ajustar item a item depois, mas esse é o padrão das suas ofertas.</div>
            {tried && !step2Ok && <ErrMsg>Selecione o tipo e se os preços são com/sem imposto.</ErrMsg>}
          </div>
        )}

        {step === 3 && (
          <div>
            <STitle>Quais laboratórios / distribuidoras você representa?</STitle>
            <div style={{ position: 'relative', marginBottom: 12 }}>
              <Icon name="search" size={16} color={T.mute} style={{ position: 'absolute', left: 12, top: 13 }} />
              <input value={labQ} onChange={e => setLabQ(e.target.value)} placeholder="Buscar laboratório..." style={{ ...suIn(), paddingLeft: 38 }} />
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {shownLabs.map(l => { const on = labs.includes(l.id); return (
                <button key={l.id} onClick={() => toggleLab(l.id)} style={{ display:'flex', flexDirection:'column', alignItems:'flex-start', gap: 2, padding: '10px 13px', borderRadius: 12, cursor: 'pointer', fontFamily: 'inherit', border: `1.5px solid ${on ? T.red : T.border}`, background: on ? T.redBg : T.panel, color: T.text }}>
                  <span style={{ fontWeight: 700, fontSize: 13.5, display:'flex',alignItems:'center',gap:6 }}>{on && <Icon name="check" size={13} color={T.redBright} strokeWidth={3} />}{l.name}</span>
                  <span style={{ fontSize: 10.5, color: T.mute }}>{l.type}</span>
                </button>
              ); })}
            </div>
            {labs.length > 0 && <div style={{ fontSize: 12, color: T.green, marginTop: 12, fontWeight: 600 }}>{labs.length} selecionado(s)</div>}
            {tried && !step3Ok && <ErrMsg>Selecione ao menos um laboratório ou distribuidora.</ErrMsg>}
          </div>
        )}

        {step === 4 && (
          <div>
            <STitle>Categorias que você atende</STitle>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {ICs.CATEGORIES.map(c => { const on = cats.includes(c.id); return (
                <button key={c.id} onClick={() => toggleCat(c.id)} style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '13px 15px', borderRadius: 14, cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left', background: on ? T.redBg : T.panel, border: `1.5px solid ${on ? T.red : T.border}`, color: T.text }}>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: on ? 'rgba(255,19,48,0.2)' : T.panelHi, display:'flex',alignItems:'center',justifyContent:'center' }}><Icon name={c.icon} size={19} color={on ? T.redBright : T.mute} /></div>
                  <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14.5 }}>{c.name}</div><div style={{ fontSize: 11.5, color: T.mute }}>{c.count.toLocaleString('pt-BR')} produtos</div></div>
                  <div style={{ width: 23, height: 23, borderRadius: 7, border: `1.5px solid ${on ? T.red : T.borderHi}`, background: on ? T.red : 'transparent', display:'flex',alignItems:'center',justifyContent:'center' }}>{on && <Icon name="check" size={14} color="#fff" strokeWidth={3} />}</div>
                </button>
              ); })}
            </div>
            <div style={{ display:'flex', alignItems:'center', gap: 8, marginTop: 14, padding: '11px 14px', borderRadius: 12, background: 'rgba(0,230,140,0.10)', border: '1px solid rgba(0,230,140,0.30)' }}>
              <Icon name="bell" size={17} color={T.green} /><span style={{ fontSize: 12, color: T.green }}>Você receberá avisos no sistema quando o Felipe abrir cotações nessas categorias.</span>
            </div>
            {tried && !step4Ok && <ErrMsg>Escolha pelo menos uma categoria.</ErrMsg>}
          </div>
        )}
      </div>

      {/* barra inferior */}
      <div style={{ flexShrink: 0, padding: '12px 22px 28px', borderTop: `1px solid ${T.border}`, background: 'rgba(5,5,6,0.9)', backdropFilter: 'blur(10px)' }}>
        <button onClick={next} style={{ width: '100%', 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 }}>
          {step < total ? <>Continuar <Icon name="chevron" size={17} color="#fff" strokeWidth={2.4} /></> : <><Icon name="check" size={18} color="#fff" strokeWidth={2.6} /> Finalizar cadastro</>}
        </button>
      </div>
    </div>
  );
}

function STitle({ children, style }) { return <div style={{ fontSize: 17, fontWeight: 800, fontFamily: 'var(--display)', marginBottom: 14, letterSpacing: -0.3, ...style }}>{children}</div>; }
function Field({ label, children, style }) { return <div style={{ marginBottom: 13, ...style }}><label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: T.mute, marginBottom: 6 }}>{label}</label>{children}</div>; }
function ErrMsg({ children }) { return <div style={{ fontSize: 12.5, color: T.redBright, marginTop: 14, fontWeight: 600, display:'flex',alignItems:'center',gap:6 }}><Icon name="bell" size={14} color={T.redBright} />{children}</div>; }
const suIn = () => ({ width: '100%', boxSizing: 'border-box', padding: '12px 13px', borderRadius: 11, border: `1px solid ${T.border}`, background: T.panel, color: T.text, fontFamily: 'inherit', fontSize: 14, outline: 'none' });

window.RepPart3 = { RepSignup };
