// Astrail — Auth Screens: Login · Register · Onboarding

// ── Password strength indicator ───────────────────────────────
const PwdStrength = ({ password }) => {
  const score = React.useMemo(() => {
    if (!password) return 0;
    let s = 0;
    if (password.length >= 8)          s++;
    if (password.length >= 12)         s++;
    if (/[A-Z]/.test(password))        s++;
    if (/[0-9]/.test(password))        s++;
    if (/[^A-Za-z0-9]/.test(password)) s++;
    return Math.min(s, 4);
  }, [password]);
  const labels = ['', 'Weak', 'Fair', 'Good', 'Strong'];
  const colors = ['', '#DC2626', '#D97706', '#16A34A', '#059669'];
  if (!password) return null;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:6 }}>
      <div style={{ display:'flex', gap:3, flex:1 }}>
        {[1,2,3,4].map(i =>
          <div key={i} style={{ flex:1, height:3, borderRadius:999, background: i <= score ? colors[score] : 'var(--col-border)', transition:'background 220ms' }} />
        )}
      </div>
      <span style={{ fontSize:11, fontWeight:600, minWidth:40, textAlign:'right', color: score > 0 ? colors[score] : 'var(--col-text-3)', transition:'color 220ms' }}>
        {labels[score]}
      </span>
    </div>
  );
};

// ── Shared: Password input with show/hide ─────────────────────
const PwdInput = ({ value, onChange, placeholder = '••••••••', autoComplete = 'current-password' }) => {
  const [show, setShow] = React.useState(false);
  return (
    <div className="input-pwd-wrap">
      <input
        type={show ? 'text' : 'password'}
        className="form-input"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        autoComplete={autoComplete} />
      <button type="button" className="input-pwd-toggle" onClick={() => setShow((s) => !s)}
        style={{ display:'flex', alignItems:'center', justifyContent:'center', width:34, padding:0, background:'none', border:'none', cursor:'pointer', color:'var(--col-text-3)' }}
        title={show ? 'Hide password' : 'Show password'}>
        {show
          ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
          : <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
        }
      </button>
    </div>);
};

// ── Shared: Registration step indicator ──────────────────────
const RegSteps = ({ labels, current }) =>
<div className="reg-steps">
    {labels.map((lbl, i) =>
  <React.Fragment key={i}>
        {i > 0 && <div className={`reg-step-line ${i <= current ? 'done' : ''}`} />}
        <div className={`reg-step ${i < current ? 's-done' : i === current ? 's-active' : ''}`}>
          <div className="reg-step-dot">
            {i < current ? <IcoCheck size={11} color="#fff" /> : i + 1}
          </div>
          <span className="reg-step-lbl">{lbl}</span>
        </div>
      </React.Fragment>
  )}
  </div>;


// ── Shared: Brand panel ───────────────────────────────────────
const AuthBrand = ({ headline, bullets }) =>
<div className="auth-brand"
  style={{ background:'var(--auth-brand-bg, linear-gradient(145deg,#060E12 0%,#0C1E20 35%,#081818 65%,#071218 100%))', position:'relative', overflow:'hidden' }}>
    {/* Decorative glows */}
    <div style={{ position:'absolute', top:-80, right:-60, width:440, height:440, borderRadius:'50%', background:'radial-gradient(circle,rgba(95,138,255,0.38) 0%,transparent 68%)', filter:'blur(64px)', pointerEvents:'none', willChange:'transform,opacity', animation:'aurGlow1 11s ease-in-out infinite' }} />
    <div style={{ position:'absolute', bottom:-60, left:-80, width:300, height:300, borderRadius:'50%', background:'radial-gradient(circle,rgba(69,113,242,0.30) 0%,transparent 68%)', filter:'blur(58px)', pointerEvents:'none', willChange:'transform,opacity', animation:'aurGlow2 15s ease-in-out infinite' }} />
    <div style={{ position:'absolute', top:'38%', left:'28%', width:200, height:200, borderRadius:'50%', background:'radial-gradient(circle,rgba(0,230,180,0.22) 0%,transparent 68%)', filter:'blur(50px)', pointerEvents:'none', willChange:'transform,opacity', animation:'aurGlow3 8s ease-in-out infinite' }} />
    <div style={{ position:'absolute', top:'15%', left:'10%', width:160, height:160, borderRadius:'50%', background:'radial-gradient(circle,rgba(95,138,255,0.18) 0%,transparent 68%)', filter:'blur(44px)', pointerEvents:'none', willChange:'transform,opacity', animation:'aurGlow4 13s ease-in-out infinite 2s' }} />

    <div style={{ position:'relative' }}>
      <div className="auth-brand-logo">
        <div className="auth-brand-mark">
          <svg width="18" height="18" viewBox="0 0 16 16" fill="none">
            <path d="M3.6 13.4 8 2.6l4.4 10.8" stroke="#F4F1EC" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" fill="none" /><path d="M5.6 9.5h4.8" stroke="#5F8AFF" strokeWidth="1.9" strokeLinecap="round" />
          </svg>
        </div>
        <span className="auth-brand-name">Astrail</span>
      </div>

      <div className="auth-brand-hl" dangerouslySetInnerHTML={{ __html: headline }} />

      <div className="auth-brand-feats">
        {bullets.map((b, i) =>
      <div key={i} className="auth-feat-row">
            <div className="auth-feat-ico">
              <b.Icon size={16} color="rgba(160,186,255,.88)" />
            </div>
            <div>
              <div className="auth-feat-title">{b.title}</div>
              <div className="auth-feat-desc">{b.desc}</div>
            </div>
          </div>
      )}
      </div>

    </div>
  </div>;


// ── Login Screen ──────────────────────────────────────────────
const LoginScreen = ({ onLogin, onGoToRegister }) => {
  const [email, setEmail] = React.useState('finance@acme-labs.io');
  const [password, setPassword] = React.useState('demo-workspace');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState('');
  const [forgotSent, setForgotSent] = React.useState(false);

  const submit = (e) => {
    e.preventDefault();
    if (!email || !password) {setError('Please enter your email and password.');return;}
    setError('');
    setLoading(true);
    setTimeout(onLogin, 1400);
  };

  const BULLETS = [
  { Icon: IcoTreasury, title: 'Batch payouts', desc: 'TRON, Ethereum, BSC, Arbitrum, Base' },
  { Icon: IcoApprovals, title: 'Your keys, your signers', desc: 'Safe and TRON multisig, m of n' },
  { Icon: IcoPayroll, title: 'Audit-ready', desc: 'Invoice, purpose, hash on every line' }];


  return (
    <div className="auth-shell">
      <AuthBrand headline={'Crypto payouts,<br/><em>in one batch.</em>'} bullets={BULLETS} />

      <div className="auth-panel">
        <div className="auth-wrap">
          <div className="auth-title">Welcome back</div>
          <div className="auth-sub">Sign in to your workspace</div>

          <form className="auth-form" onSubmit={submit}>
            <div className="form-group">
              <label className="form-label">Email</label>
              <input type="email" className="form-input" value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="you@company.com" autoComplete="email" />
            </div>

            <div className="form-group">
              <div className="auth-row-label">
                <label className="form-label" style={{ marginBottom: 0 }}>Password</label>
                <button type="button" className="btn btn-link" style={{ fontSize: 12, padding: 0, height: 'auto' }}
                  onClick={() => { if (email) setForgotSent(true); else setError('Enter your email above first.'); }}>
                  Forgot password?
                </button>
              </div>
              <PwdInput value={password} onChange={setPassword} />
              {forgotSent &&
                <div style={{ marginTop:6, padding:'8px 12px', borderRadius:8, background:'var(--col-success-bg)', border:'1px solid var(--col-success-border,#86efac)', fontSize:12, color:'var(--col-success)' }}>
                  Reset link sent to {email}
                </div>
              }
            </div>

            {error &&
            <div className="form-error">
                <IcoAlert size={13} color="var(--col-error)" />
                {error}
              </div>
            }

            <button type="submit" className="btn btn-primary btn-lg"
            style={{ width: '100%', justifyContent: 'center', gap: 8, marginTop: 4 }}
            disabled={loading}>
              {loading ? <><LoaderArc size="sm" /> Signing in…</> : 'Sign in'}
            </button>
          </form>

          <div className="auth-divider"><span>or</span></div>

          <button className="auth-3p-btn"
          onClick={() => {setLoading(true);setTimeout(onLogin, 1000);}}>
            <IcoWallet size={17} color="var(--col-text-2)" />
            Connect wallet to sign in
          </button>
          <p style={{ textAlign:'center', fontSize:11, color:'var(--col-text-3)', marginTop:8, lineHeight:1.4 }}>
            New? You'll be asked to complete your profile after connecting.
          </p>

          <div className="auth-foot-link">
            Don't have an account?{' '}
            <button className="btn btn-link" onClick={onGoToRegister}>Create one free</button>
          </div>
        </div>
      </div>
    </div>);

};

// ── Register Screen ───────────────────────────────────────────
const RegisterScreen = ({ onComplete, onGoToLogin }) => {
  const [step, setStep] = React.useState(0);
  const [loading, setLoading] = React.useState(false);
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [company, setCompany] = React.useState('');
  const [workspace, setWorkspace] = React.useState('');
  const [size, setSize] = React.useState('');
  const [role, setRole] = React.useState('');

  const STEPS = ['Account', 'Organization', 'Done'];
  const SIZES = ['1–5', '6–20', '21–100', '100+'];
  const ROLES = ['Founder / CEO', 'Finance Lead', 'Operations', 'Engineer', 'Other'];

  const BULLETS = [
  { title: 'Connect your Safe, TRON multisig or wallet' },
  { title: 'Import your team in seconds via CSV' },
  { title: 'Run your first payroll in under 5 minutes' },
  { title: 'Multi-sig approval flows included' }];


  const submitStep0 = (e) => {
    e.preventDefault();
    if (!name || !email || !password) return;
    setStep(1);
  };

  const submitStep1 = (e) => {
    e.preventDefault();
    if (!company) return;
    setLoading(true);
    setTimeout(() => {setLoading(false);setStep(2);}, 900);
  };

  const RegBrand = () =>
  <div className="auth-brand">
      <div className="auth-brand-logo">
        <div className="auth-brand-mark">
          <svg width="18" height="18" viewBox="0 0 16 16" fill="none">
            <path d="M3.6 13.4 8 2.6l4.4 10.8" stroke="#F4F1EC" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" fill="none" /><path d="M5.6 9.5h4.8" stroke="#5F8AFF" strokeWidth="1.9" strokeLinecap="round" />
          </svg>
        </div>
        <span className="auth-brand-name">Astrail</span>
      </div>
      <div className="auth-brand-hl" style={{ fontSize: 29 }}>
        Your crypto finance OS.<br /><em>Set up in minutes.</em>
      </div>
      <div className="auth-brand-feats">
        {BULLETS.map((b, i) =>
      <div key={i} className="auth-feat-row" style={{ alignItems: 'center' }}>
            <div style={{ width: 22, height: 22, borderRadius: 6, flexShrink: 0, background: 'rgba(95,138,255,.16)', border: '1px solid rgba(95,138,255,.26)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <IcoCheck size={11} color="rgba(160,186,255,.9)" />
            </div>
            <span className="auth-feat-desc" style={{ color: 'rgba(255,255,255,.55)' }}>{b.title}</span>
          </div>
      )}
      </div>
    </div>;


  return (
    <div className="auth-shell">
      <RegBrand />
      <div className="auth-panel">
        <div className="auth-wrap">
          <RegSteps labels={STEPS} current={step} />

          {step === 0 &&
          <>
              <div className="auth-title">Create your account</div>
              <div className="auth-sub">Free to start — no credit card required</div>
              <form className="auth-form" onSubmit={submitStep0}>
                <div className="form-group">
                  <label className="form-label">Full name</label>
                  <input type="text" className="form-input" value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Alice Johnson" autoComplete="name" />
                </div>
                <div className="form-group">
                  <label className="form-label">Email</label>
                  <input type="email" className="form-input" value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="you@company.com" autoComplete="email" />
                </div>
                <div className="form-group">
                  <label className="form-label">Password</label>
                  <PwdInput value={password} onChange={setPassword} autoComplete="new-password" placeholder="Choose a strong password" />
                  <PwdStrength password={password} />
                </div>
                <button type="submit" className="btn btn-primary btn-lg"
              style={{ width: '100%', justifyContent: 'center', gap: 8, marginTop: 4 }}>
                  Continue <IcoArrowRight size={15} color="white" />
                </button>
              </form>
              <div className="auth-foot-link">
                Already have an account?{' '}
                <button className="btn btn-link" onClick={onGoToLogin}>Sign in</button>
              </div>
            </>
          }

          {step === 1 &&
          <>
              <div className="auth-title">Your organization</div>
              <div className="auth-sub">Helps us configure your workspace correctly</div>
              <form className="auth-form" onSubmit={submitStep1}>
                <div className="form-group">
                  <label className="form-label">Workspace name <span style={{ fontSize:11, color:'var(--col-text-3)', fontWeight:400 }}>— internal identifier in Astrail</span></label>
                  <input type="text" className="form-input" value={workspace}
                onChange={(e) => setWorkspace(e.target.value)}
                placeholder="acme-finance" autoComplete="off" />
                </div>
                <div className="form-group">
                  <label className="form-label">Legal company name <span style={{ fontSize:11, color:'var(--col-text-3)', fontWeight:400 }}>— for invoices &amp; reports</span></label>
                  <input type="text" className="form-input" value={company}
                onChange={(e) => setCompany(e.target.value)}
                placeholder="Acme Corp Ltd." autoComplete="organization" />
                </div>
                <div className="form-group">
                  <label className="form-label">Team size</label>
                  <div className="chip-group">
                    {SIZES.map((s) =>
                  <button type="button" key={s} className={`chip ${size === s ? 'on' : ''}`}
                  onClick={() => setSize(s)}>{s}</button>
                  )}
                  </div>
                </div>
                <div className="form-group">
                  <label className="form-label">Your role</label>
                  <div className="chip-group">
                    {ROLES.map((r) =>
                  <button type="button" key={r} className={`chip ${role === r ? 'on' : ''}`}
                  onClick={() => setRole(r)}>{r}</button>
                  )}
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
                  <button type="button" className="btn btn-secondary btn-lg" onClick={() => setStep(0)}>
                    Back
                  </button>
                  <button type="submit" className="btn btn-primary btn-lg"
                style={{ flex: 1, justifyContent: 'center', gap: 8 }}
                disabled={loading || !company}>
                    {loading ?
                  <><LoaderArc size="sm" /> Creating account…</> :
                  <>Continue <IcoArrowRight size={15} color="white" /></>
                  }
                  </button>
                </div>
              </form>
            </>
          }

          {step === 2 &&
          <div style={{ textAlign: 'center' }}>
              <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--col-success-bg)', border: '2px solid var(--col-success-border)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px' }}>
                <IcoCheck size={28} color="var(--col-success)" />
              </div>
              <div className="auth-title" style={{ textAlign: 'center' }}>Account created!</div>
              <div className="auth-sub" style={{ textAlign: 'center', marginBottom: 32 }}>
                Welcome to Astrail{name ? `, ${name.split(' ')[0]}` : ''}. Let's set up your workspace.
              </div>
              <button className="btn btn-primary btn-lg"
            style={{ width: '100%', justifyContent: 'center', gap: 8 }}
            onClick={onComplete}>
                Set up workspace <IcoArrowRight size={15} color="white" />
              </button>
              <div className="auth-foot-link" style={{ marginTop: 16 }}>
                <button className="btn btn-link" style={{ color: 'var(--col-text-3)' }}
              onClick={onGoToLogin}>
                  Skip — go to sign in
                </button>
              </div>
            </div>
          }
        </div>
      </div>
    </div>);

};

// ── Onboarding Screen ─────────────────────────────────────────
const OnboardingScreen = ({ onComplete }) => {
  const [step, setStep] = React.useState(0);
  const [selectedWallet, setSelectedWallet] = React.useState(null);
  const [walletConnected, setWalletConnected] = React.useState(false);
  const [connecting, setConnecting] = React.useState(false);
  const [wcModalOpen, setWcModalOpen] = React.useState(false);
  const [wcWallet, setWcWallet] = React.useState(null);
  const [inviteEmail, setInviteEmail] = React.useState('');
  const [inviteRole, setInviteRole] = React.useState('Approver');
  const [invitees, setInvitees] = React.useState([]);

  const TOTAL = 4;
  const pct = step / (TOTAL - 1) * 100;

  const WALLETS = [
  { id: 'walletconnect', name: 'WalletConnect', hint: 'MetaMask, Phantom & 300+ wallets', color: '#3B99FC',
    Logo: () => <svg width="22" height="16" viewBox="0 0 40 25" fill="none"><path d="M8.2 6.8C14.7.3 25.3.3 31.8 6.8L32.7 7.7C33 8 33 8.5 32.7 8.8L29.5 12C29.3 12.2 29 12.2 28.8 12L27.5 10.7C22.9 6.1 17.1 6.1 12.5 10.7L11.1 12.1C10.9 12.3 10.6 12.3 10.4 12.1L7.2 8.9C6.9 8.6 6.9 8.1 7.2 7.8L8.2 6.8ZM37.2 12.3L40 15.1C40.3 15.4 40.3 15.9 40 16.2L28.1 28.1C27.8 28.4 27.3 28.4 27 28.1L18.6 19.7C18.5 19.6 18.3 19.6 18.2 19.7L9.8 28.1C9.5 28.4 9 28.4 8.7 28.1L-3.2 16.2C-3.5 15.9-3.5 15.4-3.2 15.1L-0.4 12.3C-0.1 12 0.4 12 0.7 12.3L9.1 20.7C9.2 20.8 9.4 20.8 9.5 20.7L17.9 12.3C18.2 12 18.7 12 19 12.3L27.4 20.7C27.5 20.8 27.7 20.8 27.8 20.7L36.2 12.3C36.6 12 37.1 12 37.2 12.3Z" fill="#3B99FC" transform="translate(4,0) scale(0.82)"/></svg> },
  { id: 'tronlink', name: 'TronLink', hint: 'Tron network', color: '#E84142',
    Logo: () => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><polygon points="12,3 21,8 21,16 12,21 3,16 3,8" stroke="#E84142" strokeWidth="1.5" fill="rgba(232,65,66,0.10)"/><line x1="9" y1="9" x2="15" y2="9" stroke="#E84142" strokeWidth="2" strokeLinecap="round"/><line x1="12" y1="9" x2="12" y2="16" stroke="#E84142" strokeWidth="2" strokeLinecap="round"/></svg> },
  { id: 'ledger', name: 'Ledger', hint: 'Hardware wallet', color: '#1C1C1C',
    Logo: () => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><rect x="3" y="5" width="18" height="14" rx="2.5" fill="rgba(0,0,0,0.07)" stroke="#1C1C1C" strokeWidth="1.4"/><path d="M7.5 8V16M7.5 16H16.5" stroke="#1C1C1C" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg> },
  { id: 'phantom', name: 'Phantom', hint: 'Solana & EVM', color: '#9B8EDB',
    Logo: () => <svg width="22" height="22" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" fill="rgba(155,142,219,0.14)"/><path d="M8 12C8 9.8 9.8 8 12 8C14.2 8 16 9.8 16 12C16 14.5 14 16.5 11.9 16.5L10.2 17.2L10.7 15.8C9.1 14.9 8 13.5 8 12Z" fill="#9B8EDB" opacity="0.75"/><circle cx="10.8" cy="11.6" r="1.1" fill="white"/><circle cx="13.2" cy="11.6" r="1.1" fill="white"/></svg> },
  ];

  const WC_WALLETS = [
  { id: 'metamask',  name: 'MetaMask',        color: '#F6851B', bg: 'rgba(246,133,27,0.12)',  Logo: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M21 3L13.5 9l1.4-3.3L21 3Z" fill="#E17726"/><path d="M3 3l7.4 6.1L9.1 5.7 3 3Z" fill="#E27625"/><path d="M18.2 16.5l-2 3.1 4.3 1.2 1.2-4.2-3.5-.1Z" fill="#E27625"/><path d="M2.3 16.6l1.2 4.2 4.3-1.2-2-3.1-3.5.1Z" fill="#E27625"/><path d="M7.6 10.8l-1.2 1.8 4.2.2-.1-4.5-2.9 2.5Z" fill="#E27625"/><path d="M16.4 10.8l-3-2.6-.1 4.6 4.2-.2-1.1-1.8Z" fill="#E27625"/><path d="M7.8 19.6l2.5-1.2-2.2-1.7-.3 2.9Z" fill="#E27625"/><path d="M13.7 18.4l2.5 1.2-.3-2.9-2.2 1.7Z" fill="#E27625"/></svg> },
  { id: 'phantom',   name: 'Phantom',         color: '#9B8EDB', bg: 'rgba(155,142,219,0.12)', Logo: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" fill="rgba(155,142,219,0.18)"/><path d="M8 12C8 9.8 9.8 8 12 8C14.2 8 16 9.8 16 12C16 14.5 14 16.5 11.9 16.5L10.2 17.2L10.7 15.8C9.1 14.9 8 13.5 8 12Z" fill="#9B8EDB" opacity="0.8"/><circle cx="10.8" cy="11.6" r="1" fill="white"/><circle cx="13.2" cy="11.6" r="1" fill="white"/></svg> },
  { id: 'rainbow',   name: 'Rainbow',         color: '#FF6B6B', bg: 'rgba(255,107,107,0.10)', Logo: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M4 14C4 9.6 7.6 6 12 6C16.4 6 20 9.6 20 14" stroke="#FF6B6B" strokeWidth="2.2" strokeLinecap="round" fill="none"/><path d="M7 14C7 11.2 9.2 9 12 9C14.8 9 17 11.2 17 14" stroke="#FF9D5C" strokeWidth="2.2" strokeLinecap="round" fill="none"/><path d="M10 14C10 12.9 10.9 12 12 12C13.1 12 14 12.9 14 14" stroke="#FFCB5C" strokeWidth="2.2" strokeLinecap="round" fill="none"/></svg> },
  { id: 'coinbase',  name: 'Coinbase Wallet', color: '#0052FF', bg: 'rgba(0,82,255,0.10)',    Logo: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="9" fill="rgba(0,82,255,0.12)"/><circle cx="12" cy="12" r="9" stroke="#0052FF" strokeWidth="1.4" fill="none"/><rect x="8.5" y="9.5" width="7" height="5" rx="1.5" fill="#0052FF" opacity="0.8"/></svg> },
  ];

  const connectWallet = () => {
    if (!selectedWallet) return;
    if (selectedWallet === 'walletconnect') { setWcModalOpen(true); return; }
    setConnecting(true);
    setTimeout(() => {setConnecting(false);setWalletConnected(true);}, 1400);
  };

  const connectViaWC = (wId) => {
    setWcWallet(wId);
    setConnecting(true);
    setTimeout(() => {setWcModalOpen(false);setConnecting(false);setWalletConnected(true);}, 1400);
  };

  const addInvitee = () => {
    if (!inviteEmail.trim()) return;
    setInvitees((prev) => [...prev, { email: inviteEmail.trim(), role: inviteRole }]);
    setInviteEmail('');
  };

  const selWallet = WALLETS.find((w) => w.id === selectedWallet);

  return (
    <div className="onb-shell">

      {/* Header */}
      <div className="onb-header">
        <div className="onb-logo">
          <div className="onb-logo-mark">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
              <path d="M3.6 13.4 8 2.6l4.4 10.8" stroke="#F4F1EC" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" fill="none" /><path d="M5.6 9.5h4.8" stroke="#5F8AFF" strokeWidth="1.9" strokeLinecap="round" />
            </svg>
          </div>
          <span className="onb-logo-name">Astrail</span>
        </div>

        <span className="onb-step-label">Step {step + 1} of {TOTAL}</span>

        {step < TOTAL - 1 &&
        <button className="btn btn-ghost btn-sm" style={{ color: 'var(--col-text-3)' }}
        onClick={onComplete}>
            Skip setup
          </button>
        }
      </div>

      {/* Progress bar */}
      <div className="onb-bar">
        <div className="onb-bar-fill" style={{ width: `${pct}%` }} />
      </div>

      <div className="onb-body">
        <div className="onb-wrap">

          {/* ── Step 0: Welcome ─────────────────────── */}
          {step === 0 &&
          <>
              <div className="onb-eyebrow">Welcome to Astrail</div>
              <div className="onb-title">Your crypto finance OS<br />is ready.</div>
              <div className="onb-desc">Here's what you'll be able to do once your workspace is configured.</div>
              <div className="onb-feat-grid">
                {[
              { Icon: IcoTreasury, title: 'Treasury overview', desc: 'Unified balance view across all chains and wallets, updated in real time.' },
              { Icon: IcoPayroll, title: 'Payroll runs', desc: 'Batch-send to any number of recipients. CSV import and per-chain routing included.' },
              { Icon: IcoApprovals, title: 'Multi-sig approvals', desc: 'Set signature thresholds per run — no single point of failure on outgoing funds.' }].
              map((f) =>
              <div key={f.title} className="onb-feat-card">
                    <div className="onb-feat-card-ico">
                      <f.Icon size={18} color="var(--col-accent)" />
                    </div>
                    <div className="onb-feat-card-title">{f.title}</div>
                    <div className="onb-feat-card-desc">{f.desc}</div>
                  </div>
              )}
              </div>
              <div className="onb-actions">
                <button className="btn btn-primary btn-lg" style={{ gap: 8 }}
              onClick={() => setStep(1)}>
                  Let's get started <IcoArrowRight size={15} color="white" />
                </button>
              </div>
            </>
          }

          {/* ── Step 1: Connect wallet ───────────────── */}
          {step === 1 &&
          <>
              <div className="onb-eyebrow">Step 1 of 3</div>
              <div className="onb-title">Connect your treasury wallet</div>
              <div className="onb-desc">Link a wallet to manage funds and run payroll. You can add more wallets later from Treasury settings.</div>

              {!walletConnected ?
            <>
                  <div className="wallet-grid">
                    {WALLETS.map((w) =>
                <button key={w.id} className={`wallet-card ${selectedWallet === w.id ? 'on' : ''}`}
                onClick={() => setSelectedWallet(w.id)}>
                        <div className="wallet-card-ico" style={{ background: 'var(--col-surface-2)' }}>
                          <w.Logo />
                        </div>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div className="wallet-card-name">{w.name}</div>
                          <div className="wallet-card-hint">{w.hint}</div>
                        </div>
                        {selectedWallet === w.id &&
                  <IcoCheck size={14} color="var(--col-accent)" />
                  }
                      </button>
                )}
                  </div>

                  <div className="onb-actions">
                    <button className="btn btn-ghost btn-md" onClick={() => setStep(0)}>Back</button>
                    <button className="btn btn-primary btn-lg" style={{ gap: 8 }}
                disabled={!selectedWallet || connecting}
                onClick={connectWallet}>
                      {connecting ?
                  <><LoaderArc size="sm" /> Connecting…</> :
                  <>Connect wallet <IcoArrowRight size={15} color="white" /></>
                  }
                    </button>
                    <button className="btn btn-ghost btn-sm" style={{ color: 'var(--col-text-3)', marginLeft: 2 }}
                onClick={() => setStep(2)}>
                      Skip for now
                    </button>
                  </div>

                  {/* WalletConnect modal */}
                  {wcModalOpen &&
                  <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.52)', zIndex:300, display:'flex', alignItems:'center', justifyContent:'center' }}
                    onClick={() => setWcModalOpen(false)}>
                    <div style={{ background:'var(--col-surface)', borderRadius:20, padding:'28px 24px', width:340, boxShadow:'0 24px 64px rgba(0,0,0,0.22)', animation:'modalIn 200ms ease' }}
                      onClick={e => e.stopPropagation()}>
                      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:20 }}>
                        <div style={{ width:32, height:32, borderRadius:8, background:'rgba(59,153,252,0.12)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                          <svg width="18" height="13" viewBox="0 0 40 25" fill="none"><path d="M8.2 6.8C14.7.3 25.3.3 31.8 6.8L32.7 7.7C33 8 33 8.5 32.7 8.8L29.5 12C29.3 12.2 29 12.2 28.8 12L27.5 10.7C22.9 6.1 17.1 6.1 12.5 10.7L11.1 12.1C10.9 12.3 10.6 12.3 10.4 12.1L7.2 8.9C6.9 8.6 6.9 8.1 7.2 7.8L8.2 6.8ZM37.2 12.3L40 15.1C40.3 15.4 40.3 15.9 40 16.2L28.1 28.1C27.8 28.4 27.3 28.4 27 28.1L18.6 19.7C18.5 19.6 18.3 19.6 18.2 19.7L9.8 28.1C9.5 28.4 9 28.4 8.7 28.1L-3.2 16.2C-3.5 15.9-3.5 15.4-3.2 15.1L-0.4 12.3C-0.1 12 0.4 12 0.7 12.3L9.1 20.7C9.2 20.8 9.4 20.8 9.5 20.7L17.9 12.3C18.2 12 18.7 12 19 12.3L27.4 20.7C27.5 20.8 27.7 20.8 27.8 20.7L36.2 12.3C36.6 12 37.1 12 37.2 12.3Z" fill="#3B99FC" transform="translate(4,0) scale(0.82)"/></svg>
                        </div>
                        <div>
                          <div style={{ fontSize:15, fontWeight:600, color:'var(--col-text)' }}>WalletConnect</div>
                          <div style={{ fontSize:12, color:'var(--col-text-3)' }}>Choose your wallet app</div>
                        </div>
                        <button onClick={() => setWcModalOpen(false)} style={{ marginLeft:'auto', background:'none', border:'none', cursor:'pointer', color:'var(--col-text-3)', padding:4 }}>
                          <IcoX size={16} />
                        </button>
                      </div>
                      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                        {WC_WALLETS.map(w =>
                        <button key={w.id} onClick={() => connectViaWC(w.id)}
                          style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', border:'1.5px solid var(--col-border)', borderRadius:12, background:'var(--col-surface)', cursor:'pointer', fontFamily:'inherit', transition:'all 130ms', textAlign:'left' }}
                          onMouseEnter={e => { e.currentTarget.style.borderColor = w.color; e.currentTarget.style.background = w.bg; }}
                          onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--col-border)'; e.currentTarget.style.background = 'var(--col-surface)'; }}>
                          <div style={{ width:36, height:36, borderRadius:9, background:w.bg, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                            <w.Logo />
                          </div>
                          <span style={{ fontSize:14, fontWeight:500, color:'var(--col-text)' }}>{w.name}</span>
                          <IcoArrowRight size={13} color="var(--col-text-3)" style={{ marginLeft:'auto' }} />
                        </button>
                        )}
                      </div>
                    </div>
                  </div>
                  }
                </> :

            <>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 20px', background: 'var(--col-success-bg)', border: '1px solid var(--col-success-border)', borderRadius: 12, marginBottom: 8 }}>
                    <div className="wallet-card-ico" style={{ background: 'var(--col-surface-2)', width: 40, height: 40, borderRadius: 10 }}>
                      {selectedWallet === 'walletconnect' && wcWallet
                        ? (() => { const w = WC_WALLETS.find(x => x.id === wcWallet); return w ? <w.Logo /> : null; })()
                        : selWallet && <selWallet.Logo />
                      }
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--col-success)' }}>
                        {selectedWallet === 'walletconnect' && wcWallet
                          ? `${WC_WALLETS.find(x => x.id === wcWallet)?.name} connected via WalletConnect`
                          : `${selWallet?.name} connected`}
                      </div>
                      <div style={{ fontSize: 12, fontFamily: 'SF Mono, Fira Code, monospace', color: 'var(--col-success)', marginTop: 2, opacity: 0.7 }}>
                        0x3d2c9a4f…b1d7e
                      </div>
                    </div>
                    <IcoCheck size={18} color="var(--col-success)" />
                  </div>
                  <div className="onb-actions">
                    <button className="btn btn-primary btn-lg" style={{ gap: 8 }} onClick={() => setStep(2)}>
                      Continue <IcoArrowRight size={15} color="white" />
                    </button>
                  </div>
                </>
            }
            </>
          }

          {/* ── Step 2: Invite approvers ─────────────── */}
          {step === 2 &&
          <>
              <div className="onb-eyebrow">Step 2 of 3</div>
              <div className="onb-title">Invite your approvers</div>
              <div className="onb-desc">Add teammates who can co-sign payroll runs. You need at least one approver to meet a 2-of-2 threshold. You can always do this from Settings.</div>

              <div className="invite-row">
                <div className="form-group" style={{ flex: 1 }}>
                  <label className="form-label">Email address</label>
                  <input type="email" className="form-input" value={inviteEmail}
                onChange={(e) => setInviteEmail(e.target.value)}
                placeholder="colleague@company.com"
                onKeyDown={(e) => {if (e.key === 'Enter') {e.preventDefault();addInvitee();}}} />
                
                </div>
                <div className="form-group" style={{ width: 136 }}>
                  <label className="form-label">Role</label>
                  <select className="form-select" value={inviteRole}
                onChange={(e) => setInviteRole(e.target.value)}>
                    <option>Approver</option>
                    <option>Admin</option>
                    <option>Viewer</option>
                  </select>
                </div>
                <div className="form-group" style={{ justifyContent: 'flex-end' }}>
                  <button className="btn btn-secondary btn-md" style={{ height: 42, gap: 5 }}
                onClick={addInvitee} disabled={!inviteEmail.trim()}>
                    <IcoPlus size={13} /> Add
                  </button>
                </div>
              </div>

              {invitees.length > 0 &&
            <div className="invite-list" style={{ marginBottom: 4 }}>
                  {invitees.map((inv, i) =>
              <div key={i} className="invite-item">
                      <Avatar name={inv.email} size="sm" />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--col-text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                          {inv.email}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--col-text-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginTop: 1 }}>
                          {inv.role}
                        </div>
                      </div>
                      <span style={{ fontSize: 11, padding: '2px 7px', background: 'var(--col-accent-50)', color: 'var(--col-accent)', borderRadius: 4, fontWeight: 600, flexShrink: 0 }}>
                        Pending
                      </span>
                      <button className="btn btn-ghost btn-sm"
                style={{ padding: '0 6px', height: 28, color: 'var(--col-text-3)' }}
                onClick={() => setInvitees((prev) => prev.filter((_, j) => j !== i))}>
                        <IcoX size={12} />
                      </button>
                    </div>
              )}
                </div>
            }

              <div className="onb-actions">
                <button className="btn btn-ghost btn-md" onClick={() => setStep(1)}>Back</button>
                <button className="btn btn-primary btn-lg" style={{ gap: 8 }} onClick={() => setStep(3)}>
                  {invitees.length > 0 ?
                `Send ${invitees.length} invite${invitees.length > 1 ? 's' : ''} & continue` :
                'Continue'
                } <IcoArrowRight size={15} color="white" />
                </button>
                {invitees.length === 0 &&
              <button className="btn btn-ghost btn-sm"
              style={{ color: 'var(--col-text-3)' }}
              onClick={() => setStep(3)}>
                    Skip for now
                  </button>
              }
              </div>
            </>
          }

          {/* ── Step 3: All set ──────────────────────── */}
          {step === 3 &&
          <div style={{ textAlign: 'center' }}>
              <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
                <div className="onb-success-ico">
                  <IcoCheck size={28} color="var(--col-success)" />
                </div>
              </div>

              <div className="onb-title" style={{ textAlign: 'center' }}>You're all set!</div>
              <div className="onb-desc" style={{ textAlign: 'center', marginBottom: 28 }}>
                Your workspace is configured. Here's a summary of what was set up.
              </div>

              <div className="onb-check-list" style={{ maxWidth: 360, margin: '0 auto 32px', textAlign: 'left' }}>
                {[
              { done: true, label: 'Account created' },
              { done: walletConnected, label: walletConnected ? `${selWallet?.name} wallet connected` : 'Wallet — connect from Treasury later' },
              { done: invitees.length > 0, label: invitees.length > 0 ? `${invitees.length} team invite${invitees.length > 1 ? 's' : ''} sent` : 'Approvers — add from Settings later' }].
              map((item, i) =>
              <div key={i} className="onb-check-item">
                    <div className="onb-check-dot" style={{
                  background: item.done ? 'var(--col-success-bg)' : 'var(--col-surface-2)',
                  border: `1.5px solid ${item.done ? 'var(--col-success-border)' : 'var(--col-border-s)'}`
                }}>
                      {item.done ?
                  <IcoCheck size={11} color="var(--col-success)" /> :
                  <span style={{ fontSize: 9, color: 'var(--col-text-3)', fontWeight: 600 }}>{i + 1}</span>
                  }
                    </div>
                    <span style={{ color: item.done ? 'var(--col-text)' : 'var(--col-text-3)' }}>{item.label}</span>
                  </div>
              )}
              </div>

              <button className="btn btn-primary btn-lg" style={{ gap: 8, padding: '0 36px' }}
            onClick={onComplete}>
                Go to Dashboard <IcoArrowRight size={15} color="white" />
              </button>
            </div>
          }

        </div>
      </div>
    </div>);

};

Object.assign(window, { LoginScreen, RegisterScreen, OnboardingScreen });