/* PORCEVILLE — Painel Comercial (INTERNO, protegido por PIN).
   Mostra os preços e gera o orçamento para enviar ao cliente.
   O cliente NUNCA acessa esta tela. */

function brlP(v) { return 'R$ ' + Number(v).toFixed(2).replace('.', ','); }

function AdminPanel({ app }) {
  const [pin, setPin] = React.useState('');
  const [ok, setOk] = React.useState(false);
  const [err, setErr] = React.useState(false);
  const [includeName, setIncludeName] = React.useState(false);
  const [discount, setDiscount] = React.useState(0);

  const tryPin = (v) => {
    if (v.length === 4) {
      if (v === PORCE_PRICES.PIN) { setOk(true); setErr(false); }
      else { setErr(true); setPin(''); setTimeout(() => setErr(false), 1200); }
    }
  };
  const press = (d) => { const v = (pin + d).slice(0, 4); setPin(v); tryPin(v); };

  // ----- PIN gate -----
  if (!ok) {
    return (
      <>
        <div className="overlay" onClick={app.closeAdmin} />
        <div className="sheet" style={{ height: 'auto', paddingBottom: 30 }}>
          <div className="sheet-grip" />
          <div style={{ padding: '12px 24px 8px', textAlign: 'center' }}>
            <div style={{ width: 52, height: 52, borderRadius: '50%', background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
              <PIcon name="lock" size={24} stroke="var(--gold)" />
            </div>
            <div className="h2">Área Comercial</div>
            <p className="muted" style={{ fontSize: 13, margin: '6px auto 0', maxWidth: 240 }}>Acesso restrito à equipe Porceville. Digite o PIN.</p>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 10, margin: '18px 0', animation: err ? 'shake .4s' : 'none' }}>
            {[0, 1, 2, 3].map(i => (
              <div key={i} style={{ width: 16, height: 16, borderRadius: '50%', background: pin.length > i ? (err ? 'var(--danger)' : 'var(--navy)') : 'var(--porc-2)', transition: 'background .15s' }} />
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10, padding: '0 40px' }}>
            {[1, 2, 3, 4, 5, 6, 7, 8, 9].map(n => (
              <button key={n} onClick={() => press(String(n))} style={padBtn}>{n}</button>
            ))}
            <div />
            <button onClick={() => press('0')} style={padBtn}>0</button>
            <button onClick={() => setPin(pin.slice(0, -1))} style={{ ...padBtn, fontSize: 18, color: 'var(--ink-soft)' }}>⌫</button>
          </div>
        </div>
        <style>{`@keyframes shake{0%,100%{transform:translateX(0)}25%{transform:translateX(-8px)}75%{transform:translateX(8px)}}`}</style>
      </>
    );
  }

  // ----- Painel com preços -----
  const lines = app.quote.map(e => ({ entry: e, q: PORCE_PRICES.lineQuote(e, includeName) }));
  const pricedSubtotal = lines.reduce((s, l) => s + (l.q.priced ? l.q.total : 0), 0);
  const hasUnpriced = lines.some(l => !l.q.priced);
  const total = pricedSubtotal * (1 - discount / 100);

  const genWhats = () => {
    const body = lines.map(l => {
      const e = l.entry;
      const eng = engravingLabel(e);
      if (!l.q.priced) return `• ${e.qty}× ${e.name} (${eng}) — a definir`;
      return `• ${e.qty}× ${e.name} (${eng}) — ${brlP(l.q.withName)}/un = ${brlP(l.q.total)}`;
    }).join('\n');
    const validade = (PORCE_DATA.settings && PORCE_DATA.settings.validade_dias) || 7;
    const prazo = (PORCE_DATA.settings && PORCE_DATA.settings.prazo_producao) || '20–30 dias';
    const msg = `*Orçamento Porceville*\n\n${body}\n\n${discount > 0 ? `Desconto: ${discount}%\n` : ''}*Total: ${brlP(total)}*\n\nValores válidos por ${validade} dias. Prazo de produção: ${prazo}.`;
    return encodeURIComponent(msg);
  };

  return (
    <>
      <div className="overlay" onClick={app.closeAdmin} />
      <div className="sheet" style={{ height: '92%' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '16px 18px 12px', borderBottom: '1px solid var(--line)' }}>
          <div style={{ width: 34, height: 34, borderRadius: '50%', background: 'var(--navy)', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
            <PIcon name="lock" size={17} stroke="var(--gold)" />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--navy)', fontFamily: 'var(--font-display)' }}>Painel Comercial</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-mute)' }}>Preços internos · não exibidos ao cliente</div>
          </div>
          <button onClick={app.closeAdmin} style={{ border: 'none', background: 'var(--porc-2)', borderRadius: '50%', width: 34, height: 34, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <PIcon name="close" size={18} stroke="var(--ink)" />
          </button>
        </div>

        <div className="scroll" style={{ flex: 1, padding: '14px 18px 20px' }}>
          {app.quote.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--ink-mute)' }}>
              <PIcon name="doc" size={34} stroke="var(--ink-mute)" />
              <p style={{ fontSize: 14, marginTop: 10 }}>Nenhum item na seleção do cliente ainda.</p>
            </div>
          ) : (
            <>
              {/* opções de cálculo */}
              <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
                <button className={`chip ${includeName ? 'active' : ''}`} onClick={() => setIncludeName(!includeName)}>
                  <PIcon name="check" size={14} stroke={includeName ? '#fff' : 'var(--ink-soft)'} /> Incluir nome (+{brlP(PORCE_PRICES.ADD_NAME)}/pç)
                </button>
                {[0, 5, 10, 15].map(d => (
                  <button key={d} className={`chip ${discount === d ? 'active' : ''}`} onClick={() => setDiscount(d)}>Desc. {d}%</button>
                ))}
              </div>

              {/* linhas com preço */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {lines.map(({ entry: e, q }) => (
                  <div key={e.key} className="card" style={{ padding: 13 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--navy)' }}>{e.qty}× {e.name}</div>
                        <div className="muted" style={{ fontSize: 12, marginTop: 2 }}>{engravingLabel(e)}</div>
                      </div>
                      <div style={{ textAlign: 'right', flex: 'none' }}>
                        {q.priced ? (
                          <>
                            <div style={{ fontWeight: 800, fontSize: 15, color: 'var(--navy)' }}>{brlP(q.total)}</div>
                            <div className="muted" style={{ fontSize: 11 }}>{brlP(q.withName)}/un</div>
                          </>
                        ) : (
                          <div className="quote-tag" style={{ fontSize: 13 }}>a definir</div>
                        )}
                      </div>
                    </div>
                    {!q.priced && (
                      <div style={{ fontSize: 11, color: 'var(--gold-700)', marginTop: 6, fontWeight: 700 }}>
                        {e.colors === 'colorido' ? 'Sublimação — tabela ainda não cadastrada.' : 'Produto sem tabela de serigrafia cadastrada.'}
                      </div>
                    )}
                  </div>
                ))}
              </div>

              {/* totais */}
              <div className="card" style={{ padding: 16, marginTop: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, color: 'var(--ink-soft)', marginBottom: 6 }}>
                  <span>Subtotal {hasUnpriced ? '(itens com preço)' : ''}</span><span style={{ fontWeight: 700 }}>{brlP(pricedSubtotal)}</span>
                </div>
                {discount > 0 && (
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13.5, color: 'var(--green)', marginBottom: 6 }}>
                    <span>Desconto {discount}%</span><span style={{ fontWeight: 700 }}>− {brlP(pricedSubtotal * discount / 100)}</span>
                  </div>
                )}
                <div className="hr" style={{ margin: '8px 0' }} />
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                  <span style={{ fontWeight: 800, fontSize: 15, color: 'var(--navy)' }}>Total</span>
                  <span className="display" style={{ fontSize: 24, color: 'var(--navy)' }}>{brlP(total)}</span>
                </div>
                {hasUnpriced && <div style={{ fontSize: 11.5, color: 'var(--gold-700)', marginTop: 8, fontWeight: 700 }}>⚠ Há itens sem preço — confira antes de enviar.</div>}
              </div>
            </>
          )}
        </div>

        {app.quote.length > 0 && (
          <div style={{ padding: '12px 18px 26px', borderTop: '1px solid var(--line)', background: 'var(--surface)', display: 'flex', gap: 10 }}>
            <button className="btn btn-ghost" style={{ flex: 'none' }} onClick={() => window.print()}>
              <PIcon name="doc" size={18} /> PDF
            </button>
            <a className="btn btn-whats" style={{ flex: 1, textDecoration: 'none' }}
              href={`https://wa.me/?text=${genWhats()}`} target="_blank" rel="noopener noreferrer">
              <PIcon name="whats" size={19} stroke="#fff" /> Enviar orçamento ao cliente
            </a>
          </div>
        )}
      </div>
    </>
  );
}
const padBtn = { padding: '14px 0', fontSize: 22, fontWeight: 700, fontFamily: 'var(--font-body)', border: 'none', background: 'var(--porc-2)', borderRadius: 14, color: 'var(--navy)', cursor: 'pointer' };

Object.assign(window, { AdminPanel });
