// components/BannerPanel.jsx — Зээлийн бараа реклам panel (TDS / baron.mn)
// PHP endpoint: http://208.91.198.196/api/credit-products.php

const TDS_BASE_URL = 'http://208.91.198.196';

function BannerPanel({ isOpen, onClose, orderBaseUrl, apiUrl }) {
    const { useState, useEffect, useCallback, useRef } = React;

    const [products, setProducts]   = useState([]);
    const [loading, setLoading]     = useState(false);
    const [error, setError]         = useState(null);
    const [orderItem, setOrderItem] = useState(null); // Захиалах барааны modal
    const [orderName, setOrderName] = useState('');
    const [orderPhone, setOrderPhone] = useState('');
    const [orderQty, setOrderQty]   = useState(1);
    const [orderSent, setOrderSent] = useState(false);
    const [orderLoading, setOrderLoading] = useState(false);
    const slideRef = useRef(null);

    const BASE_URL  = (orderBaseUrl || TDS_BASE_URL).replace(/\/$/, '');
    const FETCH_URL = apiUrl || `${BASE_URL}/api/credit-products.php`;

    // Бараа татах
    const fetchProducts = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const r = await fetch(FETCH_URL, { signal: AbortSignal.timeout(8000) });
            if (!r.ok) throw new Error(`HTTP ${r.status}`);
            const data = await r.json();
            const list = Array.isArray(data) ? data : (data.products || data.data || []);
            setProducts(list);
        } catch(e) {
            // Холболт байхгүй үед дэлгэрэнгүй жишиг бараа харуулах
            setProducts(SAMPLE_PRODUCTS);
            setError(null); // sample-г харуулна, алдаа гаргахгүй
        }
        setLoading(false);
    }, [FETCH_URL]);

    useEffect(() => { if (isOpen) fetchProducts(); }, [isOpen]);

    // Захиалга илгээх
    const submitOrder = async () => {
        if (!orderName.trim() || !orderPhone.trim()) return;
        setOrderLoading(true);
        try {
            const payload = {
                product_id:   orderItem?.id,
                product_name: orderItem?.name,
                name:         orderName,
                phone:        orderPhone,
                quantity:     orderQty,
            };
            // baron.mn захиалга endpoint
            await fetch(`${BASE_URL}/api/order.php`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload),
                signal: AbortSignal.timeout(8000),
            }).catch(()=>{}); // алдаа гарсан ч дараагийн алхам руу үргэлжлүүлнэ
            setOrderSent(true);
        } catch(e) {}
        setOrderLoading(false);
    };

    const closeOrder = () => { setOrderItem(null); setOrderSent(false); setOrderName(''); setOrderPhone(''); setOrderQty(1); };

    const fmt = n => Math.round(parseFloat(n)||0).toLocaleString('mn-MN');

    if (!isOpen) return null;

    return (
        <>
        {/* ── Overlay (mobile) ── */}
        <div className="banner-overlay" onClick={onClose} />

        {/* ── Panel ── */}
        <div className="banner-panel" ref={slideRef}>

            {/* Header — TDS лого */}
            <div className="banner-header">
                <div style={{display:'flex',alignItems:'center',gap:10}}>
                    <div className="tds-logo">TDS</div>
                    <div>
                        <div style={{fontWeight:700,fontSize:14,color:'white',lineHeight:1.2}}>Зээлийн бараа</div>
                        <div style={{fontSize:11,color:'rgba(255,255,255,0.75)'}}>baron.mn</div>
                    </div>
                </div>
                <div style={{display:'flex',gap:8,alignItems:'center'}}>
                    <button onClick={fetchProducts} title="Шинэчлэх"
                        style={{background:'rgba(255,255,255,0.2)',border:'none',color:'white',
                            borderRadius:6,padding:'4px 8px',cursor:'pointer',fontSize:16}}
                    >↻</button>
                    <button onClick={onClose}
                        style={{background:'rgba(255,255,255,0.2)',border:'none',color:'white',
                            borderRadius:6,padding:'4px 8px',cursor:'pointer',fontSize:18,lineHeight:1}}
                    >×</button>
                </div>
            </div>

            {/* Бараа жагсаалт */}
            <div className="banner-body">
                {loading && (
                    <div style={{textAlign:'center',padding:40,color:'#667eea'}}>Уншиж байна...</div>
                )}

                {!loading && products.map((p, i) => (
                    <div key={p.id||i} className="banner-product-card">
                        {p.image && (
                            <img src={p.image} alt={p.name}
                                style={{width:'100%',height:130,objectFit:'cover',
                                    borderRadius:'8px 8px 0 0',display:'block'}}
                                onError={e=>e.target.style.display='none'}/>
                        )}
                        <div style={{padding:'10px 12px 12px'}}>
                            <div style={{fontWeight:700,fontSize:13,color:'#2c3e50',
                                marginBottom:4,lineHeight:1.3}}>{p.name}</div>

                            {p.price && (
                                <div style={{fontSize:15,fontWeight:'bold',color:'#e74c3c',marginBottom:4}}>
                                    {fmt(p.price)}₮
                                </div>
                            )}

                            {(p.monthly_payment || p.credit_info) && (
                                <div style={{fontSize:11,color:'#27ae60',fontWeight:600,marginBottom:8}}>
                                    {p.credit_info || `Сар бүр: ${fmt(p.monthly_payment)}₮`}
                                    {p.credit_months ? ` × ${p.credit_months}с` : ''}
                                </div>
                            )}

                            <div style={{display:'flex',gap:6}}>
                                <button
                                    onClick={()=>{ setOrderItem(p); setOrderSent(false); setOrderName(''); setOrderPhone(''); setOrderQty(1); }}
                                    className="banner-order-btn"
                                >🛒 Захиалах</button>
                                {p.url && (
                                    <button onClick={()=>window.open(p.url||`${BASE_URL}/product/${p.id}`,'_blank')}
                                        style={{padding:'6px 10px',borderRadius:6,border:'1px solid #667eea',
                                            background:'white',color:'#667eea',cursor:'pointer',fontSize:11,fontWeight:600}}
                                    >Дэлгэрэнгүй</button>
                                )}
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {/* Footer */}
            <div style={{padding:'10px 14px',borderTop:'1px solid #e9ecef',
                display:'flex',alignItems:'center',justifyContent:'space-between'}}>
                <span style={{fontSize:11,color:'#95a5a6'}}>baron.mn — Зээлийн бараа</span>
                <button onClick={()=>window.open(`${BASE_URL}`,'_blank')}
                    style={{padding:'6px 14px',background:'#667eea',color:'white',
                        border:'none',borderRadius:6,cursor:'pointer',fontSize:12,fontWeight:600}}>
                    baron.mn →
                </button>
            </div>
        </div>

        {/* ── Захиалах modal ── */}
        {orderItem && (
            <div className="modal-overlay" style={{zIndex:20000}} onClick={closeOrder}>
            <div className="modal-content" onClick={e=>e.stopPropagation()} style={{maxWidth:400}}>
                <div className="modal-header">
                    <h2>🛒 Захиалга</h2>
                    <button className="modal-close" onClick={closeOrder}>×</button>
                </div>
                <div className="modal-body">
                    {orderSent ? (
                        <div style={{textAlign:'center',padding:20}}>
                            <div style={{fontSize:40,marginBottom:12}}>✅</div>
                            <div style={{fontWeight:700,fontSize:16,color:'#27ae60',marginBottom:8}}>
                                Захиалга амжилттай илгээгдлээ!
                            </div>
                            <div style={{fontSize:13,color:'#7f8c8d',marginBottom:16}}>
                                baron.mn-ийн менежер тантай холбогдох болно.
                            </div>
                            <button className="btn btn-primary" onClick={closeOrder}>Хаах</button>
                        </div>
                    ) : (
                        <>
                        <div style={{background:'#f8f9fa',borderRadius:8,padding:'10px 14px',marginBottom:16}}>
                            <div style={{fontWeight:700,fontSize:14,color:'#2c3e50'}}>{orderItem.name}</div>
                            {orderItem.price && (
                                <div style={{fontSize:13,color:'#e74c3c',marginTop:2}}>{fmt(orderItem.price)}₮</div>
                            )}
                        </div>
                        <div className="form-group">
                            <label>Нэр <span style={{color:'red'}}>*</span></label>
                            <input className="form-input" placeholder="Таны нэр" value={orderName}
                                onChange={e=>setOrderName(e.target.value)} autoFocus/>
                        </div>
                        <div className="form-group">
                            <label>Утасны дугаар <span style={{color:'red'}}>*</span></label>
                            <input className="form-input" placeholder="99XXXXXX" value={orderPhone}
                                onChange={e=>setOrderPhone(e.target.value)} type="tel"/>
                        </div>
                        <div className="form-group">
                            <label>Тоо хэмжээ</label>
                            <input className="form-input" type="number" min="1" value={orderQty}
                                onChange={e=>setOrderQty(parseInt(e.target.value)||1)} style={{width:80}}/>
                        </div>
                        </>
                    )}
                </div>
                {!orderSent && (
                <div className="modal-footer">
                    <button className="btn btn-secondary" onClick={closeOrder}>Буцах</button>
                    <button className="btn btn-primary" onClick={submitOrder}
                        disabled={orderLoading || !orderName.trim() || !orderPhone.trim()}>
                        {orderLoading ? 'Илгээж байна...' : '📤 Захиалга илгээх'}
                    </button>
                </div>
                )}
            </div>
            </div>
        )}
        </>
    );
}

// ── Жишиг бараанууд (API байхгүй үед) ─────────────────────
const SAMPLE_PRODUCTS = [
    { id:1, name:'Samsung 55" Smart TV', price:1800000, monthly_payment:150000, credit_months:12,
      credit_info:'Сар бүр 150,000₮ × 12 сар', image:'', url:'' },
    { id:2, name:'LG Washing Machine 8kg', price:1200000, monthly_payment:100000, credit_months:12,
      credit_info:'Сар бүр 100,000₮ × 12 сар', image:'', url:'' },
    { id:3, name:'iPhone 15 128GB', price:2400000, monthly_payment:200000, credit_months:12,
      credit_info:'Сар бүр 200,000₮ × 12 сар', image:'', url:'' },
    { id:4, name:'Laptop Asus VivoBook', price:1600000, monthly_payment:135000, credit_months:12,
      credit_info:'Сар бүр 135,000₮ × 12 сар', image:'', url:'' },
];

if (typeof window !== 'undefined') window.BannerPanel = BannerPanel;
