/* Componentes de form reutilizaveis + widget Turnstile. */

const { useEffect, useRef } = React;


function Field({ label, hint, children }) {
    return (
        <div className="c-field">
            <label>{label}</label>
            {children}
            {hint && <span className="hint">{hint}</span>}
        </div>
    );
}


function Alert({ kind, children }) {
    if (!children) return null;
    return <div className={'c-alert c-alert-' + (kind || 'info')}>{children}</div>;
}


/*
 * Widget Cloudflare Turnstile.
 * Props:
 *   on_token(token):  callback quando o usuario resolve o desafio.
 *   reset_signal:     muda este valor pra forcar reset do widget.
 */
function Turnstile({ on_token, reset_signal }) {
    const container_ref = useRef(null);
    const widget_id_ref = useRef(null);

    useEffect(() => {
        // turnstile carregado?
        function try_render() {
            if (!window.turnstile) {
                setTimeout(try_render, 200);
                return;
            }
            if (!container_ref.current) return;
            widget_id_ref.current = window.turnstile.render(container_ref.current, {
                sitekey: window.C7_CONFIG.TURNSTILE_SITE_KEY,
                callback: (token) => { if (on_token) on_token(token); },
                'error-callback': () => {
                    // Apenas limpa o token; reset manual pelo usuario (F5)
                    // evita loop se for erro persistente de config
                    if (on_token) on_token(null);
                },
                'expired-callback': () => {
                    if (on_token) on_token(null);
                    if (window.turnstile && widget_id_ref.current) {
                        try { window.turnstile.reset(widget_id_ref.current); } catch (e) {}
                    }
                },
                theme: 'dark',
            });
        }
        try_render();
        return () => {
            if (window.turnstile && widget_id_ref.current) {
                try { window.turnstile.remove(widget_id_ref.current); } catch (e) {}
            }
        };
    }, []);

    useEffect(() => {
        if (window.turnstile && widget_id_ref.current) {
            try { window.turnstile.reset(widget_id_ref.current); } catch (e) {}
        }
    }, [reset_signal]);

    return <div ref={container_ref} style={{ marginTop: 8 }} />;
}


/*
 * Componente QR — gera local via lib qrcode (sem mandar payload pra
 * servico externo, importante pra PIX que carrega dados sensiveis).
 *
 * Props:
 *   data:    string a codificar (BR-Code PIX, otpauth://, etc).
 *   size:    pixels (default 220).
 *   margin:  padding interno em modulos (default 1).
 */
function QRImage({ data, size, margin }) {
    const [src, setSrc] = React.useState(null);
    const [err, setErr] = React.useState(null);

    React.useEffect(() => {
        if (!data) { setSrc(null); return; }
        let cancelled = false;
        function try_gen() {
            if (!window.qrcode) {
                setTimeout(try_gen, 100);
                return;
            }
            try {
                // typeNumber=0 (auto) + errorCorrectionLevel='M'
                const qr = window.qrcode(0, 'M');
                qr.addData(String(data));
                qr.make();
                const moduleCount = qr.getModuleCount();
                const px = size || 220;
                const mgn = margin == null ? 1 : margin;
                const cellSize = Math.floor(px / (moduleCount + mgn * 2));
                if (cancelled) return;
                setSrc(qr.createDataURL(cellSize, mgn));
            } catch (e) {
                if (!cancelled) setErr(String(e));
            }
        }
        try_gen();
        return () => { cancelled = true; };
    }, [data, size, margin]);

    if (err) return <div style={{color:'#ff6b6b', fontSize:12}}>QR: {err}</div>;
    if (!src) return <div style={{width: size || 220, height: size || 220,
                                    background: '#1a1a1f'}} />;
    return <img alt="QR" src={src}
                style={{display:'block', width: size || 220, height: size || 220,
                         imageRendering: 'pixelated'}} />;
}


/*
 * Toast — substitui alert() nativo por uma faixa estilizada no canto.
 * Auto-dismiss em 4s; clique fecha imediatamente.
 *
 * Uso (imperativo, fora de componentes):
 *   window.C7_Toast.show('erro: ...', 'error');
 *   window.C7_Toast.show('salvo', 'ok');
 */
(function setup_toast() {
    let container = null;
    function ensure_container() {
        if (container && document.body.contains(container)) return container;
        container = document.createElement('div');
        container.id = 'c7-toast-container';
        Object.assign(container.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            zIndex: '99999',
            display: 'flex',
            flexDirection: 'column',
            gap: '8px',
            pointerEvents: 'none',
        });
        document.body.appendChild(container);
        return container;
    }
    function show(message, kind) {
        const root = ensure_container();
        const t = document.createElement('div');
        const colors = {
            error: { bg: 'rgba(217,54,44,0.95)',  border: '#ff6b6b' },
            ok:    { bg: 'rgba(55,178,77,0.95)',  border: '#51cf66' },
            warn:  { bg: 'rgba(255,200,87,0.95)', border: '#ffc857' },
            info:  { bg: 'rgba(77,171,247,0.95)', border: '#4dabf7' },
        };
        const c = colors[kind] || colors.info;
        Object.assign(t.style, {
            background: c.bg,
            color: '#fff',
            border: `1px solid ${c.border}`,
            borderRadius: '4px',
            padding: '10px 16px',
            fontFamily: 'var(--c7-font-mono, monospace)',
            fontSize: '13px',
            maxWidth: '380px',
            cursor: 'pointer',
            pointerEvents: 'auto',
            boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
            transition: 'opacity 0.2s',
        });
        t.textContent = String(message);
        t.onclick = () => t.remove();
        root.appendChild(t);
        setTimeout(() => {
            t.style.opacity = '0';
            setTimeout(() => t.remove(), 200);
        }, 4000);
    }
    window.C7_Toast = { show };
})();


window.C7_Forms = { Field, Alert, Turnstile, QRImage };
