/* global React */
const { useState, useEffect } = React;

const BRIDGE_URL = 'https://ipbridge.indiegroup.id';

const STATUS_LABEL = {
  pending_payment: { label: 'Menunggu pembayaran', color: '#D97706' },
  paid:            { label: 'Dibayar', color: '#059669' },
  processing:      { label: 'Diproses', color: '#2563EB' },
  shipped:         { label: 'Dikirim', color: '#7C3AED' },
  delivered:       { label: 'Terkirim', color: '#059669' },
  cancelled:       { label: 'Dibatalkan', color: '#DC2626' },
};

function OrdersPage({ navigate }) {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!window.IndieAuth.isLoggedIn()) { navigate('/gallery'); return; }
    const profile = window.IndieAuth.getProfile();
    if (!profile?.email) { setLoading(false); return; }

    fetch(BRIDGE_URL + '/orders?email=' + encodeURIComponent(profile.email))
      .then(r => r.json())
      .then(d => {
        if (d.ok) setOrders(d.orders || []);
        else setError(d.error);
        setLoading(false);
      })
      .catch(e => { setError(e.message); setLoading(false); });
  }, []);

  return (
    <main className="fade-in">
      <div className="shell" style={{paddingBlock:'clamp(32px,6vw,64px)'}}>
        <nav className="crumb" style={{marginBottom:32}}>
          <a onClick={() => navigate('/gallery')}>Gallery</a>
          <span className="sep">/</span>
          <span className="here">Riwayat Order</span>
        </nav>
        <h2 style={{marginBottom:24}}>Riwayat Order</h2>

        {loading && <div style={{color:'var(--ink-meta)',fontFamily:'var(--font-mono)',fontSize:13}}>Memuat orders…</div>}
        {error && <div style={{color:'#DC2626',fontSize:13}}>{error}</div>}
        {!loading && orders.length === 0 && (
          <div style={{padding:'60px 0',textAlign:'center',color:'var(--ink-meta)'}}>
            <p>Belum ada order.</p>
            <button className="btn btn-primary" onClick={() => navigate('/gallery')}>Browse kertas →</button>
          </div>
        )}
        {orders.map(order => {
          const st = STATUS_LABEL[order.status] || { label: order.status, color: '#6B7280' };
          return (
            <div key={order.id} style={{border:'1px solid var(--paper-card-edge)',marginBottom:12,background:'var(--paper-card)'}}>
              <div style={{padding:'16px 20px',display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,flexWrap:'wrap',borderBottom:'1px solid var(--paper-card-edge)'}}>
                <div>
                  <span style={{fontFamily:'var(--font-mono)',fontSize:13,fontWeight:600,color:'var(--ink)'}}>{order.order_number}</span>
                  <span style={{marginLeft:12,fontSize:12,color:'var(--ink-meta)'}}>
                    {new Date(order.created_at).toLocaleDateString('id-ID',{day:'numeric',month:'long',year:'numeric'})}
                  </span>
                </div>
                <span style={{fontSize:12,fontWeight:600,color:st.color,padding:'4px 10px',border:'1px solid '+st.color,borderRadius:999}}>
                  {st.label}
                </span>
              </div>
              <div style={{padding:'16px 20px',display:'flex',justifyContent:'space-between',alignItems:'center',flexWrap:'wrap',gap:12}}>
                <div style={{fontSize:13,color:'var(--ink-soft)'}}>
                  {order.shipping_address?.city && <span>📍 {order.shipping_address.city}</span>}
                </div>
                <div style={{fontFamily:'var(--font-mono)',fontSize:15,fontWeight:600,color:'var(--ink)'}}>
                  Rp {(order.total||0).toLocaleString('id-ID')}
                </div>
              </div>
              {order.xendit_invoice_url && order.status === 'pending_payment' && (
                <div style={{padding:'0 20px 16px'}}>
                  <a href={order.xendit_invoice_url} className="btn btn-primary btn-sm" style={{textDecoration:'none',display:'inline-flex'}}>
                    Lanjut pembayaran →
                  </a>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </main>
  );
}

window.OrdersPage = OrdersPage;
