// Módulo LIVE — Apresentar (mobile), Pedidos, Bag, Sortear

// ---------- APRESENTAR (mobile phone frame) ----------
const ApresentarPage = () => {
  const [presentingId, setPresentingId] = React.useState("AUR-2841");
  const [selectedSize, setSelectedSize] = React.useState(null);
  const [instagram, setInstagram] = React.useState("");
  const [orders, setOrders] = React.useState(PEDIDOS_LIVE.slice());

  const presenting = PRODUTOS.find(p => p.id === presentingId);
  const liveOrderCount = orders.filter(o => o.produto === presenting.nome).length;

  const registerOrder = () => {
    if (!selectedSize || !instagram) return;
    const tam = selectedSize;
    const novo = {
      nr: "L-" + (2848 + (orders.length - PEDIDOS_LIVE.length)),
      instagram: instagram.startsWith("@") ? instagram : "@" + instagram,
      cliente: "—",
      produto: presenting.nome,
      tam,
      valor: presenting.precoLive,
      status: "Sacola",
      hora: new Date().toLocaleTimeString("pt-BR").slice(0, 5),
    };
    setOrders([novo, ...orders]);
    setInstagram("");
    setSelectedSize(null);
  };

  return (
    <div className="page" style={{paddingBottom:80}}>
      <div className="page-head">
        <div>
          <span className="eyebrow"><span className="play"/>AO VIVO · Live #48 · 38m</span>
          <h1 style={{marginTop:10}}>Apresentar produto</h1>
          <p className="lead">Tela operada pelo apresentador no celular. Registra pedido em 1 toque por @ do Instagram.</p>
        </div>
        <div className="actions">
          <div className="mode-switch">
            <button className="active">Mobile</button>
            <button>Tablet</button>
          </div>
          <button className="btn ghost"><Ic name="pause" size={13}/> Pausar live</button>
          <button className="btn danger"><Ic name="x" size={13}/> Encerrar</button>
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'376px 1fr', gap:24 }}>
        {/* Phone preview */}
        <div className="phone-frame">
          <div className="phone-screen">
            <PhoneApresentar
              presenting={presenting}
              produtos={PRODUTOS}
              presentingId={presentingId}
              setPresentingId={(id) => { setPresentingId(id); setSelectedSize(null); }}
              selectedSize={selectedSize}
              setSelectedSize={setSelectedSize}
              instagram={instagram}
              setInstagram={setInstagram}
              registerOrder={registerOrder}
              liveOrderCount={liveOrderCount}
            />
          </div>
        </div>

        {/* Side panel — visão do que tá rolando */}
        <div className="stack">
          <div className="card">
            <div className="card-head">
              <h3>Pedidos da live · ao vivo</h3>
              <Badge kind="green" dot>{orders.length} pedidos</Badge>
            </div>
            <div className="stat-grid cols-4 mb-16">
              <Stat label="Faturado agora" value={brl(orders.reduce((s,o) => o.status !== 'Cancelado' ? s + o.valor : s, 0))} glow="green"/>
              <Stat label="Aguardando pgto" value={orders.filter(o => o.status === 'Aguardando pgto').length}/>
              <Stat label="Em sacola" value={orders.filter(o => o.status === 'Sacola').length} glow="cyan"/>
              <Stat label="Clientes únicos" value={new Set(orders.map(o => o.instagram)).size}/>
            </div>

            <div className="tbl-wrap" style={{maxHeight:380, overflowY:'auto'}}>
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Hora</th><th>@</th><th>Produto · Tam</th><th style={{textAlign:'right'}}>Valor</th><th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  {orders.map(o => (
                    <tr key={o.nr}>
                      <td className="mono t-3">{o.hora}</td>
                      <td className="strong">{o.instagram}</td>
                      <td className="t-3" style={{fontSize:11.5}}>{o.produto} <span className="mono">· {o.tam}</span></td>
                      <td className="num">{brl(o.valor)}</td>
                      <td><StatusBadge status={o.status}/></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <h3>Roteiro da live</h3>
              <span className="meta">10 produtos · 4 apresentados</span>
            </div>
            <div className="stack-tight">
              {PRODUTOS.slice(0, 6).map((p, i) => {
                const isPresenting = p.id === presentingId;
                const orderCount = orders.filter(o => o.produto === p.nome).length;
                return (
                  <div key={p.id} className={"live-product-card" + (isPresenting ? " presenting" : "")}
                       onClick={() => setPresentingId(p.id)}>
                    <span className="t-mono-label" style={{width:24}}>{String(i+1).padStart(2,'0')}</span>
                    <div className="product-thumb">{p.foto}</div>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontSize:13, fontWeight:500}}>{p.nome}</div>
                      <div className="row gap-8 t-3" style={{fontSize:11}}>
                        <span className="mono">{p.id}</span>
                        <span>·</span>
                        <span className="mono">{Object.entries(p.tamanhos).filter(([,q]) => q > 0).map(([t]) => t).join('/')}</span>
                      </div>
                    </div>
                    <div className="text-right">
                      <div style={{fontSize:13, fontWeight:500}} className="t-green">{brl(p.precoLive)}</div>
                      <div className="t-3" style={{fontSize:11, textDecoration:'line-through'}}>{brl(p.preco)}</div>
                    </div>
                    <div className="text-right" style={{minWidth:50}}>
                      <Badge kind={orderCount > 0 ? "accent" : "muted"}>{orderCount} pedidos</Badge>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Phone screen content — mobile operator view
const PhoneApresentar = ({ presenting, produtos, presentingId, setPresentingId, selectedSize, setSelectedSize, instagram, setInstagram, registerOrder, liveOrderCount }) => (
  <div style={{padding:'12px 14px', display:'flex', flexDirection:'column', height:'100%'}}>
    {/* Top status bar */}
    <div className="row gap-8 mb-12" style={{justifyContent:'space-between'}}>
      <div className="row gap-6">
        <span style={{width:7, height:7, background:'var(--red)', borderRadius:'50%', animation:'pulse 1.5s infinite'}}/>
        <span className="t-mono-label" style={{color:'var(--red)'}}>AO VIVO</span>
        <span className="t-3 mono" style={{fontSize:10}}>38:14</span>
      </div>
      <Ic name="settings" size={14} className="t-3"/>
    </div>

    {/* Big product card */}
    <div style={{background:'var(--bg-2)', border:'1px solid var(--accent)', borderRadius:12, padding:12, position:'relative', boxShadow:'0 0 0 1px var(--accent-glow)'}}>
      <div className="row gap-12">
        <div className="product-thumb xl">{presenting.foto}</div>
        <div style={{flex:1, minWidth:0}}>
          <div className="t-mono-label" style={{fontSize:9.5, letterSpacing:'0.16em'}}>APRESENTANDO · {presenting.id}</div>
          <div style={{fontSize:14, fontWeight:500, lineHeight:1.2, margin:'4px 0'}}>{presenting.nome}</div>
          <div className="row gap-6">
            <div className="t-green" style={{fontSize:18, fontWeight:600, fontFamily:'var(--mono)'}}>{brl(presenting.precoLive)}</div>
            <div className="t-3" style={{textDecoration:'line-through', fontSize:11}}>{brl(presenting.preco)}</div>
          </div>
          <Badge kind="accent" dot>{liveOrderCount} pedidos</Badge>
        </div>
      </div>
    </div>

    {/* Size grid */}
    <div className="t-mono-label mt-12 mb-12" style={{fontSize:10}}>Tamanhos · toque para selecionar</div>
    <div className="size-grid">
      {Object.entries(presenting.tamanhos).map(([t, q]) => (
        <button key={t}
          className={"size-chip" + (q === 0 ? " empty" : "") + (selectedSize === t ? " selected" : "") + (q > 0 && q <= 2 ? " low" : "")}
          style={{flex:1, height:48}}
          disabled={q === 0}
          onClick={() => setSelectedSize(t)}>
          <div style={{fontSize:13, fontWeight:500}}>{t}</div>
          <div className="qty">{q === 0 ? 'zero' : q + ' un'}</div>
        </button>
      ))}
    </div>

    {/* Order input */}
    <div className="mt-16" style={{marginTop:'auto'}}>
      <div className="t-mono-label mb-8" style={{fontSize:10}}>Registrar pedido · @instagram</div>
      <div style={{display:'flex', gap:6, marginBottom:8}}>
        <div className="input" style={{flex:1, height:40}}>
          <Ic name="instagram" size={14} className="t-3"/>
          <input
            value={instagram}
            onChange={e => setInstagram(e.target.value)}
            placeholder="@usuario"
            style={{flex:1, fontSize:13}}
            autoFocus/>
        </div>
      </div>
      <button
        className="btn primary"
        style={{width:'100%', height:44, fontSize:14}}
        disabled={!selectedSize || !instagram.trim()}
        onClick={registerOrder}>
        {selectedSize ? `Confirmar · ${presenting.nome.split(' ')[0]} · ${selectedSize}` : 'Selecione um tamanho'}
        <Ic name="arrowRight" size={14}/>
      </button>
    </div>

    {/* Quick product switcher */}
    <div className="t-mono-label mt-16 mb-8" style={{fontSize:10}}>Roteiro · próximos produtos</div>
    <div style={{display:'flex', gap:6, overflowX:'auto', paddingBottom:4}}>
      {produtos.slice(0, 6).map((p, i) => (
        <button key={p.id}
          onClick={() => setPresentingId(p.id)}
          style={{flexShrink:0, width:64, height:64, padding:0, background:'var(--bg-2)', border:'1px solid '+ (p.id === presentingId ? 'var(--accent)' : 'var(--line)'), borderRadius:8, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:2, cursor:'pointer'}}>
          <div style={{fontSize:22}}>{p.foto}</div>
          <div className="mono" style={{fontSize:8.5, color:'var(--text-3)'}}>{String(i+1).padStart(2,'0')}</div>
        </button>
      ))}
    </div>
  </div>
);

// ---------- PEDIDOS ----------
const LivePedidosPage = () => {
  const [tab, setTab] = React.useState("pedidos");
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <span className="eyebrow"><span className="play"/>Live em andamento</span>
          <h1 style={{marginTop:10}}>Pedidos da live</h1>
          <p className="lead">Todos os pedidos registrados nesta live + gestão de frete, juntou-levou e cashback.</p>
        </div>
        <div className="actions">
          <button className="btn ghost"><Ic name="download" size={13}/> Exportar</button>
          <button className="btn"><Ic name="truck" size={13}/> Gerar etiquetas (12)</button>
          <button className="btn primary"><Ic name="whatsapp" size={13}/> Avisar pendentes</button>
        </div>
      </div>

      <Tabs active={tab} onChange={setTab} tabs={[
        { id: "pedidos", label: "Pedidos", count: 47 },
        { id: "fretes", label: "Fretes" },
        { id: "itens", label: "Itens vendidos" },
        { id: "juntou", label: "Juntou levou" },
        { id: "creditos", label: "Créditos" },
        { id: "wpp", label: "WhatsApp" },
        { id: "cb", label: "Cashback" },
      ]}/>

      {tab === "pedidos" && (
        <div className="stack">
          <div className="stat-grid cols-4">
            <Stat glow="green" label="Faturado" value={brl(8240.50)}/>
            <Stat label="Aguardando pagamento" value="12" hint="R$ 2.140,80"/>
            <Stat label="Pagamento confirmado" value="31" hint="R$ 5.870,40"/>
            <Stat label="Cancelados" value="4" hint="R$ 432,60"/>
          </div>

          <div className="filter-row">
            <div className="input search">
              <Ic name="search" size={13} className="t-3"/>
              <input placeholder="@instagram, nº pedido, produto…"/>
            </div>
            <select className="input"><option>Todos os status</option><option>Pago</option><option>Aguardando</option></select>
            <select className="input"><option>Live atual (#48)</option><option>Live #47</option><option>Todas</option></select>
            <button className="btn ghost sm"><Ic name="filter" size={12}/> Mais filtros</button>
            <div style={{marginLeft:'auto'}} className="t-3" style={{fontSize:11.5}}>{PEDIDOS_LIVE.length} resultados</div>
          </div>

          <div className="tbl-wrap">
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{width:30}}><input type="checkbox" style={{accentColor:'var(--accent)'}}/></th>
                  <th>Nº</th><th>@Instagram</th><th>Cliente</th><th>Produto · Tam</th><th>Hora</th><th style={{textAlign:'right'}}>Valor</th><th>Status</th><th style={{width:60}}></th>
                </tr>
              </thead>
              <tbody>
                {PEDIDOS_LIVE.map(p => (
                  <tr key={p.nr}>
                    <td><input type="checkbox" style={{accentColor:'var(--accent)'}}/></td>
                    <td className="mono t-3">{p.nr}</td>
                    <td className="strong">{p.instagram}</td>
                    <td>{p.cliente}</td>
                    <td className="t-3">{p.produto} <span className="mono t-2">· {p.tam}</span></td>
                    <td className="mono t-3">{p.hora}</td>
                    <td className="num">{brl(p.valor)}</td>
                    <td><StatusBadge status={p.status}/></td>
                    <td className="row-action"><div className="menu-dot">⋯</div></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "fretes" && (
        <div className="card">
          <div className="card-head">
            <h3>Tabela de frete · Live #48</h3>
            <button className="btn sm"><Ic name="plus" size={11}/> Nova faixa</button>
          </div>
          <table className="tbl">
            <thead><tr><th>Região</th><th>Tipo</th><th>Valor</th><th>Frete grátis acima</th><th></th></tr></thead>
            <tbody>
              <tr><td>Goiânia capital</td><td>Motoboy</td><td className="num">{brl(12.00)}</td><td className="num">{brl(200.00)}</td><td><span className="menu-dot">⋯</span></td></tr>
              <tr><td>Centro-Oeste</td><td>Sedex</td><td className="num">{brl(28.50)}</td><td className="num">{brl(350.00)}</td><td><span className="menu-dot">⋯</span></td></tr>
              <tr><td>Sul/Sudeste</td><td>PAC</td><td className="num">{brl(34.90)}</td><td className="num">{brl(450.00)}</td><td><span className="menu-dot">⋯</span></td></tr>
              <tr><td>Nordeste</td><td>PAC</td><td className="num">{brl(42.00)}</td><td className="num">{brl(500.00)}</td><td><span className="menu-dot">⋯</span></td></tr>
              <tr><td>Norte</td><td>Sedex</td><td className="num">{brl(58.00)}</td><td className="num">{brl(600.00)}</td><td><span className="menu-dot">⋯</span></td></tr>
            </tbody>
          </table>
        </div>
      )}

      {tab === "itens" && (
        <div className="card">
          <div className="card-head">
            <h3>Itens vendidos na live</h3>
            <span className="meta">53 unidades</span>
          </div>
          <table className="tbl">
            <thead><tr><th>Produto</th><th>Marca</th><th>Tam</th><th>Qtd</th><th style={{textAlign:'right'}}>Total</th></tr></thead>
            <tbody>
              {PRODUTOS.slice(0, 7).map((p,i) => (
                <tr key={i}>
                  <td className="row gap-8"><div className="product-thumb">{p.foto}</div><span className="strong">{p.nome}</span></td>
                  <td className="t-3">{p.marca}</td>
                  <td className="mono">{Object.keys(p.tamanhos).slice(0,2).join(',')}</td>
                  <td className="num">{Math.floor(Math.random()*8)+2}</td>
                  <td className="num strong">{brl(p.precoLive * (Math.floor(Math.random()*8)+2))}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab === "juntou" && (
        <div className="card">
          <div className="card-head">
            <h3>Juntou Levou · ativo nesta live</h3>
            <Toggle on/>
          </div>
          <p className="t-2" style={{fontSize:13, maxWidth:600}}>Cliente que comprar 3+ peças na live ganha desconto automático no fechamento.</p>
          <div className="stat-grid cols-3 mt-16">
            <Stat label="Compre 3 peças" value="R$ 30" hint="de desconto"/>
            <Stat label="Compre 5 peças" value="R$ 70" hint="de desconto" glow/>
            <Stat label="Compre 8+ peças" value="R$ 150" hint="+ frete grátis" glow="green"/>
          </div>
          <div className="t-mono-label mt-16 mb-8">Aplicado a · 14 clientes nesta live</div>
          <BarH rows={[
            { label: "Compraram 3", value: 8, display: '8 cli', color: 'var(--accent)' },
            { label: "Compraram 5", value: 4, display: '4 cli', color: 'var(--accent)' },
            { label: "Compraram 8+", value: 2, display: '2 cli', color: 'var(--green)' },
          ]}/>
        </div>
      )}

      {(tab === "creditos" || tab === "wpp" || tab === "cb") && (
        <Empty icon={tab === 'wpp' ? 'whatsapp' : tab === 'cb' ? 'sparkles' : 'dollar'} title="Em construção neste protótipo" hint="Tela acessível mas sem dados mockados nesta versão."/>
      )}
    </div>
  );
};

// ---------- BAG ----------
const LiveBagPage = () => (
  <div className="page">
    <div className="page-head">
      <div>
        <span className="eyebrow"><span className="play"/>Sacolas abertas</span>
        <h1 style={{marginTop:10}}>Bag — sacolas em aberto</h1>
        <p className="lead">Clientes que adicionaram itens na live mas ainda não fecharam. Aviso automático após 1h.</p>
      </div>
      <div className="actions">
        <button className="btn ghost"><Ic name="settings" size={13}/> Regras de aviso</button>
        <button className="btn primary"><Ic name="whatsapp" size={13}/> Avisar todos (4)</button>
      </div>
    </div>

    <div className="stat-grid cols-4 mb-24">
      <Stat label="Sacolas abertas" value="4" glow="cyan"/>
      <Stat label="Valor em sacolas" value={brl(1807.30)}/>
      <Stat label="Tempo médio em aberto" value="27 min"/>
      <Stat label="Taxa fechamento (mês)" value="68%" delta={4.2}/>
    </div>

    <div className="card">
      <div className="card-head"><h3>Sacolas · live #48</h3><span className="meta">{SACOLAS.length} ativas</span></div>
      <div className="tbl-wrap">
        <table className="tbl">
          <thead>
            <tr><th>Cliente</th><th>@</th><th>Itens</th><th style={{textAlign:'right'}}>Valor</th><th>Aberta há</th><th>Status aviso</th><th></th></tr>
          </thead>
          <tbody>
            {SACOLAS.map((s, i) => (
              <tr key={i}>
                <td className="row gap-8"><ClientAvatar name={s.cliente}/> <span className="strong">{s.cliente}</span></td>
                <td className="t-3">{s.instagram}</td>
                <td className="num">{s.itens}</td>
                <td className="num">{brl(s.valor)}</td>
                <td className="mono">{s.abertaHa}</td>
                <td>{i === 2 ? <Badge kind="cyan">Aviso enviado</Badge> : <Badge kind="muted">Sem aviso</Badge>}</td>
                <td className="row-action row gap-4" style={{justifyContent:'flex-end'}}>
                  <button className="btn sm ghost"><Ic name="whatsapp" size={11}/> Avisar</button>
                  <button className="btn sm">Fechar</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  </div>
);

// ---------- SORTEAR ----------
const LiveSortearPage = () => {
  const [winner, setWinner] = React.useState(null);
  const [spinning, setSpinning] = React.useState(false);
  const [participants] = React.useState(CLIENTES.slice(0, 8));

  const sortear = () => {
    setSpinning(true);
    setWinner(null);
    setTimeout(() => {
      setSpinning(false);
      setWinner(participants[Math.floor(Math.random() * participants.length)]);
    }, 2400);
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <span className="eyebrow"><span className="play"/>Sorteio</span>
          <h1 style={{marginTop:10}}>Sortear ganhador</h1>
          <p className="lead">Sorteie entre clientes que compraram na live ou uma lista personalizada.</p>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 360px', gap:18}}>
        <div className="stack">
          <div className="card">
            <div className="card-head">
              <h3>Fonte do sorteio</h3>
              <select className="input" defaultValue="live"><option value="live">Clientes com pedido na live #48</option><option>Lista personalizada</option><option>@handles colados</option></select>
            </div>
            <div className="row gap-12 t-3" style={{fontSize:12, marginBottom:8}}>
              <span><b className="t-2">{participants.length}</b> participantes elegíveis</span>
              <span>·</span>
              <span>cada @ entra <b className="t-2">1×</b></span>
            </div>
          </div>

          <div className="sortear-stage">
            {spinning && (
              <div style={{textAlign:'center'}}>
                <div className="mono t-3 mb-16" style={{letterSpacing:'0.2em', fontSize:11}}>SORTEANDO…</div>
                <div style={{fontSize:32, fontFamily:'var(--mono)', fontWeight:500, letterSpacing:'-0.02em', minHeight:48}}>
                  {participants[Math.floor(Math.random() * participants.length)].instagram}
                </div>
                <Ic name="spinner" size={28} className="t-accent" style={{animation:'spin 0.8s linear infinite', marginTop:14}}/>
              </div>
            )}
            {!spinning && winner && (
              <div style={{textAlign:'center'}}>
                <div className="t-mono-label mb-12" style={{color:'var(--green)', letterSpacing:'0.24em'}}>★ GANHADORA ★</div>
                <ClientAvatar name={winner.nome} size="xl"/>
                <div style={{fontSize:24, fontWeight:500, marginTop:14}}>{winner.nome}</div>
                <div className="t-accent mono" style={{fontSize:14, marginTop:4}}>{winner.instagram}</div>
                <div className="row gap-8 mt-16" style={{justifyContent:'center'}}>
                  <button className="btn ghost" onClick={sortear}><Ic name="refresh" size={12}/> Repetir sorteio</button>
                  <button className="btn primary">Salvar resultado <Ic name="check" size={12}/></button>
                </div>
              </div>
            )}
            {!spinning && !winner && (
              <div style={{textAlign:'center'}}>
                <div style={{fontSize:48, marginBottom:8}}>🎁</div>
                <div className="t-2" style={{fontSize:14, marginBottom:16}}>Pronto pra sortear entre {participants.length} clientes</div>
                <button className="btn primary lg" onClick={sortear}>Girar a roleta <Ic name="play" size={14}/></button>
              </div>
            )}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <h3>Histórico de sorteios</h3>
            <a className="t-mono-label" style={{cursor:'pointer', color:'var(--text-2)'}}>Ver tudo</a>
          </div>
          <div className="stack-tight">
            {[
              { live: "Live #47", data: "12/05", ganhadora: "Renata Pacheco", premio: "Vestido Luna" },
              { live: "Live #46", data: "05/05", ganhadora: "Patrícia Souza", premio: "Vale R$ 200" },
              { live: "Live #45", data: "28/04", ganhadora: "Daniela Rocha", premio: "Cropped Pétala" },
              { live: "Live #44", data: "21/04", ganhadora: "Beatriz Almeida", premio: "Vale R$ 150" },
            ].map((h, i) => (
              <div key={i} className="row gap-10" style={{padding:'8px 0', borderBottom:'1px solid var(--line)'}}>
                <div style={{fontSize:18}}>🎁</div>
                <div style={{flex:1}}>
                  <div style={{fontSize:12.5, fontWeight:500}}>{h.ganhadora}</div>
                  <div className="t-3" style={{fontSize:11}}>{h.live} · {h.premio}</div>
                </div>
                <div className="mono t-3" style={{fontSize:11}}>{h.data}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
};

Object.assign(window, { ApresentarPage, LivePedidosPage, LiveBagPage, LiveSortearPage });
