/* global React, firebase */
function DashboardPage({ user, go, onBuy }) {
  const [orders, setOrders] = React.useState([]);
  const [allOrders, setAllOrders] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [adminOrderQuery, setAdminOrderQuery] = React.useState('');
  const isAdmin = !!window.__effAdminMode;
  const [, adminTick] = React.useReducer((x) => x + 1, 0);

  React.useEffect(() => {
    const h = () => adminTick();
    window.addEventListener('eff_admin_changed', h);
    return () => window.removeEventListener('eff_admin_changed', h);
  }, []);

  // Live-load this user's purchase orders from Firestore
  React.useEffect(() => {
    if (!user?.uid || !window.fb) { setLoading(false); return; }
    const unsub = window.fb.db.collection('orders')
      .where('userId', '==', user.uid)
      .onSnapshot(snap => {
        const items = snap.docs.map(d => ({ id: d.id, ...d.data() }))
          .sort((a, b) => (b.createdAt?.seconds || 0) - (a.createdAt?.seconds || 0));
        setOrders(items);
        setLoading(false);
      }, err => { console.warn('Orders load error:', err); setLoading(false); });
    return () => unsub();
  }, [user?.uid]);

  // Admin: subscribe to ALL orders (used in admin section only)
  React.useEffect(() => {
    if (!isAdmin || !window.fb) return;
    const unsub = window.fb.db.collection('orders')
      .onSnapshot(snap => {
        const items = snap.docs.map(d => ({ id: d.id, ...d.data() }))
          .sort((a, b) => (b.createdAt?.seconds || 0) - (a.createdAt?.seconds || 0));
        setAllOrders(items);
      }, err => console.warn('Admin orders load error:', err));
    return () => unsub();
  }, [isAdmin, user?.uid]);

  // Owned EAs = unique EAs from COMPLETED orders (admin marked them active)
  const ownedEAs = React.useMemo(() => {
    const ownedIds = new Set(orders.filter(o => o.status === 'active').map(o => o.eaId));
    const list = window.EAReports?.effectiveList?.() || window.EA_LIST || [];
    return list.filter(ea => ownedIds.has(ea.id));
  }, [orders]);

  // Admin: change an order's status. Marking "active" (complete) emails the customer.
  const [statusBusy, setStatusBusy] = React.useState(null);
  async function setOrderStatus(o, status) {
    if (!window.fb || !o?.id) return;
    setStatusBusy(o.id);
    try {
      const updates = { status, updatedAt: firebase.firestore.FieldValue.serverTimestamp() };
      if (status === 'active') updates.deliveredAt = firebase.firestore.FieldValue.serverTimestamp();
      await window.fb.db.collection('orders').doc(o.id).set(updates, { merge: true });
      if (status === 'active' && window.Mailer && o.userEmail) {
        window.Mailer.sendOrderComplete({
          email: o.userEmail, name: o.userName,
          eaName: o.eaName, price: o.amount, method: o.method,
          orderId: o.id, licenseTerm: o.licenseTerm || null,
        }).catch(() => {});
      }
    } catch (e) {
      alert('Could not update status: ' + (e.message || e));
    } finally {
      setStatusBusy(null);
    }
  }

  // Map eaId -> its latest order (used to attach files / license to UI cards)
  const orderByEaId = React.useMemo(() => {
    const m = {};
    orders.forEach(o => {
      if (!m[o.eaId] || (o.createdAt?.seconds || 0) > (m[o.eaId].createdAt?.seconds || 0)) {
        m[o.eaId] = o;
      }
    });
    return m;
  }, [orders]);

  const totalInvested = orders
    .filter(o => o.status === 'active')
    .reduce((s, o) => s + (o.amount || 0), 0);

  const totalEAs = (window.EAReports?.effectiveList?.() || window.EA_LIST || []).length;

  return (
    <div>
      <section style={{ padding: '32px 0 16px' }}>
        <div className="container">
          <div className="flex-between mb-6">
            <div>
              <span className="eyebrow">YOUR LIBRARY · {ownedEAs.length} EAs LICENSED</span>
              <h1 className="mt-2" style={{ fontSize: 40 }}>Welcome back, <span className="text-cyan">{user?.name || 'OPERATOR'}</span></h1>
              <p className="text-muted text-sm mt-2">Download your EAs, manage license keys, and ask the AI agent anything.</p>
            </div>
            <div className="flex gap-3">
              <button className="btn btn-ghost" onClick={() => go('agent')}>Ask AI Agent →</button>
              <button className="btn btn-primary btn-sheen" onClick={() => go('marketplace')}>+ Buy EA</button>
            </div>
          </div>

          {/* Quick stats — based on actual orders */}
          <div className="grid grid-2">
            <div className="panel panel-padded lift">
              <span className="stat-label">DOWNLOADS AVAILABLE</span>
              <div className="stat-value mt-2" style={{ color: 'var(--magenta)' }}>{ownedEAs.length * 2}</div>
              <div className="stat-delta text-muted mt-2 font-mono">.ex5 + .set</div>
            </div>
            <div className="panel panel-padded lift">
              <span className="stat-label">PLAN</span>
              <div className="stat-value mt-2" style={{ color: 'var(--amber)' }}>OPERATOR</div>
              <div className="stat-delta text-muted mt-2 font-mono">$29/mo</div>
            </div>
          </div>
        </div>
      </section>

      {/* Your library */}
      <section style={{ padding: '24px 0' }}>
        <div className="container">
          <div className="panel panel-padded">
            <div className="flex-between mb-6">
              <div>
                <span className="eyebrow">YOUR LICENSED EAs</span>
                <h3 className="mt-2" style={{ fontSize: 20 }}>Downloads, license keys & .set files</h3>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => go('marketplace')}>Browse marketplace →</button>
            </div>

            {ownedEAs.length === 0 ? (
              <div className="panel" style={{ padding: 48, textAlign: 'center', border: '1px dashed var(--line-strong)', background: 'transparent' }}>
                <div style={{ fontSize: 48, color: 'var(--cyan)', lineHeight: 1, opacity: 0.5 }}>◌</div>
                <h4 className="mt-4" style={{ fontSize: 18 }}>No EAs licensed yet</h4>
                <p className="text-muted text-sm mt-2" style={{ maxWidth: 400, margin: '8px auto 0' }}>
                  Browse the marketplace to find a system that matches your trading style. Every EA includes a lifetime license and full backtest.
                </p>
                <button className="btn btn-primary btn-sheen mt-6" onClick={() => go('marketplace')}>Browse Marketplace →</button>
              </div>
            ) : (
              <div className="grid grid-3">
                {ownedEAs.map((e, i) =>
                  <div key={e.id} className="panel lift" style={{ padding: 0, overflow: 'hidden' }}>
                    <div style={{ position: 'relative', height: 120, background: 'rgba(0,0,0,0.4)', borderBottom: '1px solid var(--line)' }}>
                      <EAImageSlot eaId={e.id} name={e.name} />
                      <div style={{ position: 'absolute', top: 10, left: 10, right: 10, display: 'flex', justifyContent: 'space-between', pointerEvents: 'none' }}>
                        <span className="tag" style={{ fontSize: 9, backdropFilter: 'blur(8px)', background: 'rgba(5,6,13,0.6)' }}>{e.strategy}</span>
                        <span className="tag tag-green" style={{ fontSize: 9, backdropFilter: 'blur(8px)' }}>ACTIVE</span>
                      </div>
                    </div>
                    <div style={{ padding: 18 }}>
                      <div style={{ fontWeight: 600, fontSize: 16 }}>{e.name}</div>
                      <div className="text-xs text-muted mt-1">{e.pairs.join(' · ')}</div>
                      <div style={{ height: 50, marginTop: 10 }}>
                        <EquityCurve data={e.curve.slice(-12)} height={50} animated={false} color={i === 0 ? '#00E5FF' : i === 1 ? '#FF2DAA' : '#00FF94'} />
                      </div>
                      <div className="font-mono text-xs text-muted mt-1" style={{ fontSize: 9, letterSpacing: '0.1em' }}>12M BACKTEST · +{((e.curve[e.curve.length - 1] / e.curve[0] - 1) * 100).toFixed(1)}%</div>

                      <div className="panel mt-3" style={{ padding: 10, background: 'rgba(0,0,0,0.4)' }}>
                        <div className="text-xs text-muted">License Key</div>
                        <div className="font-mono text-cyan mt-1" style={{ fontSize: 11 }}>
                          {orderByEaId[e.id]?.licenseKey || `EFF-${e.id.toUpperCase()}-XXXX`}
                        </div>
                        {orderByEaId[e.id]?.mt5Account && (
                          <div className="mt-2">
                            <div className="text-xs text-muted">MT5 Account</div>
                            <div className="font-mono mt-1" style={{ fontSize: 11, color: 'var(--magenta)' }}>{orderByEaId[e.id].mt5Account}</div>
                          </div>
                        )}
                      </div>

                      {/* Real downloadable expert files for this order */}
                      <div className="mt-3">
                        <div className="font-mono text-xs text-muted mb-2" style={{ letterSpacing: '0.1em' }}>EXPERT FILES</div>
                        {orderByEaId[e.id] ? (
                          <OrderFiles order={orderByEaId[e.id]} isAdmin={false} />
                        ) : (
                          <div className="text-xs text-muted font-mono">// No order linked</div>
                        )}
                      </div>

                      <div className="flex gap-2 mt-3">
                        <button className="btn btn-ghost" style={{ flex: 1, fontSize: 10, padding: '8px 10px' }} onClick={() => go('detail', e.id)}>Details</button>
                      </div>
                    </div>
                  </div>
                )}
                <div className="panel" style={{ padding: 20, border: '1px dashed var(--line-strong)', background: 'transparent', display: 'grid', placeItems: 'center', cursor: 'pointer', minHeight: 380 }} onClick={() => go('marketplace')}>
                  <div className="text-center">
                    <div style={{ fontSize: 40, color: 'var(--cyan)' }}>+</div>
                    <div className="text-xs text-muted mt-2 font-mono uppercase">BUY NEW EA</div>
                    <div className="text-xs text-muted mt-1">{Math.max(0, totalEAs - ownedEAs.length)} more available</div>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Setup guide + AI Agent shortcut */}
          <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 20, marginTop: 20 }}>
            <div className="panel panel-padded">
              <span className="eyebrow">SETUP GUIDE</span>
              <h3 className="mt-2" style={{ fontSize: 18 }}>How to deploy your EA on MT5</h3>
              <div className="mt-4 flex-col gap-3">
                {[
                  { n: '01', t: 'Download the .ex5 and .set file', d: 'From your library above.' },
                  { n: '02', t: 'Copy .ex5 to MT5/MQL5/Experts folder', d: 'File → Open Data Folder in MT5.' },
                  { n: '03', t: 'Restart MT5 and drag the EA onto a chart', d: 'Match the pair & timeframe in the spec sheet.' },
                  { n: '04', t: 'Load the .set file in EA inputs', d: 'Common tab → Load.' },
                  { n: '05', t: 'Enable AutoTrading and let it run', d: 'A VPS is strongly recommended for 24/7.' }
                ].map(s =>
                  <div key={s.n} className="flex gap-3" style={{ alignItems: 'flex-start' }}>
                    <div className="font-mono text-cyan" style={{ fontSize: 11, minWidth: 24 }}>{s.n}</div>
                    <div style={{ flex: 1 }}>
                      <div className="text-sm" style={{ fontWeight: 600 }}>{s.t}</div>
                      <div className="text-xs text-muted mt-1">{s.d}</div>
                    </div>
                  </div>
                )}
              </div>
              <div className="divider" />
              <button className="btn btn-ghost btn-sm btn-block">Watch 12-min walkthrough →</button>
            </div>

            <div className="panel panel-padded" style={{ background: 'rgba(255,45,170,0.04)', borderColor: 'rgba(255,45,170,0.25)' }}>
              <span className="eyebrow" style={{ color: 'var(--magenta)' }}>AI AGENT</span>
              <h3 className="mt-2" style={{ fontSize: 18 }}>Need help choosing or setting up?</h3>
              <p className="text-sm text-muted mt-3">Ask anything about lot sizing, parameters, broker choice, or which EA fits your account next.</p>
              <div className="mt-4 flex-col gap-2">
                <button className="btn btn-ghost btn-sm btn-block" style={{ justifyContent: 'flex-start', textTransform: 'none', letterSpacing: 'normal' }} onClick={() => go('agent')}>"What lot size for $10k @ 1% risk?"</button>
                <button className="btn btn-ghost btn-sm btn-block" style={{ justifyContent: 'flex-start', textTransform: 'none', letterSpacing: 'normal' }} onClick={() => go('agent')}>"Best broker for APEX on EURUSD?"</button>
                <button className="btn btn-ghost btn-sm btn-block" style={{ justifyContent: 'flex-start', textTransform: 'none', letterSpacing: 'normal' }} onClick={() => go('agent')}>"Should I add CIPHER to my portfolio?"</button>
                <button className="btn btn-ghost btn-sm btn-block" style={{ justifyContent: 'flex-start', textTransform: 'none', letterSpacing: 'normal' }} onClick={() => go('agent')}>"Explain MagicNumber and why it matters"</button>
              </div>
              <button className="btn btn-magenta btn-block btn-sheen mt-4" onClick={() => go('agent')}>Open AI Agent →</button>
            </div>
          </div>

          {/* ADMIN ONLY — All customer orders with file upload */}
          {isAdmin && (
            <div className="panel panel-padded mt-5" style={{ background: 'rgba(255,45,170,0.04)', borderColor: 'rgba(255,45,170,0.3)' }}>
              <div className="flex-between mb-4" style={{ flexWrap: 'wrap', gap: 12 }}>
                <div>
                  <span className="eyebrow" style={{ color: 'var(--magenta)' }}>ADMIN · ALL CUSTOMER ORDERS</span>
                  <h3 className="mt-2" style={{ fontSize: 20 }}>Upload Expert files per customer</h3>
                  <p className="text-xs text-muted mt-1">Each customer sees only the files attached to their own order. Uploading at least one file marks the order ACTIVE.</p>
                </div>
                <input
                  className="input"
                  placeholder="Search by email / MT5 / order id / EA..."
                  value={adminOrderQuery}
                  onChange={(e) => setAdminOrderQuery(e.target.value)}
                  style={{ maxWidth: 360, fontSize: 13 }}
                />
              </div>

              {allOrders.length === 0 ? (
                <div className="text-muted font-mono text-sm" style={{ padding: '24px 0', textAlign: 'center' }}>// NO ORDERS YET</div>
              ) : (
                <div className="flex-col gap-3">
                  {allOrders.filter(o => {
                    const q = adminOrderQuery.trim().toLowerCase();
                    if (!q) return true;
                    return (
                      (o.userEmail || '').toLowerCase().includes(q) ||
                      (o.userName || '').toLowerCase().includes(q) ||
                      (o.mt5Account || '').toLowerCase().includes(q) ||
                      (o.id || '').toLowerCase().includes(q) ||
                      (o.eaName || '').toLowerCase().includes(q)
                    );
                  }).map(o => (
                    <div key={o.id} className="panel" style={{ padding: 16, background: 'rgba(0,0,0,0.35)' }}>
                      <div className="admin-order-grid">
                        <div>
                          <div className="flex gap-2" style={{ alignItems: 'center', flexWrap: 'wrap' }}>
                            <span className={`tag ${o.status === 'active' ? 'tag-green' : o.status === 'pending' ? 'tag-amber' : 'tag-red'}`} style={{ fontSize: 9 }}>{(o.status || 'pending').toUpperCase()}</span>
                            <span className="font-mono text-xs text-muted">{o.id}</span>
                          </div>
                          <div style={{ fontWeight: 600, fontSize: 15, marginTop: 8 }}>{o.eaName}</div>
                          <div className="text-xs text-muted mt-1">
                            <span className="text-cyan font-mono">{o.userEmail || '—'}</span>
                            {o.userName && <span> · {o.userName}</span>}
                          </div>
                          <div className="mt-2 flex gap-3" style={{ flexWrap: 'wrap' }}>
                            <div>
                              <div className="stat-label" style={{ fontSize: 9 }}>MT5</div>
                              <div className="font-mono" style={{ fontSize: 13, color: 'var(--magenta)' }}>{o.mt5Account || '—'}</div>
                            </div>
                            <div>
                              <div className="stat-label" style={{ fontSize: 9 }}>BROKER</div>
                              <div className="font-mono" style={{ fontSize: 13 }}>{o.mt5Broker || '—'}</div>
                            </div>
                            <div>
                              <div className="stat-label" style={{ fontSize: 9 }}>AMOUNT</div>
                              <div className="font-mono text-cyan" style={{ fontSize: 13 }}>${o.amount}</div>
                            </div>
                            <div>
                              <div className="stat-label" style={{ fontSize: 9 }}>METHOD</div>
                              <div className="font-mono" style={{ fontSize: 13 }}>{o.method || '—'}</div>
                            </div>
                            <div>
                              <div className="stat-label" style={{ fontSize: 9 }}>DATE</div>
                              <div className="font-mono text-muted" style={{ fontSize: 12 }}>{o.createdAt?.toDate ? o.createdAt.toDate().toLocaleString() : '—'}</div>
                            </div>
                          </div>
                          <div className="mt-3 panel" style={{ padding: 8, background: 'rgba(0,0,0,0.5)' }}>
                            <div className="text-xs text-muted">License Key</div>
                            <div className="font-mono text-cyan mt-1" style={{ fontSize: 11, wordBreak: 'break-all' }}>{o.licenseKey}</div>
                          </div>

                          <div className="mt-3">
                            <div className="font-mono text-xs text-muted mb-2" style={{ letterSpacing: '0.1em' }}>ORDER STATUS · <span style={{ color: o.status === 'active' ? 'var(--green)' : o.status === 'cancelled' ? 'var(--red)' : 'var(--amber)' }}>{(o.status || 'pending').toUpperCase()}</span></div>
                            <div className="flex gap-2" style={{ flexWrap: 'wrap' }}>
                              {o.status !== 'active' && (
                                <button className="btn btn-sm" style={{ background: 'var(--green)', color: '#000', borderColor: 'var(--green)' }} disabled={statusBusy === o.id} onClick={() => setOrderStatus(o, 'active')}>
                                  {statusBusy === o.id ? '…' : '✓ Mark Complete'}
                                </button>
                              )}
                              {o.status !== 'pending' && (
                                <button className="btn btn-ghost btn-sm" disabled={statusBusy === o.id} onClick={() => setOrderStatus(o, 'pending')}>↩ Set Pending</button>
                              )}
                              {o.status !== 'cancelled' && (
                                <button className="btn btn-ghost btn-sm" style={{ color: 'var(--red)', borderColor: 'rgba(255,59,92,0.4)' }} disabled={statusBusy === o.id} onClick={() => { if (confirm('Cancel this order?')) setOrderStatus(o, 'cancelled'); }}>✕ Cancel</button>
                              )}
                            </div>
                            <div className="text-xs text-muted mt-2" style={{ fontSize: 11 }}>Uploading the EA file auto-completes the order and emails the customer. These buttons let you override the status manually.</div>
                          </div>
                        </div>
                        <div>
                          <div className="font-mono text-xs text-muted mb-2" style={{ letterSpacing: '0.1em' }}>EXPERT FILES · {o.expertFiles?.length || 0}</div>
                          <OrderFiles order={o} isAdmin={true} />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Order history */}
          <div className="panel panel-padded mt-5">
            <div className="flex-between mb-4">
              <div>
                <span className="eyebrow">ORDER HISTORY</span>
                <h3 className="mt-2" style={{ fontSize: 18 }}>Your purchases</h3>
              </div>
              {orders.length > 0 && <button className="btn btn-ghost btn-sm" onClick={() => window.Invoice?.open(orders[0])}>Download latest invoice →</button>}
            </div>
            {orders.length === 0 ? (
              <div style={{ padding: '32px 0', textAlign: 'center' }}>
                <div className="text-muted font-mono text-sm">// NO PURCHASES YET</div>
                <p className="text-muted text-sm mt-3">Your purchase receipts will appear here.</p>
              </div>
            ) : (
              <div className="orders-table-wrap" style={{ width: '100%', overflowX: 'auto', WebkitOverflowScrolling: 'touch' }}>
                <table style={{ minWidth: 760, width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
                  <thead>
                    <tr style={{ borderBottom: '1px solid var(--line)' }}>
                      {['EA', 'MT5 Account', 'Date', 'Method', 'Amount', 'Plan', 'Status', 'Invoice'].map(h =>
                        <th key={h} className="font-mono" style={{ textAlign: 'left', padding: '12px 8px', color: 'var(--text-3)', fontSize: 10, letterSpacing: '0.15em', whiteSpace: 'nowrap' }}>{h.toUpperCase()}</th>
                      )}
                    </tr>
                  </thead>
                  <tbody>
                    {orders.map(o =>
                      <tr key={o.id} style={{ borderBottom: '1px solid var(--line-soft)' }}>
                        <td style={{ padding: '14px 8px', fontWeight: 600, whiteSpace: 'nowrap' }}>{o.eaName || o.eaId}</td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }} className="font-mono text-cyan text-xs">{o.mt5Account || '—'}</td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }} className="font-mono text-muted">
                          {o.createdAt?.toDate ? o.createdAt.toDate().toLocaleDateString() : '—'}
                        </td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }} className="font-mono">{o.method || '—'}</td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }} className="font-mono text-cyan">${o.amount}</td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }} className="font-mono text-xs">{o.licenseTerm || '—'}</td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }}>
                          <span className={`tag ${o.status === 'active' ? 'tag-green' : o.status === 'pending' ? 'tag-amber' : 'tag-red'}`} style={{ fontSize: 9 }}>
                            {(o.status || 'pending').toUpperCase()}
                          </span>
                        </td>
                        <td style={{ padding: '14px 8px', whiteSpace: 'nowrap' }}>
                          <button className="btn btn-ghost btn-sm" style={{ fontSize: 10, padding: '6px 12px' }} onClick={() => window.Invoice?.open(o)}>⬇ Invoice</button>
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      </section>
    </div>);

}

window.DashboardPage = DashboardPage;
