// Disparo em massa — WhatsApp blast dedicado

const DisparoPage = () => {
  const [step, setStep] = React.useState("compor"); // compor | revisar | enviando | concluido
  const [tipo, setTipo] = React.useState("texto-imagem"); // texto | texto-imagem | botao
  const [msg, setMsg] = React.useState("Oi {primeiro_nome}! 💛\n\nTem live nova hoje às 20h — peças de Verão 26 com preço exclusivo de live.\n\nGuarda já no carrinho ⬇️\n👉 {link_live}");
  const [segmentos, setSegmentos] = React.useState(["champions", "leais", "live60"]);
  const [intervalo, setIntervalo] = React.useState(15);
  const [agora, setAgora] = React.useState(true);
  const [sent, setSent] = React.useState(0);

  const toggleSeg = (s) => setSegmentos(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s]);

  // Estimativa de destinatários (mock)
  const calcDestinatarios = () => {
    const m = { champions: 142, leais: 318, potencial: 89, risco: 204, novos: 64, perdidos: 487, live60: 312, loja30: 89, aniver: 28, cashback: 84 };
    return segmentos.reduce((s, k) => s + (m[k] || 0), 0);
  };
  const dest = calcDestinatarios();
  const custo = dest * 0.05;
  const tempoMin = Math.ceil(dest * intervalo / 60);

  // Simula envio
  React.useEffect(() => {
    if (step !== "enviando") return;
    setSent(0);
    const start = Date.now();
    const id = setInterval(() => {
      const elapsed = (Date.now() - start) / 1000;
      const target = Math.min(dest, Math.floor(elapsed / 1.5 * dest * 0.08));
      setSent(target);
      if (target >= dest) {
        clearInterval(id);
        setTimeout(() => setStep("concluido"), 600);
      }
    }, 80);
    return () => clearInterval(id);
  }, [step, dest]);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <span className="eyebrow"><span className="play"/>WhatsApp em massa</span>
          <h1 style={{marginTop:10}}>Disparo em massa</h1>
          <p className="lead">Envio direto via API WhatsApp Business · até 5.000 destinatários por disparo.</p>
        </div>
        <div className="actions">
          <div style={{padding:'6px 10px', background:'var(--bg-2)', border:'1px solid var(--line)', borderRadius:7, fontSize:11}} className="row gap-8">
            <Ic name="whatsapp" size={12} className="t-green"/>
            <span className="t-3 mono" style={{letterSpacing:'0.1em'}}>SALDO</span>
            <span className="t-accent mono" style={{fontWeight:600}}>R$ 28,40</span>
            <span className="t-3">·</span>
            <span className="mono t-3">≈ 568 envios</span>
            <span className="t-3">·</span>
            <a className="t-2 mono" style={{cursor:'pointer'}}>recarregar</a>
          </div>
        </div>
      </div>

      {/* Stepper */}
      <div className="row gap-0 mb-24" style={{background:'var(--bg-2)', border:'1px solid var(--line)', borderRadius:10, padding:4}}>
        <StepIndicator num="01" label="Compor" active={step === "compor"} done={step !== "compor"}/>
        <StepIndicator num="02" label="Segmentar & revisar" active={step === "revisar"} done={step === "enviando" || step === "concluido"}/>
        <StepIndicator num="03" label="Enviando" active={step === "enviando"} done={step === "concluido"}/>
        <StepIndicator num="04" label="Concluído" active={step === "concluido"}/>
      </div>

      {step === "compor" && (
        <div style={{display:'grid', gridTemplateColumns:'1fr 380px', gap:18}}>
          <div className="stack">
            <div className="card">
              <div className="card-head"><h3>Tipo de mensagem</h3></div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8}}>
                <TipoChip tipo="texto" active={tipo === "texto"} onClick={() => setTipo("texto")} icon="send" label="Texto simples"/>
                <TipoChip tipo="texto-imagem" active={tipo === "texto-imagem"} onClick={() => setTipo("texto-imagem")} icon="eye" label="Texto + imagem"/>
                <TipoChip tipo="botao" active={tipo === "botao"} onClick={() => setTipo("botao")} icon="arrowRight" label="Texto + botão CTA"/>
              </div>
            </div>

            <div className="card">
              <div className="card-head">
                <h3>Mensagem</h3>
                <div className="row gap-6">
                  <select className="input"><option>Sem template</option><option>Convite Live</option><option>Aniversário</option><option>Recuperação carrinho</option></select>
                  <button className="btn sm ghost"><Ic name="sparkles" size={11}/> Gerar com IA</button>
                </div>
              </div>
              {tipo === "texto-imagem" && (
                <div style={{height:120, background:'var(--bg-3)', border:'1px dashed var(--line-2)', borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', gap:4, marginBottom:10, cursor:'pointer'}}>
                  <Ic name="plus" size={20} className="t-3"/>
                  <span className="t-3" style={{fontSize:12}}>Arraste imagem ou clique para enviar</span>
                  <span className="t-3 mono" style={{fontSize:10}}>JPEG · PNG · até 5MB</span>
                </div>
              )}
              <textarea
                value={msg}
                onChange={e => setMsg(e.target.value)}
                style={{width:'100%', minHeight:160, background:'var(--bg-3)', border:'1px solid var(--line)', borderRadius:7, padding:12, color:'var(--text)', fontFamily:'var(--font)', fontSize:13, resize:'vertical', outline:'none', lineHeight:1.5}}/>
              {tipo === "botao" && (
                <div className="mt-12 row gap-8">
                  <input className="input grow" placeholder="Texto do botão (ex: Ver Lives)"/>
                  <input className="input grow" placeholder="URL do botão"/>
                </div>
              )}
              <div className="row" style={{justifyContent:'space-between', marginTop:10}}>
                <div className="row" style={{flexWrap:'wrap', gap:4}}>
                  <button className="btn sm ghost" onClick={() => setMsg(m => m + " {primeiro_nome}")}><span className="mono">{`{primeiro_nome}`}</span></button>
                  <button className="btn sm ghost" onClick={() => setMsg(m => m + " {valor_cashback}")}><span className="mono">{`{valor_cashback}`}</span></button>
                  <button className="btn sm ghost"><span className="mono">{`{link_live}`}</span></button>
                  <button className="btn sm ghost"><span className="mono">{`{link_carrinho}`}</span></button>
                  <button className="btn sm ghost"><span className="mono">+ outras</span></button>
                </div>
                <div className="t-3" style={{fontSize:11}}>{msg.length}/1.024 caracteres</div>
              </div>
            </div>

            <div className="card">
              <div className="card-head">
                <h3>Configurações avançadas</h3>
              </div>
              <div className="stack-tight">
                <ConfigRow
                  label="Intervalo entre envios"
                  hint="Protege contra bloqueio do WhatsApp · recomendado 15s+"
                  control={
                    <div className="row gap-6">
                      <input className="input" type="number" value={intervalo} onChange={e => setIntervalo(Number(e.target.value))} min={5} max={60} style={{width:60, textAlign:'right'}}/>
                      <span className="t-3 mono">seg</span>
                    </div>
                  }/>
                <ConfigRow
                  label="Janela de envio"
                  hint="Só dispara entre estes horários (respeita fuso do destinatário)"
                  control={<div className="row gap-6"><input className="input" type="time" defaultValue="09:00" style={{width:80}}/><span className="t-3">→</span><input className="input" type="time" defaultValue="21:00" style={{width:80}}/></div>}/>
                <ConfigRow
                  label="Excluir quem recebeu marketing há"
                  hint="Não reenviar para quem já foi impactado recentemente"
                  control={<select className="input"><option>menos de 24h</option><option>menos de 48h</option><option>menos de 7 dias</option><option>nunca excluir</option></select>}/>
                <ConfigRow
                  label="Modo respeito"
                  hint="Pula clientes com tag 'não-mkt' ou que bloquearam comunicação"
                  control={<Toggle on/>}/>
              </div>
            </div>
          </div>

          {/* Preview */}
          <div style={{position:'sticky', top:0}}>
            <div className="card">
              <div className="card-head"><h3>Preview · WhatsApp</h3><Badge kind="green" dot>como Beatriz verá</Badge></div>
              <div style={{background:'#0a1612', borderRadius:10, padding:14, paddingBottom:18, backgroundImage:'radial-gradient(rgba(255,255,255,0.04) 1px, transparent 1px)', backgroundSize:'14px 14px'}}>
                <div className="row gap-8 mb-12">
                  <div style={{width:28, height:28, borderRadius:'50%', background:'var(--accent)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:700, color:'white'}}>EA</div>
                  <div>
                    <div style={{fontSize:12.5, fontWeight:600, color:'white'}}>Estúdio Aurora</div>
                    <div style={{fontSize:10, color:'rgba(255,255,255,0.5)'}}>oficial · online</div>
                  </div>
                </div>
                {tipo === "texto-imagem" && (
                  <div style={{background:'#1a2823', padding:4, borderRadius:'10px 10px 0 0', maxWidth:280}}>
                    <div style={{height:140, background:'linear-gradient(135deg, var(--accent), #b13e00)', borderRadius:'8px', display:'flex', alignItems:'center', justifyContent:'center', fontSize:42}}>🌙</div>
                  </div>
                )}
                <div style={{background:'#1a2823', color:'#e8ece9', padding:'10px 12px', borderRadius: tipo === 'texto-imagem' ? '0 0 12px 12px' : '12px 12px 12px 4px', fontSize:13, lineHeight:1.45, maxWidth:280, fontFamily:'system-ui', whiteSpace:'pre-wrap'}}>
                  {msg.replace(/{primeiro_nome}/g, "Bia").replace(/{valor_cashback}/g, "R$ 142,50").replace(/{link_live}/g, "vendanalive.com/aurora-48").replace(/{link_carrinho}/g, "vendanalive.com/c/8472")}
                </div>
                {tipo === "botao" && (
                  <div style={{background:'#1a2823', color:'#5fb3ff', padding:'10px 12px', borderRadius:'0 0 12px 12px', maxWidth:280, marginTop:-1, textAlign:'center', fontSize:13, fontWeight:500, borderTop:'1px solid rgba(255,255,255,0.06)'}}>
                    Ver Live agora
                  </div>
                )}
                <div style={{fontSize:10, color:'rgba(255,255,255,0.5)', textAlign:'right', marginTop:4}}>20:42</div>
              </div>
            </div>

            <div className="card mt-16">
              <div className="card-head"><h3>Custo estimado</h3></div>
              <dl className="kv" style={{gridTemplateColumns:'1fr auto', gap:'4px 14px'}}>
                <dt>Destinatários atuais</dt><dd className="mono">{numFmt(dest)}</dd>
                <dt>Custo por mensagem</dt><dd className="mono">R$ 0,05</dd>
                <dt>Custo total</dt><dd className="mono t-accent" style={{fontSize:15, fontWeight:600}}>{brl(custo)}</dd>
                <dt>Tempo de envio</dt><dd className="mono">~{tempoMin} min</dd>
              </dl>
              <button className="btn primary lg mt-16" style={{width:'100%'}} disabled={dest === 0} onClick={() => setStep("revisar")}>
                Continuar → Segmentar destinatários
              </button>
            </div>
          </div>
        </div>
      )}

      {step === "revisar" && (
        <div style={{display:'grid', gridTemplateColumns:'1fr 380px', gap:18}}>
          <div className="stack">
            <div className="card">
              <div className="card-head">
                <h3>Selecione os segmentos</h3>
                <Badge kind="accent" dot>{numFmt(dest)} destinatários</Badge>
              </div>
              <div className="t-mono-label mb-8">SEGMENTOS RFM</div>
              <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:8}}>
                <SegChip seg="champions" label="Champions" count={142} desc="Compram muito e recente" active={segmentos.includes("champions")} onClick={() => toggleSeg("champions")} color="var(--green)"/>
                <SegChip seg="leais" label="Leais" count={318} desc="Compram com frequência" active={segmentos.includes("leais")} onClick={() => toggleSeg("leais")} color="var(--cyan)"/>
                <SegChip seg="potencial" label="Potencial" count={89} desc="Novos com bom valor" active={segmentos.includes("potencial")} onClick={() => toggleSeg("potencial")} color="var(--accent)"/>
                <SegChip seg="risco" label="Em risco" count={204} desc="Eram bons, sumiram" active={segmentos.includes("risco")} onClick={() => toggleSeg("risco")} color="var(--pink)"/>
                <SegChip seg="novos" label="Novos" count={64} desc="Primeira compra recente" active={segmentos.includes("novos")} onClick={() => toggleSeg("novos")} color="var(--purple)"/>
                <SegChip seg="perdidos" label="Perdidos" count={487} desc="6+ meses sem comprar" active={segmentos.includes("perdidos")} onClick={() => toggleSeg("perdidos")} color="var(--text-3)"/>
              </div>

              <div className="t-mono-label mt-16 mb-8">COMPORTAMENTO</div>
              <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:8}}>
                <SegChip seg="live60" label="Comprou Live · 60d" count={312} desc="Engajadas na live" active={segmentos.includes("live60")} onClick={() => toggleSeg("live60")} color="var(--accent)"/>
                <SegChip seg="loja30" label="Comprou Loja · 30d" count={89} desc="Visitam a loja" active={segmentos.includes("loja30")} onClick={() => toggleSeg("loja30")} color="var(--cyan)"/>
                <SegChip seg="cashback" label="Tem cashback" count={84} desc="Saldo disponível" active={segmentos.includes("cashback")} onClick={() => toggleSeg("cashback")} color="var(--green)"/>
                <SegChip seg="aniver" label="Aniversariante mês" count={28} desc="Maio" active={segmentos.includes("aniver")} onClick={() => toggleSeg("aniver")} color="var(--pink)"/>
                <SegChip seg="abandono" label="Abandono 7d" count={42} desc="Carrinho recente" active={false} onClick={() => {}} color="var(--purple)"/>
                <SegChip seg="custom" label="+ Filtro avançado" count={null} desc="Cidade, nível, etc" active={false} onClick={() => {}} color="var(--text-3)" addMore/>
              </div>
            </div>

            <div className="card">
              <div className="card-head"><h3>Preview da lista · primeiros 20</h3><a className="t-mono-label" style={{cursor:'pointer', color:'var(--text-2)'}}>Ver lista completa ({numFmt(dest)})</a></div>
              <div className="tbl-wrap" style={{border:'none'}}>
                <table className="tbl">
                  <thead><tr><th>Cliente</th><th>@</th><th>Cidade</th><th>RFM</th><th>Cashback</th><th>Última compra</th></tr></thead>
                  <tbody>
                    {CLIENTES.slice(0,8).map(c => (
                      <tr key={c.id}>
                        <td className="row gap-8"><ClientAvatar name={c.nome}/><span className="strong">{c.nome.split(" ").slice(0,2).join(" ")}</span></td>
                        <td className="mono t-3">{c.instagram}</td>
                        <td className="t-3" style={{fontSize:11}}>{c.cidade}</td>
                        <td><Badge kind={c.rfm === "Champions" ? "green" : "cyan"}>{c.rfm}</Badge></td>
                        <td className="num t-green">{c.cashback > 0 ? brl(c.cashback) : "—"}</td>
                        <td className="mono t-3">{c.ultimaCompra}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <div style={{position:'sticky', top:0}}>
            <div className="card">
              <div className="card-head"><h3>Resumo do disparo</h3></div>
              <div className="stack-tight">
                <Stat label="Destinatários" value={numFmt(dest)} glow="green"/>
                <Stat label="Custo total" value={brl(custo)} glow/>
                <Stat label="Tempo de envio" value={`~${tempoMin} min`}/>
                <Stat label="Saldo restante após" value={brl(28.40 - custo)} glow={28.40 - custo < 10 ? "" : "cyan"}/>
              </div>

              <div className="t-mono-label mt-16 mb-8">QUANDO ENVIAR</div>
              <div style={{display:'flex', gap:4, padding:3, background:'var(--bg-3)', borderRadius:7}}>
                <button className={"btn sm grow " + (agora ? "accent" : "ghost")} onClick={() => setAgora(true)} style={{background: agora ? 'var(--accent)' : 'transparent', border:'none'}}>
                  Agora
                </button>
                <button className={"btn sm grow " + (!agora ? "accent" : "ghost")} onClick={() => setAgora(false)} style={{background: !agora ? 'var(--accent)' : 'transparent', border:'none'}}>
                  Agendar
                </button>
              </div>
              {!agora && (
                <div className="row gap-6 mt-12">
                  <input className="input" type="date" defaultValue="2026-05-20" style={{flex:1}}/>
                  <input className="input" type="time" defaultValue="19:00" style={{width:90}}/>
                </div>
              )}

              <div className="row gap-8 mt-16">
                <button className="btn ghost grow" onClick={() => setStep("compor")}>← Voltar</button>
                <button className="btn primary grow" disabled={dest === 0} onClick={() => setStep("enviando")}>
                  <Ic name="send" size={12}/> Disparar
                </button>
              </div>

              {28.40 - custo < 0 && (
                <div style={{padding:10, background:'rgba(223,74,99,.08)', border:'1px solid rgba(223,74,99,.3)', borderRadius:7, marginTop:14, fontSize:11.5}} className="t-red">
                  ⚠️ Saldo insuficiente. Recarregue antes de disparar.
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {step === "enviando" && (
        <div className="card" style={{padding:40, textAlign:'center', maxWidth:600, margin:'0 auto'}}>
          <div className="row gap-8" style={{justifyContent:'center', marginBottom:12}}>
            <span style={{width:10, height:10, background:'var(--green)', borderRadius:'50%', animation:'pulse 1.2s infinite', boxShadow:'0 0 14px var(--green)'}}/>
            <span className="t-mono-label" style={{color:'var(--green)', letterSpacing:'0.22em'}}>ENVIANDO</span>
          </div>
          <h2 style={{margin:'8px 0 4px', fontSize:24}}>{numFmt(sent)} <span className="t-3" style={{fontSize:18}}>/ {numFmt(dest)}</span></h2>
          <p className="t-3" style={{fontSize:13}}>mensagens enviadas com sucesso</p>

          <div style={{height:8, background:'var(--bg-3)', borderRadius:4, overflow:'hidden', margin:'24px 0 12px'}}>
            <div style={{height:'100%', width: (sent/dest*100).toFixed(0) + '%', background:'linear-gradient(90deg, var(--green), var(--accent))', transition:'width .3s'}}/>
          </div>

          <div className="stat-grid cols-4 mt-24">
            <Stat label="Enviadas" value={numFmt(sent)} glow="green"/>
            <Stat label="Falhas" value={Math.floor(sent * 0.02)} hint="número inválido"/>
            <Stat label="Tempo restante" value={Math.max(0, tempoMin - Math.floor(sent/dest*tempoMin)) + " min"}/>
            <Stat label="Saldo restante" value={brl(28.40 - (sent * 0.05))} glow="cyan"/>
          </div>

          <div className="row gap-8 mt-24" style={{justifyContent:'center'}}>
            <button className="btn ghost">Pausar</button>
            <button className="btn danger">Cancelar restante</button>
          </div>
        </div>
      )}

      {step === "concluido" && (
        <div className="card" style={{padding:40, textAlign:'center', maxWidth:600, margin:'0 auto'}}>
          <div style={{width:64, height:64, borderRadius:'50%', background:'rgba(162,248,101,.15)', border:'2px solid var(--green)', display:'inline-flex', alignItems:'center', justifyContent:'center', marginBottom:16, color:'var(--green)'}}>
            <Ic name="check" size={28} style={{strokeWidth:2.5}}/>
          </div>
          <h2 style={{margin:'8px 0 4px', fontSize:24}}>Disparo concluído!</h2>
          <p className="t-2" style={{fontSize:14}}>{numFmt(dest)} mensagens enviadas em ~{tempoMin} minutos</p>

          <div className="stat-grid cols-3 mt-24">
            <Stat glow="green" label="Entregues" value={numFmt(Math.floor(dest * 0.94))} hint={`${(94).toFixed(0)}% taxa de entrega`}/>
            <Stat label="Falhas" value={Math.floor(dest * 0.06)} hint="número inválido / bloqueado"/>
            <Stat label="Custo final" value={brl(custo * 0.94)} hint={`R$ ${(custo * 0.06).toFixed(2)} ressarcidos`}/>
          </div>

          <div className="row gap-8 mt-24" style={{justifyContent:'center'}}>
            <button className="btn ghost" onClick={() => { setStep("compor"); setSent(0); }}><Ic name="plus" size={12}/> Novo disparo</button>
            <button className="btn ghost"><Ic name="chart" size={12}/> Acompanhar conversões</button>
            <button className="btn primary"><Ic name="users" size={12}/> Ver lista enviados</button>
          </div>
        </div>
      )}

      {/* Histórico colapsado */}
      {step === "compor" && (
        <div className="card mt-24">
          <div className="card-head"><h3>Disparos recentes</h3><a className="t-mono-label" style={{cursor:'pointer', color:'var(--text-2)'}}>Ver todos</a></div>
          <table className="tbl">
            <thead><tr><th>Nome</th><th>Quando</th><th>Destinatários</th><th>Entrega</th><th>Conversões</th><th style={{textAlign:'right'}}>Receita atribuída</th><th>ROI</th></tr></thead>
            <tbody>
              <tr><td className="strong">Convite Live #47</td><td className="mono t-3">12/05 18:00</td><td className="num">2.108</td><td><Badge kind="green" dot>94.2%</Badge></td><td className="num">218</td><td className="num strong">{brl(14820)}</td><td><Badge kind="green">28.1×</Badge></td></tr>
              <tr><td className="strong">Champions — Pré-venda</td><td className="mono t-3">10/05 14:30</td><td className="num">87</td><td><Badge kind="green" dot>97.7%</Badge></td><td className="num">42</td><td className="num strong">{brl(8420)}</td><td><Badge kind="green">42.8×</Badge></td></tr>
              <tr><td className="strong">Cashback expirando</td><td className="mono t-3">12/05 09:00</td><td className="num">64</td><td><Badge kind="green" dot>95.3%</Badge></td><td className="num">18</td><td className="num strong">{brl(3240)}</td><td><Badge kind="green">21.0×</Badge></td></tr>
              <tr><td className="strong">Aniversariantes Maio</td><td className="mono t-3">01/05 09:00</td><td className="num">142</td><td><Badge kind="green" dot>97.2%</Badge></td><td className="num">38</td><td className="num strong">{brl(5240)}</td><td><Badge kind="green">14.4×</Badge></td></tr>
              <tr><td className="strong">Reativação 60d sem compra</td><td className="mono t-3">19/05 14:00</td><td className="num">312</td><td><Badge kind="cyan" dot>em curso</Badge></td><td className="num t-3">12</td><td className="num">{brl(840)}</td><td><Badge kind="muted">apurando</Badge></td></tr>
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

const StepIndicator = ({ num, label, active, done }) => (
  <div style={{flex:1, padding:'10px 14px', borderRadius:8, background: active ? 'var(--accent-soft)' : 'transparent', display:'flex', alignItems:'center', gap:10, opacity: !active && !done ? 0.5 : 1}}>
    <div style={{width:26, height:26, borderRadius:'50%', background: done ? 'var(--green)' : active ? 'var(--accent)' : 'var(--bg-3)', border:'1px solid '+ (done ? 'var(--green)' : active ? 'var(--accent)' : 'var(--line)'), display:'flex', alignItems:'center', justifyContent:'center', color: done ? '#0a1a02' : 'white', fontFamily:'var(--mono)', fontSize:11, fontWeight:600}}>
      {done ? <Ic name="check" size={12} style={{strokeWidth:3}}/> : num}
    </div>
    <span style={{fontSize:12.5, fontWeight: active ? 500 : 400, color: active ? 'var(--text)' : 'var(--text-2)'}}>{label}</span>
  </div>
);

const TipoChip = ({ active, onClick, icon, label }) => (
  <button onClick={onClick}
    style={{padding:'14px 12px', background: active ? 'var(--accent-soft)' : 'var(--bg-3)', border:'1px solid '+ (active ? 'var(--accent)' : 'var(--line)'), borderRadius:8, color: active ? 'var(--text)' : 'var(--text-2)', display:'flex', flexDirection:'column', alignItems:'center', gap:8, cursor:'pointer', fontFamily:'var(--font)', fontSize:12.5}}>
    <Ic name={icon} size={18} className={active ? "t-accent" : "t-3"}/>
    {label}
  </button>
);

const SegChip = ({ label, count, desc, active, onClick, color, addMore }) => (
  <button onClick={onClick}
    style={{padding:'12px 14px', background: active ? 'rgba(232,86,0,.06)' : 'var(--bg-3)', border:'1px solid '+ (active ? 'var(--accent)' : 'var(--line)'), borderRadius:8, textAlign:'left', cursor:'pointer', fontFamily:'var(--font)', position:'relative'}}>
    {active && <div style={{position:'absolute', top:8, right:8, width:14, height:14, borderRadius:'50%', background:'var(--accent)', display:'flex', alignItems:'center', justifyContent:'center'}}><Ic name="check" size={10} style={{color:'white', strokeWidth:3}}/></div>}
    <div className="row gap-6 mb-4">
      <span style={{width:6, height:6, background: color, borderRadius:'50%'}}/>
      <span style={{fontSize:12.5, fontWeight:500, color: active ? 'var(--text)' : 'var(--text-2)'}}>{label}</span>
    </div>
    {!addMore && count !== null && (
      <>
        <div className="mono" style={{fontSize:18, fontWeight:500, color: active ? 'var(--text)' : 'var(--text-2)', letterSpacing:'-0.01em'}}>{numFmt(count)}</div>
        <div className="t-3" style={{fontSize:10.5}}>{desc}</div>
      </>
    )}
    {addMore && <div className="t-3" style={{fontSize:11, marginTop:4}}>{desc}</div>}
  </button>
);

const ConfigRow = ({ label, hint, control }) => (
  <div className="row gap-12" style={{padding:'10px 0', borderBottom:'1px solid var(--line)'}}>
    <div style={{flex:1}}>
      <div style={{fontSize:12.5, fontWeight:500}}>{label}</div>
      {hint && <div className="t-3" style={{fontSize:11}}>{hint}</div>}
    </div>
    {control}
  </div>
);

Object.assign(window, { DisparoPage });
