// floating.jsx — Floating CTA + WhatsApp button + WhatsApp modal.
// Modal submit registra lead via api.registrarLead (mesmo endpoint que o
// Continuar do Step 1), aproveitando o LeadId no backend.

function abrirWhatsApp({ unidade, nome, telefone }) {
    const msg = nome
        ? `Olá! Meu nome é ${nome} e tenho interesse em agendar uma avaliação do meu veículo${telefone ? `. Meu telefone é ${telefone}` : ''}. (Unidade ${unidade.nome})`
        : `Olá! Tenho interesse em agendar uma avaliação na unidade ${unidade.nome}.`;
    return `https://wa.me/${unidade.whatsapp}?text=${encodeURIComponent(msg)}`;
}

function WhatsAppModal({ open, onClose }) {
    const { unidade } = useUnidade();
    const [nome, setNome] = React.useState('');
    const [tel, setTel] = React.useState('');
    const [errors, setErrors] = React.useState({});
    const [loading, setLoading] = React.useState(false);
    const [sent, setSent] = React.useState(false);

    React.useEffect(() => {
        if (!open) { setSent(false); setErrors({}); setLoading(false); }
    }, [open]);

    if (!open) return null;

    const submit = async () => {
        const e = {};
        if (!nome.trim()) e.nome = 'Informe seu nome';
        if (digits(tel).length !== 11) e.tel = 'Telefone deve ter 11 dígitos';
        setErrors(e);
        if (Object.keys(e).length > 0) return;

        setLoading(true);
        try {
            // Registra lead (mesmo endpoint do Continuar Step 1). LeadId não é
            // necessário aqui — só queremos o registro + tracking de UTMs.
            await window.api.registrarLead({
                FilialId: unidade.filialId,
                nome: nome,
                telefone: digits(tel),
                whatsapp: true,
            });
            window.api.gtmEvent('whatsapp_contato', {
                unidade: unidade.slug,
                form_lp: 'quero-vender',
            });
        } catch (err) {
        } finally {
            setLoading(false);
            setSent(true);
            const url = abrirWhatsApp({ unidade, nome, telefone: tel });
            window.location.href = url;
            setTimeout(() => { onClose(); setNome(''); setTel(''); }, 1500);
        }
    };

    return (
        <div onClick={onClose} style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            zIndex: 1000, padding: 20, animation: 'fadeIn 200ms ease',
        }}>
            <div onClick={e => e.stopPropagation()} style={{
                background: '#fff', borderRadius: 16, padding: 28,
                maxWidth: 420, width: '100%', position: 'relative',
                animation: 'slideUp 280ms ease',
            }}>
                <button onClick={onClose} style={{
                    position: 'absolute', top: 14, right: 14, background: 'none', border: 'none',
                    cursor: 'pointer', width: 32, height: 32, borderRadius: '50%',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                    <Icon name="close" size={18} color="#5B5B5B" stroke={2} />
                </button>

                {sent ? (
                    <div style={{ textAlign: 'center', padding: '20px 0' }}>
                        <div style={{
                            width: 56, height: 56, borderRadius: '50%', background: 'rgba(37,211,102,0.1)',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            margin: '0 auto 16px',
                        }}>
                            <Icon name="whatsapp" size={28} color="#25D366" />
                        </div>
                        <h3 style={{ fontFamily: "'Roboto',sans-serif", fontWeight: 500, fontSize: 19, color: '#2D2D2D', marginBottom: 6 }}>
                            Redirecionando…
                        </h3>
                        <p style={{ fontFamily: "'Roboto',sans-serif", fontSize: 13, color: '#5B5B5B' }}>
                            Você está sendo levado para o WhatsApp.
                        </p>
                    </div>
                ) : (
                    <>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6 }}>
                            <div style={{
                                width: 40, height: 40, borderRadius: '50%', background: '#25D366',
                                display: 'flex', alignItems: 'center', justifyContent: 'center',
                            }}>
                                <Icon name="whatsapp" size={22} color="#fff" />
                            </div>
                            <h3 style={{ fontFamily: "'Roboto',sans-serif", fontWeight: 500, fontSize: 18, color: '#2D2D2D' }}>
                                Falar com um especialista
                            </h3>
                        </div>
                        <p style={{ fontFamily: "'Roboto',sans-serif", fontSize: 13, color: '#5B5B5B', marginBottom: 20, lineHeight: 1.5 }}>
                            Preencha seus dados e te conectamos agora mesmo com a equipe da unidade {unidade.nome}.
                        </p>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                            <Field label="Nome completo" required error={errors.nome}>
                                <input value={nome} onChange={e => setNome(e.target.value)} placeholder="Seu nome" style={inputStyle(errors.nome)} />
                            </Field>
                            <Field label="Telefone / WhatsApp" required error={errors.tel}>
                                <input value={tel} onChange={e => setTel(maskPhone(e.target.value))} placeholder="(11) 99999-9999" style={inputStyle(errors.tel)} inputMode="numeric" />
                            </Field>
                        </div>
                        <button onClick={submit} disabled={loading} style={{
                            width: '100%', marginTop: 18, padding: '13px 20px', borderRadius: 8,
                            background: loading ? '#a8d9b6' : '#25D366', color: '#fff', border: 'none',
                            fontFamily: "'Roboto',sans-serif", fontSize: 15, fontWeight: 500,
                            cursor: loading ? 'wait' : 'pointer',
                            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                        }}>
                            {loading ? (
                                <>
                                    <span style={{
                                        width: 16, height: 16, borderRadius: '50%',
                                        border: '2px solid rgba(255,255,255,0.3)', borderTopColor: '#fff',
                                        animation: 'spin 700ms linear infinite',
                                    }} />
                                    Aguarde...
                                </>
                            ) : (
                                <>
                                    <Icon name="whatsapp" size={18} color="#fff" />
                                    Quero falar agora no WhatsApp
                                </>
                            )}
                        </button>
                        <p style={{
                            fontFamily: "'Roboto',sans-serif", fontSize: 11, color: '#919191',
                            textAlign: 'center', marginTop: 10,
                        }}>
                            Respondemos em minutos durante horário comercial.
                        </p>
                    </>
                )}
            </div>
        </div>
    );
}

function FloatingButtons({ onCTA, onWhatsApp, hideAgendar }) {
    return (
        <div style={{
            position: 'fixed', right: 18, bottom: 18, zIndex: 900,
            display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-end',
        }}>
            {!hideAgendar && (
                <button onClick={onCTA} style={{
                    padding: '12px 20px', borderRadius: 999,
                    background: '#E31018', color: '#fff', border: 'none',
                    fontFamily: "'Roboto',sans-serif", fontSize: 14, fontWeight: 500,
                    cursor: 'pointer', boxShadow: '0 8px 24px rgba(227,16,24,0.4)',
                    display: 'inline-flex', alignItems: 'center', gap: 8,
                    animation: 'slideUp 320ms ease',
                }}>
                    <Icon name="calendar" size={16} color="#fff" stroke={2.2} />
                    Agendar Agora
                </button>
            )}
            <button onClick={onWhatsApp} aria-label="Falar no WhatsApp" style={{
                width: 56, height: 56, borderRadius: '50%',
                background: '#25D366', color: '#fff', border: 'none',
                cursor: 'pointer', boxShadow: '0 8px 24px rgba(37,211,102,0.4)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                position: 'relative',
            }}>
                <span style={{
                    position: 'absolute', inset: 0, borderRadius: '50%',
                    background: '#25D366', animation: 'pulse 2s ease-out infinite',
                    opacity: 0.5,
                }} />
                <Icon name="whatsapp" size={28} color="#fff" />
            </button>
        </div>
    );
}

Object.assign(window, { WhatsAppModal, FloatingButtons, abrirWhatsApp });
