// Astrail — Reusable UI Primitives
// Exported to window for cross-script access

// ── Avatar ──────────────────────────────────────────────────────
const AVATAR_COLORS = [
['#E8F2FC', '#4E8CDA'], ['#DCFCE7', '#16A34A'], ['#FEF3C7', '#C2800A'],
['#F5EEFF', '#9945FF'], ['#FEE2E2', '#DC2626'], ['#E0FDF8', '#00897B']];

const Avatar = ({ name = '?', size = 'md', style }) => {
  const initials = name.split(' ').map((w) => w[0]).join('').toUpperCase().slice(0, 2);
  const idx = name.charCodeAt(0) % AVATAR_COLORS.length;
  const [bg, fg] = AVATAR_COLORS[idx];
  return (
    <div className={`avatar avatar-${size}`}
    style={{ background: bg, color: fg, ...style }}>
      {initials}
    </div>);

};

// ── Chain Badge ──────────────────────────────────────────────────
const CHAIN_META = {
  EVM: { label: 'EVM', cls: 'chain-evm', dotColor: 'var(--col-chain-evm)' },
  Tron: { label: 'Tron', cls: 'chain-tron', dotColor: 'var(--col-chain-tron)' },
  Solana: { label: 'Solana', cls: 'chain-sol', dotColor: 'var(--col-chain-sol)' },
  BTC: { label: 'Bitcoin', cls: 'chain-btc', dotColor: 'var(--col-chain-btc)' },
  TON: { label: 'TON', cls: 'chain-ton', dotColor: 'var(--col-chain-ton)' }
};

const ChainBadge = ({ chain, size = 'sm' }) => {
  const meta = CHAIN_META[chain] || { label: chain, cls: 'chain-evm', dotColor: '#627EEA' };
  return (
    <span className={`chain-badge ${meta.cls}`} style={size === 'xs' ? { fontSize: 11, padding: '1px 6px' } : {}}>
      <span className="chain-badge-dot" style={{ background: meta.dotColor }} />
      {meta.label}
    </span>);

};

// ── Status Badge ─────────────────────────────────────────────────
const STATUS_META = {
  confirmed: { label: 'Confirmed', cls: 'badge-confirmed' },
  pending: { label: 'Pending', cls: 'badge-pending' },
  processing: { label: 'Processing', cls: 'badge-processing' },
  failed: { label: 'Failed', cls: 'badge-failed' },
  draft: { label: 'Draft', cls: 'badge-draft' },
  scheduled: { label: 'Scheduled', cls: 'badge-processing' },
  approved: { label: 'Approved', cls: 'badge-confirmed' }
};

const StatusBadge = ({ status }) => {
  const meta = STATUS_META[status] || { label: status, cls: 'badge-draft' };
  return <span className={`badge badge-dot ${meta.cls}`}>{meta.label}</span>;
};

// ── Bar Chart (Monthly Flows) ─────────────────────────────────────
const FlowChart = ({ data, height = 140 }) => {
  const svgW = 480;
  const svgH = height;
  const padB = 22;
  const padL = 46;           // H3: left padding for Y-axis labels
  const chartH = svgH - padB;
  const chartW = svgW - padL; // H3: usable chart width
  const maxVal = Math.max(...data.flatMap((d) => [d.in, d.out]));
  const maxScale = Math.ceil(maxVal / 100) * 100;
  const n = data.length;
  const groupW = chartW / n;  // H3: based on chartW
  const barW = Math.min(24, groupW * 0.28);
  const gap = 4;
  const [hovered, setHovered] = React.useState(null); // { month, type, x, y, val }

  return (
    <div style={{ position: 'relative' }}>
      {/* Legend */}
      <div className="flex-row gap-12" style={{ marginBottom: 12 }}>
        <div className="flex-row gap-4" style={{ fontSize: 12, color: 'var(--col-text-3)' }}>
          <div style={{ width: 10, height: 10, borderRadius: 2, background: 'var(--col-accent)', marginTop: 1 }} />
          Inflow
        </div>
        <div className="flex-row gap-4" style={{ fontSize: 12, color: 'var(--col-text-3)' }}>
          <div style={{ width: 10, height: 10, borderRadius: 2, background: 'var(--col-border-str)', marginTop: 1 }} />
          Outflow
        </div>
      </div>

      {/* Hover tooltip */}
      {hovered && (
        <div style={{
          position: 'absolute', pointerEvents: 'none', zIndex: 10,
          left: `${hovered.x}%`, top: hovered.y - 8,
          transform: 'translateX(-50%) translateY(-100%)',
          background: 'var(--col-text)', color: 'var(--col-surface)',
          fontSize: 11, fontWeight: 600, padding: '5px 9px', borderRadius: 7,
          whiteSpace: 'nowrap', boxShadow: 'var(--shadow-md)'
        }}>
          {hovered.month} · {hovered.type === 'in' ? 'In' : 'Out'} ${hovered.val}K
        </div>
      )}

      <svg viewBox={`0 0 ${svgW} ${svgH}`} style={{ width: '100%', height: svgH, display: 'block', overflow: 'visible' }}>
        {/* H3: Y-axis gridlines + labels */}
        {[0.25, 0.5, 0.75, 1.0].map(frac => {
          const gy = chartH - frac * chartH;
          return (
            <g key={frac}>
              <line x1={padL} y1={gy} x2={svgW} y2={gy}
                stroke="var(--col-border-s)" strokeWidth="1"
                strokeDasharray={frac < 1 ? '3 3' : undefined} />
              <text x={padL - 5} y={gy + 4} textAnchor="end"
                fontSize="9" fill="var(--col-text-3)" fontFamily="inherit">
                {Math.round(frac * maxScale)}K
              </text>
            </g>
          );
        })}

        {data.map((d, i) => {
          const cx = padL + i * groupW + groupW / 2; // H3: offset by padL
          const inH = d.in / maxScale * chartH;
          const outH = d.out / maxScale * chartH;
          const inX = cx - barW - gap / 2;
          const outX = cx + gap / 2;
          const xPct = (cx / svgW) * 100;

          return (
            <g key={d.month}>
              <rect x={inX} y={chartH - inH} width={barW} height={inH} rx="3"
                className="chart-bar-in"
                style={{ cursor: 'pointer', transition: 'opacity 150ms' }}
                opacity={hovered && !(hovered.month === d.month && hovered.type === 'in') ? 0.5 : 1}
                onMouseEnter={() => setHovered({ month: d.month, type: 'in', x: xPct - 3, y: chartH - inH, val: d.in })}
                onMouseLeave={() => setHovered(null)}>
              </rect>
              <rect x={outX} y={chartH - outH} width={barW} height={outH} rx="3"
                className="chart-bar-out"
                style={{ cursor: 'pointer', transition: 'opacity 150ms' }}
                opacity={hovered && !(hovered.month === d.month && hovered.type === 'out') ? 0.5 : 1}
                onMouseEnter={() => setHovered({ month: d.month, type: 'out', x: xPct + 3, y: chartH - outH, val: d.out })}
                onMouseLeave={() => setHovered(null)}>
              </rect>
              <text x={cx} y={svgH - 4} textAnchor="middle"
                style={{ fontSize: 11, fill: 'var(--col-text-3)', fontFamily: 'Onest, sans-serif', fontWeight: 500 }}>
                {d.month}
              </text>
            </g>);
        })}
      </svg>
    </div>);
};

// ── Wallet Balance Bar ────────────────────────────────────────────
const BalanceBar = ({ wallets, total }) => {
  const CHAIN_BAR_COLORS = {
    EVM: 'var(--col-chain-evm)',
    Tron: 'var(--col-chain-tron)',
    Solana: 'var(--col-chain-sol)',
    BTC: 'var(--col-chain-btc)',
    TON: 'var(--col-chain-ton)'
  };
  return (
    <div>
      {/* Segmented bar */}
      <div style={{ display: 'flex', borderRadius: 6, overflow: 'hidden', height: 8, gap: 2, marginBottom: 12 }}>
        {wallets.map((w) =>
        <div key={w.name} style={{
          flex: w.balance / total,
          background: CHAIN_BAR_COLORS[w.chain] || 'var(--col-accent)',
          borderRadius: 2,
          transition: 'flex 400ms ease'
        }} title={`${w.chain}: $${(w.balance / 1000).toFixed(0)}K`} />
        )}
      </div>
      {/* Legend rows */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {wallets.map((w) =>
        <div key={w.name} className="flex-row" style={{ fontSize: 13 }}>
            <div style={{ width: 8, height: 8, borderRadius: 2, background: CHAIN_BAR_COLORS[w.chain] || 'var(--col-accent)', marginRight: 8, flexShrink: 0, marginTop: 1 }} />
            <span style={{ color: 'var(--col-text-2)', flex: 1 }}>{w.name}</span>
            <span className="text-3 text-xs" style={{ marginRight: 10 }}>{w.chain}</span>
            <span className="mono fw-5" style={{ color: 'var(--col-text)', fontSize: 13 }}>
              ${(w.balance / 1000).toFixed(1)}K
            </span>
          </div>
        )}
      </div>
    </div>);

};

// ── Approval Progress Dots ────────────────────────────────────────
const ApprovalDots = ({ signed, required, signers = [] }) =>
<div className="flex-row gap-8">
    <div className="flex-row gap-4">
      {Array.from({ length: required }).map((_, i) =>
    <div key={i} className={`sig-dot ${i < signed ? 'signed' : 'unsigned'}`}>
          {i < signed ?
      <IcoCheck size={10} /> :
      <span style={{ fontSize: 9, fontWeight: 600 }}>{i + 1}</span>}
        </div>
    )}
    </div>
    <span style={{ fontSize: 13, color: 'var(--col-text-2)' }}>
      {signed} of {required} signed
    </span>
  </div>;


// ── Number formatter ─────────────────────────────────────────────
const fmt = (n, decimals = 0) =>
new Intl.NumberFormat('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals }).format(n);

const fmtUSD = (n) => {
  if (n >= 1_000_000) return `$${(n / 1_000_000).toFixed(2)}M`;
  if (n >= 1_000) return `$${(n / 1_000).toFixed(1)}K`;
  return `$${fmt(n, 2)}`;
};

const fmtFull = (n) => `$${fmt(n, 2)}`;

// ── Address truncator ─────────────────────────────────────────────
const truncAddr = (addr, front = 6, back = 4) =>
addr ? `${addr.slice(0, front)}…${addr.slice(-back)}` : '—';

// ── Toast hook ───────────────────────────────────────────────────
const useToasts = () => {
  const [toasts, setToasts] = React.useState([]);
  const addToast = React.useCallback((msg, type = 'success') => {
    const id = Date.now();
    setToasts((prev) => [...prev, { id, msg, type }]);
    const duration = type === 'error' ? null : type === 'warning' ? 6000 : 4000;
    if (duration) setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), duration);
  }, []);
  const dismiss = React.useCallback((id) => setToasts((prev) => prev.filter((t) => t.id !== id)), []);
  return { toasts, addToast, dismiss };
};

// ── ToastArea component ──────────────────────────────────────────
const TOAST_ICONS = {
  success: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6L9 17l-5-5" /></svg>,
  error: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12" /></svg>,
  warning: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M12 9v4M12 17h.01M10.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" /></svg>,
  info: <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10" /><path d="M12 16v-4M12 8h.01" /></svg>
};
const TOAST_DURATION = { success: 4000, error: null, warning: 6000, info: 4000 };

const ToastArea = ({ toasts, dismiss }) =>
<div className="toast-area">
    {toasts.map((t) => {
    const dur = TOAST_DURATION[t.type];
    return (
      <div key={t.id} className="toast">
          <div className={`toast-icon toast-icon-${t.type}`}>{TOAST_ICONS[t.type] || TOAST_ICONS.info}</div>
          <span style={{ flex: 1, fontSize: 14, fontWeight: 500, color: 'var(--col-text)', lineHeight: 1.4 }}>{t.msg}</span>
          <button onClick={() => dismiss(t.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '0 2px', color: 'var(--col-text-3)', display: 'flex', alignItems: 'center', borderRadius: 6, flexShrink: 0 }}
        onMouseOver={(e) => e.currentTarget.style.color = 'var(--col-text)'}
        onMouseOut={(e) => e.currentTarget.style.color = 'var(--col-text-3)'}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6L6 18M6 6l12 12" /></svg>
          </button>
          {dur &&
        <div className={`toast-progress toast-progress-${t.type}`}
        style={{ animationDuration: `${dur}ms` }} />
        }
        </div>);

  })}
  </div>;


// ── Confirm Modal ────────────────────────────────────────────────
const ConfirmModal = ({ title, body, confirmLabel = 'Confirm', confirmClass = 'btn-primary', onConfirm, onCancel }) =>
<div className="modal-overlay" onClick={onCancel}>
    <div className="modal" onClick={(e) => e.stopPropagation()}>
      <div className="modal-header">
        <div className="modal-title">{title}</div>
      </div>
      <div className="modal-body">{body}</div>
      <div className="modal-footer">
        <button className="btn btn-secondary btn-md" onClick={onCancel}>Cancel</button>
        <button className={`btn ${confirmClass} btn-md`} onClick={onConfirm}>{confirmLabel}</button>
      </div>
    </div>
  </div>;


// ── Search Input ──────────────────────────────────────────────────
const SearchInput = ({ value, onChange, placeholder = 'Search…', style }) =>
<div style={{ position: 'relative', ...style }}>
    <div style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', display: 'flex', alignItems: 'center' }}>
      <IcoSearch size={14} color="var(--col-text-3)" />
    </div>
    <input
    value={value}
    onChange={(e) => onChange(e.target.value)}
    placeholder={placeholder}
    style={{
      height: 36, width: '100%', paddingLeft: 32, paddingRight: 12,
      border: '1px solid var(--col-border)', borderRadius: 9,
      background: 'var(--col-surface)', color: 'var(--col-text)',
      fontSize: 13, fontFamily: 'inherit', outline: 'none',
      transition: 'border-color 150ms ease'
    }}
    onFocus={(e) => e.target.style.borderColor = 'var(--col-accent)'}
    onBlur={(e) => e.target.style.borderColor = 'var(--col-border)'} />
  
  </div>;


Object.assign(window, {
  Avatar, ChainBadge, StatusBadge, FlowChart, BalanceBar, ApprovalDots,
  fmt, fmtUSD, fmtFull, truncAddr, useToasts, ToastArea, ConfirmModal, SearchInput,
  CHAIN_META, STATUS_META
});