/* eslint-disable */
// Shared.jsx — pieces used across modules.

// =============== Auth chrome — split layout for onboarding ===============
const AuthShell = ({ children, step, totalSteps = 6, stepLabel }) => {
  const t = (typeof useT === 'function') ? useT() : ((en) => en);
  return (
  <div style={{
    display: 'flex', height: '100%', width: '100%',
    background: 'var(--bg-base)', color: 'var(--fg-primary)',
    fontFamily: 'var(--font-sans)', position: 'relative',
  }}>
    {/* Left — brand panel */}
    <aside style={{
      width: 380, flexShrink: 0,
      background: 'linear-gradient(165deg, #1A1815 0%, #221F1A 50%, #1A1815 100%)',
      borderRight: '1px solid var(--border-subtle)',
      padding: '36px 32px',
      display: 'flex', flexDirection: 'column',
      position: 'relative', overflow: 'hidden',
    }}>
      <div style={{ position: 'absolute', inset: 0, background: 'var(--grad-vignette)', pointerEvents: 'none' }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, position: 'relative' }}>
        <img src="design_system/assets/kgst-mark-square.png" alt="KGST"
          style={{ width: 34, height: 34, borderRadius: 6 }} />
        <div style={{ display: 'flex', flexDirection: 'column', lineHeight: 1.1 }}>
          <span style={{ fontWeight: 700, letterSpacing: '0.05em' }}>KGST</span>
          <span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{t('Institutional Onboarding', 'Институциональная регистрация')}</span>
        </div>
      </div>

      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', position: 'relative' }}>
        <span className="kgst-caption" style={{ color: 'var(--bone-3)', marginBottom: 14 }}>{t('National Stablecoin · Kyrgyz Republic', 'Национальный стейблкоин · Кыргызская Республика')}</span>
        <h2 className="kgst-h2" style={{ margin: 0, fontSize: 30, lineHeight: 1.15 }}>
          {t('A public, fully-reserved stablecoin pegged ', 'Публичный стейблкоин с полным резервом, привязанный ')}
          <span className="kgst-foil" style={{ fontWeight: 700 }}>1:1</span>
          {t(' to the Kyrgyz som.', ' к кыргызскому сому.')}
        </h2>
        <p style={{ marginTop: 14, color: 'var(--fg-secondary)', fontSize: 13.5, lineHeight: 1.55, maxWidth: 320 }}>
          {t('Reserves held in state-owned banks of the Kyrgyz Republic. This console grants institutional access to mint and burn KGST against KGS wire transfers.', 'Резервы хранятся в государственных банках Кыргызской Республики. Эта консоль даёт институтам доступ к эмиссии и погашению KGST против KGS-переводов.')}
        </p>
      </div>

      {step ? (
        <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span className="kgst-caption" style={{ color: 'var(--bone-3)' }}>{t(`Step ${step} of ${totalSteps}`, `Шаг ${step} из ${totalSteps}`)}</span>
            <span style={{ fontSize: 12, color: 'var(--fg-secondary)' }}>{stepLabel}</span>
          </div>
          <div style={{ height: 3, borderRadius: 999, background: 'var(--ink-3)', overflow: 'hidden' }}>
            <div style={{
              width: `${(step / totalSteps) * 100}%`, height: '100%',
              background: 'var(--grad-gold-bar)',
            }} />
          </div>
        </div>
      ) : null}
    </aside>

    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, overflow: 'auto' }}>
      <header style={{
        height: 52, display: 'flex', alignItems: 'center', justifyContent: 'flex-end',
        padding: '0 32px', borderBottom: '1px solid var(--border-subtle)',
        flexShrink: 0, gap: 14,
      }}>
        {(typeof LangToggle === 'function') ? <LangToggle /> : null}
        <span style={{ width: 1, height: 16, background: 'var(--border-subtle)' }} />
        <span style={{ fontSize: 12, color: 'var(--fg-tertiary)' }}>{t('Need help?', 'Нужна помощь?')}</span>
        <a style={{ fontSize: 12, color: 'var(--gold-300)', textDecoration: 'none' }}>onboarding@kgst.kg</a>
      </header>
      <main style={{ flex: 1, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '60px 40px' }}>
        {children}
      </main>
    </div>
    <SignBadge />
  </div>
  );
};

// =============== Stepper — used in Mint/Burn status ===============
const Stepper = ({ steps, current, failed }) => (
  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 0 }}>
    {steps.map((s, i) => {
      const done = i < current;
      const active = i === current && !failed;
      const failedStep = i === current && failed;
      const upcoming = i > current;
      const tone = done ? 'var(--gold-300)' : active ? 'var(--gold-400)' : failedStep ? 'var(--red-400)' : 'var(--bone-2)';
      return (
        <React.Fragment key={i}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flex: '0 0 auto', minWidth: 84 }}>
            <div style={{
              width: 28, height: 28, borderRadius: '50%',
              border: `1.5px solid ${tone}`,
              background: done ? 'var(--gold-400)' : active ? 'rgba(167,132,56,0.18)' : 'var(--ink-2)',
              color: done ? 'var(--ink-1)' : tone,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-mono)', fontSize: 11, fontWeight: 700,
              boxShadow: active ? '0 0 0 4px rgba(167,132,56,0.12)' : 'none',
              position: 'relative',
            }}>
              {done ? <Icons.check size={14} /> : failedStep ? <Icons.x size={14} /> : (i + 1)}
              {active && !failed ? (
                <span style={{
                  position: 'absolute', inset: -2, borderRadius: '50%',
                  border: '1.5px solid var(--gold-400)', opacity: 0.6,
                  animation: 'kgstPulse 1.8s ease-in-out infinite',
                }} />
              ) : null}
            </div>
            <div style={{ marginTop: 8, fontSize: 11, color: upcoming ? 'var(--fg-tertiary)' : 'var(--fg-secondary)', textAlign: 'center', maxWidth: 110, lineHeight: 1.3 }}>
              {s.label}
            </div>
            {s.sub ? <div style={{ marginTop: 3, fontSize: 10, color: 'var(--fg-tertiary)', fontFamily: 'var(--font-mono)', textAlign: 'center' }}>{s.sub}</div> : null}
          </div>
          {i < steps.length - 1 ? (
            <div style={{ flex: '1 1 auto', height: 1.5, background: i < current ? 'var(--gold-400)' : 'var(--border-default)', marginTop: 13, minWidth: 12 }} />
          ) : null}
        </React.Fragment>
      );
    })}
  </div>
);

// =============== KGST mono amount ===============
const Amount = ({ value, unit = 'KGST', size = 32, tone = 'foil' }) => (
  <span className="kgst-mono kgst-num" style={{
    display: 'inline-flex', alignItems: 'baseline', gap: 8,
    fontSize: size, lineHeight: 1.1, fontWeight: 600,
    letterSpacing: '-0.01em',
  }}>
    <span style={{
      ...(tone === 'foil' ? {
        background: 'linear-gradient(180deg,#F8E8A8 0%,#D9B45A 50%,#8A6018 100%)',
        WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
      } : { color: tone === 'gold' ? 'var(--gold-300)' : 'var(--fg-primary)' }),
    }}>{value}</span>
    <span style={{ fontSize: Math.max(11, size * 0.34), color: 'var(--fg-tertiary)', fontWeight: 500 }}>{unit}</span>
  </span>
);

// =============== Field row used in confirmations / details ===============
const Field = ({ label, value, mono, copyable, action, valueColor, sub }) => (
  <div style={{
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 16,
    padding: '12px 0', borderBottom: '1px solid var(--border-subtle)',
  }}>
    <span style={{ fontSize: 12.5, color: 'var(--fg-tertiary)', flexShrink: 0, paddingTop: 1 }}>{label}</span>
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, minWidth: 0, flex: 1 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13,
        color: valueColor || 'var(--fg-primary)',
        fontFamily: mono ? 'var(--font-mono)' : 'var(--font-sans)',
        textAlign: 'right',
      }}>
        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</span>
        {copyable ? (
          <span style={{ color: 'var(--bone-3)', cursor: 'pointer', display: 'inline-flex' }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <rect x="9" y="9" width="13" height="13" rx="2" /><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
            </svg>
          </span>
        ) : null}
        {action}
      </div>
      {sub ? <span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{sub}</span> : null}
    </div>
  </div>
);

// =============== Modal scrim (used to show modal screens inside a host page) ===============
const ModalScrim = ({ children, width = 480 }) => (
  <div style={{
    position: 'absolute', inset: 0,
    background: 'rgba(0,0,0,0.55)',
    backdropFilter: 'blur(3px)', WebkitBackdropFilter: 'blur(3px)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    zIndex: 10,
  }}>
    <div style={{
      width, maxWidth: '90%', background: 'var(--bg-raised)',
      border: '1px solid var(--border-default)',
      boxShadow: 'var(--shadow-lg)',
      borderRadius: 14,
      overflow: 'hidden',
    }}>
      {children}
    </div>
  </div>
);

const ModalHeader = ({ title, sub, onClose = true }) => (
  <div style={{
    padding: '20px 24px 16px',
    borderBottom: '1px solid var(--border-subtle)',
    display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16,
  }}>
    <div>
      <div className="kgst-h3" style={{ margin: 0, fontSize: 17 }}>{title}</div>
      {sub ? <div style={{ marginTop: 4, fontSize: 12.5, color: 'var(--fg-secondary)' }}>{sub}</div> : null}
    </div>
    {onClose ? <Icons.x size={16} style={{ color: 'var(--bone-3)', cursor: 'pointer' }} /> : null}
  </div>
);

// =============== QR placeholder — looks like a real QR without rendering one ===============
const QRPlaceholder = ({ size = 180, data }) => {
  // deterministic pseudo-random fill based on data
  const seed = (data || 'kgst').split('').reduce((a,c) => a + c.charCodeAt(0), 0);
  const rnd = (i) => {
    let v = Math.sin((seed + i * 1.71) * 12.9898) * 43758.5453;
    return (v - Math.floor(v));
  };
  const N = 25;
  const cells = [];
  for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) {
    // finder patterns at corners
    const isFinder =
      (r < 7 && c < 7) || (r < 7 && c >= N - 7) || (r >= N - 7 && c < 7);
    if (isFinder) continue;
    if (rnd(r * N + c) > 0.55) cells.push([r, c]);
  }
  const cell = size / N;
  return (
    <div style={{
      width: size, height: size, background: '#fff', borderRadius: 6,
      padding: cell, position: 'relative',
    }}>
      <svg viewBox={`0 0 ${N} ${N}`} width={size - cell * 2} height={size - cell * 2}>
        {/* finder patterns */}
        {[[0,0],[0,N-7],[N-7,0]].map(([r,c],i) => (
          <g key={i}>
            <rect x={c} y={r} width={7} height={7} fill="#000" />
            <rect x={c+1} y={r+1} width={5} height={5} fill="#fff" />
            <rect x={c+2} y={r+2} width={3} height={3} fill="#000" />
          </g>
        ))}
        {cells.map(([r,c], i) => <rect key={i} x={c} y={r} width={1} height={1} fill="#000" />)}
      </svg>
    </div>
  );
};

// =============== Address / hash chip ===============
const AddrChip = ({ addr, chain, short = true }) => {
  const display = short ? `${addr.slice(0, 6)}…${addr.slice(-6)}` : addr;
  return (
    <span className="kgst-mono" style={{
      display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12,
      color: 'var(--fg-secondary)',
    }}>
      {chain ? <ChainBadge chain={chain} small /> : null}
      <span>{display}</span>
    </span>
  );
};

const CHAIN_MAP = {
  eth: { name: 'Ethereum', short: 'ETH', color: '#627EEA' },
  tron:{ name: 'Tron',     short: 'TRX', color: '#EB0029' },
  bnb: { name: 'BNB Chain',short: 'BNB', color: '#F3BA2F' },
};
const ChainBadge = ({ chain, small, withLabel }) => {
  const c = CHAIN_MAP[chain] || CHAIN_MAP.eth;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 6,
      fontSize: small ? 10.5 : 11.5,
      color: 'var(--fg-secondary)',
    }}>
      <span style={{
        width: small ? 14 : 18, height: small ? 14 : 18, borderRadius: '50%',
        background: `radial-gradient(circle at 35% 30%, ${c.color}, ${c.color}99 60%, ${c.color}44 100%)`,
        boxShadow: 'inset 0 0 0 1px rgba(255,255,255,0.06)',
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        fontSize: small ? 6 : 7, fontWeight: 700, color: '#fff', letterSpacing: '0.05em',
      }}>{c.short.slice(0,1)}</span>
      {withLabel ? <span>{c.name}</span> : null}
    </span>
  );
};

// =============== Selector row (chain / address pickers) ===============
const Selector = ({ label, value, hint, leading, trailing, selected, helper, error, onClick }) => (
  <div onClick={onClick} style={{
    display: 'flex', alignItems: 'center', gap: 12,
    padding: '12px 14px', borderRadius: 8,
    background: 'var(--ink-2)',
    border: `1px solid ${selected ? 'var(--border-gold)' : error ? 'rgba(196,69,69,0.4)' : 'var(--border-default)'}`,
    cursor: onClick ? 'pointer' : 'default',
    boxShadow: selected ? '0 0 0 2px rgba(201,152,64,0.10)' : 'none',
  }}>
    {leading ? <div style={{ flexShrink: 0 }}>{leading}</div> : null}
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
      {label ? <span style={{ fontSize: 10.5, color: 'var(--fg-tertiary)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{label}</span> : null}
      <span style={{ fontSize: 13.5, color: 'var(--fg-primary)', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{value}</span>
      {hint ? <span style={{ fontSize: 11, color: 'var(--fg-tertiary)' }}>{hint}</span> : null}
    </div>
    {trailing}
  </div>
);

// =============== Verification code boxes (6-digit OTP) ===============
const OTPInput = ({ digits = ['1','5','2','9'], length = 6 }) => (
  <div style={{ display: 'flex', gap: 8 }}>
    {Array.from({ length }).map((_, i) => {
      const v = digits[i];
      const cur = digits.length === i;
      return (
        <div key={i} style={{
          width: 46, height: 54, borderRadius: 8,
          background: 'var(--ink-2)',
          border: `1px solid ${cur ? 'var(--border-gold)' : 'var(--border-default)'}`,
          boxShadow: cur ? '0 0 0 2px rgba(201,152,64,0.15)' : 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-mono)', fontSize: 22, fontWeight: 600,
          color: v ? 'var(--fg-primary)' : 'var(--fg-tertiary)',
          position: 'relative',
        }}>
          {v || ''}
          {cur ? <span style={{
            position: 'absolute', width: 1.5, height: 24, background: 'var(--gold-300)',
            animation: 'kgstPulse 1.1s ease-in-out infinite',
          }} /> : null}
        </div>
      );
    })}
  </div>
);

// =============== Mini sparkline / chart placeholder ===============
const Sparkline = ({ data, height = 60, color = 'var(--gold-300)', fill = true }) => {
  const w = 300;
  const max = Math.max(...data), min = Math.min(...data);
  const range = (max - min) || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = height - 4 - ((v - min) / range) * (height - 10);
    return [x, y];
  });
  const d = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  const fillD = d + ` L ${w} ${height} L 0 ${height} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${height}`} preserveAspectRatio="none" style={{ width: '100%', height }}>
      <defs>
        <linearGradient id={`spl-${color}`} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%" stopColor={color} stopOpacity="0.35" />
          <stop offset="100%" stopColor={color} stopOpacity="0" />
        </linearGradient>
      </defs>
      {fill ? <path d={fillD} fill={`url(#spl-${color})`} /> : null}
      <path d={d} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

Object.assign(window, {
  AuthShell, Stepper, Amount, Field, ModalScrim, ModalHeader,
  QRPlaceholder, AddrChip, ChainBadge, Selector, OTPInput, Sparkline, CHAIN_MAP,
});
