// Astrail — Treasury Dashboard Screen

const DashboardScreen = ({ onNavigate, addToast }) => {
  const { MOCK } = window;
  const [refreshing, setRefreshing] = React.useState(false);
  const [chartPeriod, setChartPeriod] = React.useState('6m');
  const [tooltip, setTooltip] = React.useState(null); // { id, text }

  // H2: filter chart data by selected period
  const chartData = React.useMemo(() => {
    const flows = MOCK.monthlyFlows;
    if (chartPeriod === '3m') return flows.slice(-3);
    if (chartPeriod === '1y') return flows.slice(-12);
    return flows.slice(-6);
  }, [chartPeriod]);

  // H8: skeleton component for loading state
  const Skel = ({ w = '60%', h = 14, r = 6 }) => (
    <div style={{ width: w, height: h, borderRadius: r,
      background: 'var(--col-border-s)', opacity: 0.7,
      animation: 'skelPulse 1.4s ease-in-out infinite' }} />
  );

  const STAT_INFO = {
    treasury:  'Total value across all connected wallets on all chains.',
    payroll:   'Upcoming payroll run — value and recipient count.',
    approvals: 'Payroll runs waiting for the required number of signatures.',
    wallets:   'Wallets currently connected to this workspace.',
  };

  const InfoIcon = ({ id }) => (
    <span style={{ position:'relative', display:'inline-flex', alignItems:'center', marginLeft:5, cursor:'default' }}
      onMouseEnter={() => setTooltip(id)}
      onMouseLeave={() => setTooltip(null)}>
      <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--col-text-3)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/>
      </svg>
      {tooltip === id &&
        <div style={{ position:'absolute', bottom:'calc(100% + 6px)', left:'50%', transform:'translateX(-50%)',
          background:'var(--col-text)', color:'var(--col-surface)', fontSize:11, fontWeight:500,
          padding:'6px 10px', borderRadius:7, whiteSpace:'nowrap', zIndex:99,
          boxShadow:'var(--shadow-md)', pointerEvents:'none', lineHeight:1.4, maxWidth:220, whiteSpace:'normal', textAlign:'center' }}>
          {STAT_INFO[id]}
        </div>
      }
    </span>
  );

  const handleRefresh = () => {
    setRefreshing(true);
    setTimeout(() => {
      setRefreshing(false);
      addToast('Balances refreshed');
    }, 1200);
  };

  return (
    <>
      {/* Page Header */}
      <div className="content-header">
        <div className="content-header-left">
          <span className="page-title">Dashboard</span>
        </div>
        <div className="content-header-right">
          <button className="btn btn-secondary btn-sm" onClick={handleRefresh}
          style={{ gap: 5 }} disabled={refreshing}>
            {refreshing ?
            <><LoaderArc size="sm" /> Refreshing…</> :
            <><IcoRefresh size={14} color="var(--col-text-2)" /> Refresh</>
            }
          </button>
          <button className="btn btn-primary btn-sm"
          onClick={() => onNavigate('payroll-new')} style={{ gap: 5 }}>
            <IcoPlus size={13} color="white" />
            Run Payroll
          </button>
        </div>
      </div>

      {/* Page Body */}
      <div className="content-body">

        {/* ── H4: Failed payroll alert ─────────────── */}
        {(MOCK.payrollRuns || []).filter(r => r.status === 'failed' && !r.resolved).map(run => (
          <div key={run.id} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '12px 16px', marginBottom: 8,
            background: 'var(--col-error-bg)',
            border: '1px solid rgba(220,38,38,.25)', borderRadius: 12
          }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
              stroke="var(--col-error)" strokeWidth="2.2"
              strokeLinecap="round" strokeLinejoin="round">
              <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
              <line x1="12" y1="9" x2="12" y2="13"/>
              <line x1="12" y1="17" x2="12.01" y2="17"/>
            </svg>
            <div style={{ flex: 1, fontSize: 14, color: 'var(--col-error)', fontWeight: 500, lineHeight: 1.4 }}>
              Payroll run failed: <strong>{run.name}</strong>
              {' · '}{fmtUSD(run.total)}{' · '}{run.recipients} recipients not paid
            </div>
            <button className="btn btn-sm" style={{ background: 'var(--col-error)', color: '#fff', border: 'none', gap: 5, flexShrink: 0 }}
              onClick={() => onNavigate('payroll')}>
              Review <IcoChevronRight size={11} color="#fff" />
            </button>
          </div>
        ))}

        {/* ── Stat Cards ─────────────────────────────── */}
        <div className="stat-cards">
          <div className="stat-card">
            <div className="stat-label">Total Treasury <InfoIcon id="treasury" /></div>
            <div className="stat-value">{refreshing ? <Skel w="70%" h={28} r={7} /> : fmtUSD(MOCK.treasury.total)}</div>
            <div className="stat-meta">
              <span className="stat-change pos">+{MOCK.treasury.changePercent}%</span>
              <span className="stat-sub">vs last month</span>
            </div>
            <div className="stat-meta" style={{ marginTop: 4 }}>
              <span className="stat-sub">{MOCK.wallets.length} wallet{MOCK.wallets.length !== 1 ? 's' : ''} · {new Set(MOCK.wallets.map(w => w.chain)).size} networks</span>
            </div>
          </div>

          <div className="stat-card">
            <div className="stat-label">Upcoming Payroll <InfoIcon id="payroll" /></div>
            <div className="stat-value">{refreshing ? <Skel w="65%" h={28} r={7} /> : fmtUSD(MOCK.upcomingPayroll.total)}</div>
            <div className="stat-meta">
              <StatusBadge status="scheduled" />
              <span className="stat-sub">{MOCK.upcomingPayroll.recipients} recipients</span>
            </div>
            <div className="stat-meta" style={{ marginTop: 4 }}>
              <ChainBadge chain={MOCK.upcomingPayroll.chain} size="xs" />
              <span className="stat-sub">USDT</span>
            </div>
          </div>

          <div className="stat-card" style={{ cursor: 'pointer' }}
          onClick={() => onNavigate('approvals')}>
            <div className="stat-label">Pending Approvals <InfoIcon id="approvals" /></div>
            <div className="stat-value">{refreshing ? <Skel w="30%" h={28} r={7} /> : MOCK.pendingApprovals.length}</div>
            <div className="stat-meta">
              <span className="stat-sub">runs awaiting sign-off</span>
            </div>
            <div className="stat-meta" style={{ marginTop: 4 }}>
              <button className="btn btn-link" style={{ fontSize: 12 }}>
                View all <IcoChevronRight size={10} />
              </button>
            </div>
          </div>

          <div className="stat-card">
            <div className="stat-label">Connected Wallets <InfoIcon id="wallets" /></div>
            <div className="stat-value">{refreshing ? <Skel w="30%" h={28} r={7} /> : MOCK.wallets.length}</div>
            <div className="stat-meta">
              <span className="stat-sub">
                {MOCK.wallets.filter((w) => w.type === 'multisig').length} multisig ·{' '}
                {MOCK.wallets.filter((w) => w.type === 'eoa').length} EOA
              </span>
            </div>
            <div className="stat-meta" style={{ marginTop: 4 }}>
              <button className="btn btn-link" style={{ fontSize: 12 }}
              onClick={() => onNavigate('settings')}>
                Manage <IcoChevronRight size={10} />
              </button>
            </div>
          </div>
        </div>

        {/* ── Middle Row ─────────────────────────────── */}
        <div className="grid-main-aside">

          {/* Monthly Flows Chart */}
          <div className="card card-pad">
            <div className="flex-row" style={{ marginBottom: 0 }}>
              <div style={{ flex: 1 }}>
                <div className="card-title" style={{ marginBottom: 0 }}>Monthly Flows</div>
                <div style={{ fontSize: 12, color: 'var(--col-text-3)', marginTop: 2 }}>USDT · last {chartPeriod === '3m' ? '3' : chartPeriod === '1y' ? '12' : '6'} months</div>
              </div>
              <div className="flex-row gap-8" style={{ alignItems:'center' }}>
                <div className="tabs" style={{ gap:2 }}>
                  {['3m','6m','1y'].map(p => (
                    <div key={p} className={`tab ${chartPeriod===p?'active':''}`}
                      style={{ padding:'3px 8px', fontSize:11, textTransform:'uppercase' }}
                      onClick={() => setChartPeriod(p)}>{p}</div>
                  ))}
                </div>
                <span className="mono fw-5" style={{ fontSize: 13, color: 'var(--col-text-2)' }}>
                  Net {fmtUSD((MOCK.monthlyFlows.at(-1).in - MOCK.monthlyFlows.at(-1).out) * 1000)}
                </span>
                <span className="stat-change pos" style={{ fontSize: 12 }}>this month</span>
              </div>
            </div>
            <div style={{ marginTop: 20 }}>
              <FlowChart data={chartData} height={148} />
            </div>
          </div>

          {/* Pending Approvals */}
          <div className="card card-pad" style={{ display: 'flex', flexDirection: 'column' }}>
            <div className="flex-row" style={{ marginBottom: 14 }}>
              <div className="card-title" style={{ marginBottom: 0, flex: 1 }}>Pending Approvals</div>
              <button className="btn btn-link" style={{ fontSize: 12 }}
              onClick={() => onNavigate('approvals')}>
                All <IcoChevronRight size={10} />
              </button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1 }}>
              {MOCK.pendingApprovals.map((run) =>
              <div key={run.id}
              onClick={() => onNavigate('approvals', run)}
              style={{
                padding: '10px 12px', borderRadius: 10, cursor: 'pointer',
                border: '1px solid var(--col-border-s)',
                transition: 'background 120ms ease, border-color 120ms ease'
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = 'var(--col-accent-hover)';
                e.currentTarget.style.borderColor = 'var(--col-accent-100)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = '';
                e.currentTarget.style.borderColor = 'var(--col-border-s)';
              }}>
                  <div className="flex-row gap-8" style={{ marginBottom: 6 }}>
                    <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)', flex: 1 }}>
                      {run.name}
                    </span>
                    <ChainBadge chain={run.chain} size="xs" />
                  </div>
                  <div className="flex-row gap-8">
                    <ApprovalDots signed={run.signed} required={run.required} />
                    <span className="ml-auto mono" style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)' }}>
                      {fmtUSD(run.total)}
                    </span>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* ── Wallet Breakdown + Recent Transactions ──── */}
        <div className="grid-aside-main">

          {/* Wallet breakdown */}
          <div className="card card-pad">
            <div className="card-title">Wallet Breakdown</div>
            <BalanceBar wallets={MOCK.wallets} total={MOCK.treasury.total} />
            <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--col-border-s)' }}>
              {MOCK.wallets.map((w) =>
              <div key={w.name} className="flex-row gap-8" style={{ marginBottom: 8 }}>
                  <Avatar name={w.name} size="sm" />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--col-text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {w.name}
                    </div>
                    <div className="flex-row gap-4" style={{ marginTop: 1 }}>
                      <span className={`wallet-type ${w.type === 'multisig' ? 'wallet-multisig' : 'wallet-eoa'}`}>
                        {w.type === 'multisig' ? 'Multisig' : 'EOA'}
                      </span>
                    </div>
                  </div>
                  <span className="mono fw-5" style={{ fontSize: 12 }}>{fmtUSD(w.balance)}</span>
                </div>
              )}
            </div>
          </div>

          {/* Recent Transactions */}
          <div className="card" style={{ overflow: 'clip', minWidth: 0 }}>
            <div className="flex-row" style={{ padding: '16px 20px 12px', borderBottom: '1px solid var(--col-border-s)' }}>
              <span className="card-title" style={{ marginBottom: 0, flex: 1 }}>Recent Transactions</span>
              <button className="btn btn-link" style={{ fontSize: 12 }} onClick={() => onNavigate('treasury')}>
                View all <IcoChevronRight size={10} />
              </button>
            </div>

            {/* ── Desktop table ─────────────────────── */}
            <div className="desktop-only-table" style={{ overflowX: 'auto' }}>
              <table className="data-table" style={{ tableLayout: 'fixed', minWidth: 600 }}>
                <thead>
                  <tr>
                    <th style={{ width: '22%' }}>From / To</th>
                    <th style={{ width: '14%' }}>Asset</th>
                    <th style={{ width: '14%' }} className="right">Amount</th>
                    <th style={{ width: '12%' }}>Chain</th>
                    <th style={{ width: '20%' }}>Reference</th>
                    <th style={{ width: '10%' }}>Time</th>
                    <th style={{ width: '8%' }} className="center">Status</th>
                  </tr>
                </thead>
                <tbody>
                  {/* H8: skeleton rows when refreshing */}
                  {refreshing ? Array(5).fill(0).map((_, i) => (
                    <tr key={i}>
                      <td><Skel w="80%" /></td><td><Skel w="50%" /></td>
                      <td className="right"><Skel w="70%" /></td>
                      <td><Skel w="60%" /></td><td><Skel w="90%" /></td>
                      <td><Skel w="55%" /></td><td className="center"><Skel w="70%" /></td>
                    </tr>
                  )) : MOCK.recentTxns.map((tx) =>
                  <tr key={tx.id}>
                      <td>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)' }}>{tx.to}</div>
                        <div className="cell-address">{truncAddr(tx.toAddr)}</div>
                      </td>
                      <td className="cell-secondary" style={{ fontSize: 13 }}>{tx.asset}</td>
                      <td className="right cell-mono" style={{ fontSize: 13, fontWeight: 500 }}>
                        {fmtFull(tx.amount)}
                      </td>
                      <td><ChainBadge chain={tx.chain} size="xs" /></td>
                      <td className="cell-secondary" style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 130 }}>
                        {tx.ref}
                      </td>
                      <td className="cell-secondary" style={{ fontSize: 12 }}>{tx.time}</td>
                      <td className="center"><StatusBadge status={tx.status} /></td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>

            {/* ── Mobile card list ──────────────────── */}
            <div className="mobile-only-list" style={{ display: 'none' }}>
              {MOCK.recentTxns.map((tx) => (
                <div key={tx.id} className="mobile-card-list-item">
                  {/* Chain + direction indicator */}
                  <div style={{
                    width: 40, height: 40, borderRadius: 11, flexShrink: 0,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: tx.status === 'failed'
                      ? 'var(--col-error-bg)'
                      : tx.status === 'processing'
                        ? 'var(--col-processing-bg)'
                        : 'var(--col-surface-2)'
                  }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
                      stroke={tx.status === 'failed' ? 'var(--col-error)' : tx.status === 'processing' ? 'var(--col-processing)' : 'var(--col-text-3)'}
                      strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                      <path d="M12 5v14M5 12l7 7 7-7" />
                    </svg>
                  </div>
                  {/* Name + address + ref */}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
                      <span style={{ fontSize: 14, fontWeight: 500, color: 'var(--col-text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>{tx.to}</span>
                      <ChainBadge chain={tx.chain} size="xs" />
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--col-text-3)', display: 'flex', alignItems: 'center', gap: 6 }}>
                      <span style={{ fontFamily: "'SF Mono','Fira Code',monospace", fontSize: 11 }}>{truncAddr(tx.toAddr)}</span>
                      {tx.status !== 'confirmed' && <StatusBadge status={tx.status} />}
                    </div>
                  </div>
                  {/* Amount + time */}
                  <div style={{ textAlign: 'right', flexShrink: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--col-text)', fontVariantNumeric: 'tabular-nums' }}>
                      {fmtFull(tx.amount)}
                    </div>
                    <div style={{ fontSize: 11, color: 'var(--col-text-3)', marginTop: 2 }}>{tx.time}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

      </div>

      <style>{`
        @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
        @keyframes skelPulse { 0%,100% { opacity:.7; } 50% { opacity:.35; } }
      `}</style>
    </>);

};

Object.assign(window, { DashboardScreen });