// Módulo LIVE — Planejamento (hub de lives)

const LivePlanejamentoPage = () => {
  const [creating, setCreating] = React.useState(false);

  const goToApresentar = () => { window.location.hash = "#live-apresentar"; };

  const lives = [
    {
      id: 48, nome: "Live #48 — Vestidos Verão 26", data: "19/05/2026", hora: "20:00", duracao: "38m em andamento",
      status: "Ao vivo", roteiro: 10, apresentados: 4,
      faturamento: 8240.50, pedidos: 47, clientes: 23, ticket: 175.33,
      apresentadora: "Letícia Borges", cor: "var(--red)"
    },
    {
      id: 49, nome: "Live #49 — Vibes praia + linho", data: "22/05/2026", hora: "20:00", duracao: "agendada",
      status: "Agendada", roteiro: 14, apresentados: 0,
      faturamento: 0, pedidos: 0, clientes: 0, ticket: 0,
      apresentadora: "Letícia Borges", convites: 2418, cor: "var(--cyan)"
    },
    {
      id: 50, nome: "Live #50 — Marco · Coleção Inverno", data: "29/05/2026", hora: "20:00", duracao: "rascunho",
      status: "Rascunho", roteiro: 6, apresentados: 0,
      faturamento: 0, pedidos: 0, clientes: 0, ticket: 0,
      apresentadora: "—", cor: "var(--text-3)"
    },
  ];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <span className="eyebrow"><span className="play"/>Gestão de lives</span>
          <h1 style={{marginTop:10}}>Lives</h1>
          <p className="lead">Crie roteiros, inicie a transmissão, acompanhe resultados. Toque <b className="t-2">Iniciar</b> para abrir o painel de Apresentar no celular.</p>
        </div>
        <div className="actions">
          <button className="btn ghost"><Ic name="folder" size={13}/> Duplicar última</button>
          <button className="btn primary" onClick={() => setCreating(true)}><Ic name="plus" size={13}/> Nova live</button>
        </div>
      </div>

      <div className="stat-grid cols-4 mb-24">
        <Stat glow="green" label="Live ativa agora" value="Live #48" hint="38min · 47 pedidos · R$ 8.240"/>
        <Stat label="Próxima agendada" value="22/05" hint="Live #49 · 2.418 convites enviados"/>
        <Stat label="Lives no mês" value="6" delta={20.0} hint="meta 8"/>
        <Stat label="Faturamento médio · live" value={brl(13398)} delta={14.2}/>
      </div>

      {/* Ativa + agendadas */}
      <div className="t-mono-label mb-12">Em andamento · Próximas</div>
      <div className="stack-tight mb-24">
        {lives.map(l => <LiveCard key={l.id} live={l} onStart={goToApresentar}/>)}
      </div>

      {/* Histórico */}
      <div className="card">
        <div className="card-head">
          <h3>Lives realizadas</h3>
          <div className="row gap-6">
            <select className="input"><option>Últimos 30 dias</option><option>Últimos 90 dias</option></select>
            <button className="btn sm ghost"><Ic name="download" size={11}/></button>
          </div>
        </div>
        <div className="tbl-wrap" style={{border:'none'}}>
          <table className="tbl">
            <thead>
              <tr><th>Live</th><th>Data</th><th>Pedidos</th><th>Clientes</th><th style={{textAlign:'right'}}>Faturamento</th><th style={{textAlign:'right'}}>Ticket</th><th>% pagos</th><th></th></tr>
            </thead>
            <tbody>
              {LIVES_HISTORICO.map((l, i) => (
                <tr key={i}>
                  <td className="strong">{l.nome}</td>
                  <td className="mono">{l.data}</td>
                  <td className="num">{l.pedidos}</td>
                  <td className="num">{l.clientes}</td>
                  <td className="num strong">{brl(l.faturamento)}</td>
                  <td className="num">{brl(l.ticket)}</td>
                  <td><Badge kind={l.pagos >= 85 ? "green" : "amber"} dot>{l.pagos}%</Badge></td>
                  <td className="row-action row gap-4" style={{justifyContent:'flex-end'}}>
                    <button className="btn sm ghost"><Ic name="eye" size={11}/></button>
                    <button className="btn sm ghost"><Ic name="folder" size={11}/> Duplicar</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {creating && <NovaLiveModal onClose={() => setCreating(false)} onCreate={() => { setCreating(false); }}/>}
    </div>
  );
};

const LiveCard = ({ live, onStart }) => {
  const isAtiva = live.status === "Ao vivo";
  const isAgendada = live.status === "Agendada";
  const isRascunho = live.status === "Rascunho";

  return (
    <div className="card" style={{ padding: 0, overflow: 'hidden', position: 'relative', border: isAtiva ? '1px solid var(--red)' : '1px solid var(--line)', boxShadow: isAtiva ? '0 0 0 1px rgba(223,74,99,.15), 0 8px 30px rgba(223,74,99,.18)' : 'none' }}>
      {/* status bar lateral */}
      <div style={{ position:'absolute', top:0, left:0, width:4, height:'100%', background: live.cor }}/>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 360px', alignItems:'stretch' }}>
        <div style={{ padding:'18px 22px' }}>
          <div className="row gap-10 mb-12">
            {isAtiva && (
              <span className="row gap-6" style={{color:'var(--red)'}}>
                <span style={{width:8, height:8, background:'var(--red)', borderRadius:'50%', animation:'pulse 1.5s infinite', boxShadow:'0 0 12px rgba(223,74,99,.6)'}}/>
                <span className="t-mono-label" style={{color:'var(--red)', letterSpacing:'0.22em'}}>AO VIVO</span>
              </span>
            )}
            {isAgendada && <Badge kind="cyan" dot>AGENDADA</Badge>}
            {isRascunho && <Badge kind="muted" dot>RASCUNHO</Badge>}
            <span className="t-mono-label" style={{letterSpacing:'0.14em'}}>{live.duracao}</span>
          </div>
          <h2 style={{ margin: '0 0 4px', fontSize: 20, fontWeight: 500, letterSpacing: '-0.02em' }}>{live.nome}</h2>
          <div className="row gap-16 t-3" style={{fontSize:12.5}}>
            <span className="row gap-4"><Ic name="cake" size={12}/> <span className="mono">{live.data} · {live.hora}</span></span>
            <span>·</span>
            <span className="row gap-4"><Ic name="package" size={12}/> {live.roteiro} produtos no roteiro</span>
            {live.apresentadora !== "—" && <><span>·</span><span className="row gap-4"><Ic name="user" size={12}/> {live.apresentadora}</span></>}
          </div>

          {isAtiva && (
            <div className="stat-grid cols-4 mt-16">
              <div style={{padding:'10px 12px', background:'var(--bg-3)', borderRadius:8}}>
                <div className="t-mono-label" style={{fontSize:9.5}}>FATURADO</div>
                <div className="mono t-green" style={{fontSize:18, fontWeight:600}}>{brl(live.faturamento)}</div>
              </div>
              <div style={{padding:'10px 12px', background:'var(--bg-3)', borderRadius:8}}>
                <div className="t-mono-label" style={{fontSize:9.5}}>PEDIDOS</div>
                <div className="mono" style={{fontSize:18, fontWeight:600}}>{live.pedidos}</div>
              </div>
              <div style={{padding:'10px 12px', background:'var(--bg-3)', borderRadius:8}}>
                <div className="t-mono-label" style={{fontSize:9.5}}>CLIENTES</div>
                <div className="mono" style={{fontSize:18, fontWeight:600}}>{live.clientes}</div>
              </div>
              <div style={{padding:'10px 12px', background:'var(--bg-3)', borderRadius:8}}>
                <div className="t-mono-label" style={{fontSize:9.5}}>APRESENTADOS</div>
                <div className="mono" style={{fontSize:18, fontWeight:600}}>{live.apresentados}<span className="t-3" style={{fontSize:13, fontWeight:400}}>/{live.roteiro}</span></div>
              </div>
            </div>
          )}

          {isAgendada && (
            <div className="mt-16 row gap-12" style={{fontSize:12.5}}>
              <div style={{padding:'8px 12px', background:'var(--bg-3)', borderRadius:7}}>
                <span className="t-3 mono" style={{letterSpacing:'0.12em', fontSize:10}}>CONVITES ENVIADOS</span>
                <div className="row gap-6 mt-4">
                  <Ic name="whatsapp" size={13} className="t-green"/>
                  <span className="mono" style={{fontSize:15, fontWeight:600}}>{numFmt(live.convites)}</span>
                  <span className="t-3" style={{fontSize:11}}>destinatários</span>
                </div>
              </div>
              <div style={{padding:'8px 12px', background:'var(--bg-3)', borderRadius:7}}>
                <span className="t-3 mono" style={{letterSpacing:'0.12em', fontSize:10}}>LEMBRETE AUTO</span>
                <div className="mono mt-4" style={{fontSize:13}}>1h antes · WhatsApp</div>
              </div>
              <div style={{padding:'8px 12px', background:'var(--bg-3)', borderRadius:7}}>
                <span className="t-3 mono" style={{letterSpacing:'0.12em', fontSize:10}}>SE INSCREVERAM</span>
                <div className="mono mt-4 t-accent" style={{fontSize:13, fontWeight:600}}>847 pessoas</div>
              </div>
            </div>
          )}

          {isRascunho && (
            <div className="mt-16 t-3" style={{fontSize:12.5, padding:'8px 12px', background:'rgba(255,255,255,0.02)', border:'1px dashed var(--line-2)', borderRadius:7}}>
              ⚠️ Roteiro incompleto · faltam ao menos 4 produtos para confirmar a live.
            </div>
          )}
        </div>

        {/* Right side: actions */}
        <div style={{ padding: '18px 22px', borderLeft: '1px solid var(--line)', background: isAtiva ? 'rgba(223,74,99,0.04)' : 'var(--bg-3)', display:'flex', flexDirection:'column', justifyContent:'center', gap:8 }}>
          {isAtiva && (
            <>
              <button className="btn lg" style={{background:'var(--red)', color:'white', borderColor:'rgba(255,255,255,.1)', boxShadow:'0 4px 16px rgba(223,74,99,.3)'}} onClick={onStart}>
                <Ic name="live" size={14}/> Abrir painel ao vivo <Ic name="arrowRight" size={13}/>
              </button>
              <button className="btn ghost"><Ic name="list" size={12}/> Ver pedidos · 47</button>
              <button className="btn ghost"><Ic name="pause" size={12}/> Encerrar live</button>
            </>
          )}
          {isAgendada && (
            <>
              <button className="btn primary lg" onClick={onStart}>
                <Ic name="play" size={14}/> Iniciar agora <Ic name="arrowRight" size={13}/>
              </button>
              <button className="btn ghost"><Ic name="edit" size={12}/> Editar roteiro</button>
              <button className="btn ghost"><Ic name="whatsapp" size={12}/> Reenviar convite</button>
              <button className="btn ghost"><Ic name="cake" size={12}/> Remarcar</button>
            </>
          )}
          {isRascunho && (
            <>
              <button className="btn accent lg"><Ic name="edit" size={14}/> Continuar montando <Ic name="arrowRight" size={13}/></button>
              <button className="btn ghost"><Ic name="cake" size={12}/> Agendar data</button>
              <button className="btn ghost danger" style={{background:'transparent'}}><Ic name="trash" size={12}/> Descartar</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

const NovaLiveModal = ({ onClose, onCreate }) => {
  const [step, setStep] = React.useState(1);
  const [nome, setNome] = React.useState("Live #51 — ");
  const [produtos, setProdutos] = React.useState([]);

  const toggleProduto = (id) => {
    setProdutos(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);
  };

  return (
    <div className="modal-back" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal" style={{ maxWidth: 640 }}>
        <div className="row" style={{justifyContent:'space-between', marginBottom:18}}>
          <div>
            <span className="t-mono-label" style={{letterSpacing:'0.14em'}}>NOVA LIVE · ETAPA {step}/3</span>
            <h2 style={{margin:'4px 0 0', fontSize:18}}>
              {step === 1 ? "Quando vai ser?" : step === 2 ? "Quais produtos no roteiro?" : "Convidar audiência"}
            </h2>
          </div>
          <button className="icon-btn" onClick={onClose}><Ic name="x" size={14}/></button>
        </div>

        {step === 1 && (
          <div className="stack-tight">
            <div>
              <div className="t-mono-label mb-8">Nome da live</div>
              <input className="input" style={{width:'100%', height:36}} value={nome} onChange={e => setNome(e.target.value)}/>
            </div>
            <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
              <div>
                <div className="t-mono-label mb-8">Data</div>
                <input className="input" style={{width:'100%', height:36}} type="date" defaultValue="2026-06-05"/>
              </div>
              <div>
                <div className="t-mono-label mb-8">Horário</div>
                <input className="input" style={{width:'100%', height:36}} type="time" defaultValue="20:00"/>
              </div>
            </div>
            <div>
              <div className="t-mono-label mb-8">Apresentadora</div>
              <select className="input" style={{width:'100%', height:36}}>
                <option>Letícia Borges</option>
                <option>Marcela Coutinho</option>
                <option>Janaína Ferreira</option>
              </select>
            </div>
            <div>
              <div className="t-mono-label mb-8">Duplicar de</div>
              <select className="input" style={{width:'100%', height:36}}>
                <option>Começar do zero</option>
                <option>Live #47 — Coleção Verão (89 pedidos)</option>
                <option>Live #46 — Vestidos & Macacões</option>
              </select>
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <div className="t-mono-label mb-8">{produtos.length} produtos selecionados · arraste para reordenar depois</div>
            <div style={{maxHeight:340, overflowY:'auto', border:'1px solid var(--line)', borderRadius:8}}>
              {PRODUTOS.map(p => {
                const sel = produtos.includes(p.id);
                return (
                  <div key={p.id} className="row gap-10" onClick={() => toggleProduto(p.id)} style={{padding:'10px 12px', borderBottom:'1px solid var(--line)', cursor:'pointer', background: sel ? 'var(--accent-soft)' : 'transparent'}}>
                    <input type="checkbox" checked={sel} readOnly style={{accentColor:'var(--accent)'}}/>
                    <div className="product-thumb">{p.foto}</div>
                    <div style={{flex:1}}>
                      <div style={{fontSize:12.5, fontWeight:500}}>{p.nome}</div>
                      <div className="t-3 mono" style={{fontSize:10.5}}>{p.id} · {p.estoqueTotal} un</div>
                    </div>
                    <div className="mono t-green" style={{fontSize:13}}>{brl(p.precoLive)}</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {step === 3 && (
          <div className="stack-tight">
            <div style={{padding:14, background:'var(--bg-3)', borderRadius:8}}>
              <div className="t-mono-label mb-8">Segmentação dos convites</div>
              <div className="row" style={{flexWrap:'wrap', gap:6}}>
                <Badge kind="green">Champions + Leais</Badge>
                <Badge kind="cyan">Compraram na última live</Badge>
                <Badge kind="muted">+ filtro</Badge>
              </div>
              <div className="t-3 mt-12" style={{fontSize:11.5}}>Estimativa: <b className="t-accent">2.418 destinatários</b> · custo <b className="t-2">R$ 120,90</b></div>
            </div>
            <div className="row gap-10" style={{padding:12, background:'var(--bg-3)', borderRadius:8}}>
              <Toggle on/>
              <div style={{flex:1}}>
                <div style={{fontSize:13, fontWeight:500}}>Lembrete automático</div>
                <div className="t-3" style={{fontSize:11}}>1h antes da live · WhatsApp</div>
              </div>
            </div>
            <div className="row gap-10" style={{padding:12, background:'var(--bg-3)', borderRadius:8}}>
              <Toggle on/>
              <div style={{flex:1}}>
                <div style={{fontSize:13, fontWeight:500}}>Cashback de live</div>
                <div className="t-3" style={{fontSize:11}}>5% sobre cada pedido</div>
              </div>
            </div>
          </div>
        )}

        <div className="row mt-24" style={{justifyContent:'space-between'}}>
          <button className="btn ghost" onClick={() => step > 1 ? setStep(step-1) : onClose()}>
            {step === 1 ? "Cancelar" : "← Voltar"}
          </button>
          {step < 3
            ? <button className="btn primary" onClick={() => setStep(step+1)}>Próximo <Ic name="arrowRight" size={12}/></button>
            : <button className="btn primary" onClick={onCreate}>Criar live <Ic name="check" size={12}/></button>}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { LivePlanejamentoPage });
