// Profile, settings, password/2FA, promotions
function Profile() {
  const { go, user, logout, desktop, setView } = useApp();
  const country = COUNTRIES.find(c => c.c === user.country);
  return (
    <div className={desktop ? "desktop-screen-inner" : "screen with-tabs page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Profile" large right={<ThemeToggle />} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <div className="card row" style={{ gap: 14, padding: 18 }}>
          <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'linear-gradient(135deg, var(--green), var(--cyan))', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#0A0B0D', fontWeight: 700, fontSize: 20 }}>
            {user.name.split(' ').map(s => s[0]).slice(0,2).join('')}
          </div>
          <div className="col" style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 17, fontWeight: 600 }}>{user.name}</div>
            <div style={{ fontSize: 12, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.email}</div>
            <div className="row" style={{ gap: 6, marginTop: 6 }}>
              <span className="pill pill-green">Verified</span>
              <span className="pill mono">{country?.c}</span>
            </div>
          </div>
        </div>

        <div style={{ marginTop: 22 }}>
          <SectionHead label="Account" />
          <ListGroup>
            <ListItem icon="user" title="Personal info" sub={user.name} onClick={() => go('settings')} />
            <ListItem icon="shield" title="Security" sub="Password · 2FA" onClick={() => go('security')} />
            <ListItem icon="globe" title="Region" sub={country?.n} />
            <ListItem icon="cube" title="Trading accounts" sub="3 active" onClick={() => go('accounts')} last />
          </ListGroup>
        </div>

        <div style={{ marginTop: 22 }}>
          <SectionHead label="Rewards" />
          <ListGroup>
            <ListItem icon="gift" title="Promotions" sub="2 active offers" onClick={() => go('promotions')} />
            <ListItem icon="star" title="Refer a friend" sub="Earn $50 per signup" last />
          </ListGroup>
        </div>

        <div style={{ marginTop: 22 }}>
          <SectionHead label="Support" />
          <ListGroup>
            <ListItem icon="info" title="Help center" />
            <ListItem icon="mail" title="Contact us" sub="support@aitrader.io" last />
          </ListGroup>
        </div>

        <button className="btn btn-secondary" onClick={() => { logout(); go('splash'); }} style={{ marginTop: 24 }}>
          <I.logout size={18}/> Sign out
        </button>
        <div style={{ textAlign: 'center', fontSize: 11, color: 'var(--text-faint)', marginTop: 18 }} className="mono">
          AITrader v1.0 · Build 2026.5.7
        </div>
      </div>
      {!desktop && <TabBar />}
    </div>
  );
}

function SectionHead({ label }) {
  return <div style={{ fontSize: 11, color: 'var(--text-dim)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, margin: '0 4px 8px' }}>{label}</div>;
}

function ListGroup({ children }) {
  return <div className="card" style={{ padding: 4 }}>{children}</div>;
}

function ListItem({ icon, title, sub, onClick, last, right }) {
  return (
    <div onClick={onClick} className="row between" style={{
      padding: 14, cursor: onClick ? 'pointer' : 'default',
      borderBottom: last ? 'none' : '1px solid var(--line-2)'
    }}>
      <div className="row" style={{ gap: 12 }}>
        <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--card-2)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-dim)' }}>
          {I[icon]({ size: 18 })}
        </div>
        <div className="col">
          <div style={{ fontSize: 14, fontWeight: 500 }}>{title}</div>
          {sub && <div style={{ fontSize: 12, color: 'var(--text-dim)' }}>{sub}</div>}
        </div>
      </div>
      {right || (onClick && <I.chevR size={16} />)}
    </div>
  );
}

function Settings() {
  const { go, user, updateUser, toast, desktop } = useApp();
  const [name, setName] = useState(user.name);
  const [email, setEmail] = useState(user.email);
  const [phone, setPhone] = useState('+44 7700 900123');

  const save = () => {
    updateUser({ name, email });
    toast('Profile updated');
    go('profile');
  };

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Personal info" onBack={() => go('profile')} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <div className="input-group" style={{ marginBottom: 16 }}>
          <label className="input-label">Full name</label>
          <input className="input" value={name} onChange={e => setName(e.target.value)} />
        </div>
        <div className="input-group" style={{ marginBottom: 16 }}>
          <label className="input-label">Email</label>
          <input className="input" type="email" value={email} onChange={e => setEmail(e.target.value)} />
        </div>
        <div className="input-group" style={{ marginBottom: 16 }}>
          <label className="input-label">Phone</label>
          <input className="input mono" type="tel" value={phone} onChange={e => setPhone(e.target.value)} />
        </div>
        <div className="input-group">
          <label className="input-label">Country</label>
          <input className="input" value={COUNTRIES.find(c => c.c === user.country)?.n} disabled style={{ opacity: 0.6 }} />
          <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 6 }}>Contact support to change region.</div>
        </div>
        <button className="btn btn-primary" onClick={save} style={{ marginTop: 24 }}>Save changes</button>
      </div>
    </div>
  );
}

function Security() {
  const { go, toast, desktop } = useApp();
  const [twoFA, setTwoFA] = useState(false);
  const [showPwModal, setShowPwModal] = useState(false);

  return (
    <div className={desktop ? "desktop-screen-inner" : "screen page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Security" onBack={() => go('profile')} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <ListGroup>
          <ListItem icon="lock" title="Change password" sub="Last changed 32 days ago" onClick={() => setShowPwModal(true)} />
          <ListItem icon="shield" title="Two-factor auth" sub={twoFA ? 'Enabled · Authenticator app' : 'Recommended'}
            right={<Switch on={twoFA} onChange={() => { setTwoFA(t => !t); toast(twoFA ? '2FA disabled' : '2FA enabled'); }} />} last />
        </ListGroup>

        <div style={{ marginTop: 22 }}>
          <SectionHead label="Session" />
          <ListGroup>
            <ListItem icon="phone" title="iPhone 15 Pro" sub="London · This device" right={<span className="pill pill-green">Active</span>} />
            <ListItem icon="globe" title="Chrome / macOS" sub="London · 2 days ago" last />
          </ListGroup>
        </div>

        <div style={{ marginTop: 22 }}>
          <SectionHead label="Login history" />
          <div className="card" style={{ padding: 4 }}>
            {[
              ['Today, 09:41', 'iPhone · London', 'success'],
              ['Yesterday, 18:22', 'Chrome · London', 'success'],
              ['May 5, 14:08', 'iPhone · London', 'success'],
              ['May 3, 02:14', 'Unknown · Lagos', 'blocked'],
            ].map((r, i, arr) => (
              <div key={i} className="between" style={{ padding: 12, borderBottom: i === arr.length - 1 ? 'none' : '1px solid var(--line-2)' }}>
                <div className="col">
                  <div style={{ fontSize: 13 }}>{r[1]}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-dim)' }} className="mono">{r[0]}</div>
                </div>
                <span className={'pill ' + (r[2] === 'blocked' ? 'pill-red' : 'pill-green')}>{r[2] === 'blocked' ? 'Blocked' : 'OK'}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {showPwModal && (
        <div className="modal-bg" onClick={() => setShowPwModal(false)}>
          <div className="sheet" onClick={e => e.stopPropagation()}>
            <div className="sheet-handle"></div>
            <h3 style={{ margin: '0 0 18px', fontSize: 22 }}>Change password</h3>
            <div className="stack" style={{ gap: 14 }}>
              <div className="input-group">
                <label className="input-label">Current password</label>
                <input className="input" type="password" placeholder="••••••••" />
              </div>
              <div className="input-group">
                <label className="input-label">New password</label>
                <input className="input" type="password" placeholder="At least 8 characters" />
              </div>
              <div className="input-group">
                <label className="input-label">Confirm new</label>
                <input className="input" type="password" placeholder="Repeat new password" />
              </div>
              <button className="btn btn-primary" onClick={() => { setShowPwModal(false); toast('Password changed'); }} style={{ marginTop: 8 }}>Update password</button>
              <button className="btn btn-ghost" onClick={() => setShowPwModal(false)}>Cancel</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function Switch({ on, onChange }) {
  return (
    <button onClick={(e) => { e.stopPropagation(); onChange(); }} style={{
      width: 44, height: 26, borderRadius: 13, border: 'none',
      background: on ? 'var(--green)' : 'var(--card-2)',
      position: 'relative', cursor: 'pointer', transition: 'background 0.15s'
    }}>
      <div style={{
        width: 22, height: 22, borderRadius: '50%', background: '#fff',
        position: 'absolute', top: 2, left: on ? 20 : 2,
        transition: 'left 0.15s', boxShadow: '0 2px 4px rgba(0,0,0,0.2)'
      }}/>
    </button>
  );
}

function Promotions() {
  const { go, toast, desktop } = useApp();
  const promos = [
    { id: 'p1', title: '100% Deposit Bonus', desc: 'Up to $5,000. Trade with double the firepower.', tag: 'Featured', tagColor: 'green', cta: 'Claim bonus', expires: 'May 31, 2026' },
    { id: 'p2', title: 'Crypto Cashback', desc: '5% cashback on every BTC, ETH or USDT deposit this month.', tag: 'New', tagColor: 'cyan', cta: 'Activate', expires: 'May 31, 2026' },
    { id: 'p3', title: 'Refer & earn $50', desc: 'Per friend who funds with $200+. Unlimited referrals.', tag: 'Always on', tagColor: 'amber', cta: 'Get my link', expires: 'No expiry' },
    { id: 'p4', title: 'Zero-spread weekend', desc: 'Trade BTC/USD with 0.0 spread, Saturday & Sunday.', tag: 'Weekend', tagColor: 'magenta', cta: 'Set reminder', expires: 'Sat – Sun' },
  ];
  return (
    <div className={desktop ? "desktop-screen-inner" : "screen with-tabs page-enter"}>
      {!desktop && <><StatusBar /><AppBar title="Promotions" large onBack={() => go('dashboard')} /></>}
      <div style={{ padding: '0 20px 30px' }}>
        <div className="card" style={{
          background: 'linear-gradient(135deg, rgba(166,255,61,0.16), rgba(255,77,210,0.12))',
          padding: 22, position: 'relative', overflow: 'hidden', borderColor: 'transparent'
        }}>
          <div style={{ position: 'absolute', top: -50, right: -50, width: 180, height: 180, borderRadius: '50%', background: 'radial-gradient(circle, rgba(166,255,61,0.3), transparent 70%)' }}></div>
          <span className="pill pill-green" style={{ position: 'relative' }}>Limited time</span>
          <h2 style={{ fontSize: 22, fontWeight: 700, margin: '10px 0 6px', letterSpacing: '-0.02em', position: 'relative' }}>2× your first deposit</h2>
          <p style={{ fontSize: 13, color: 'var(--text-dim)', margin: 0, position: 'relative', maxWidth: 250 }}>Deposit $500+ in crypto and we'll match it 1:1 as bonus margin.</p>
          <button className="btn btn-primary btn-sm" onClick={() => go('deposit')} style={{ marginTop: 14, width: 'auto', padding: '0 18px', position: 'relative' }}>
            Deposit now <I.chevR size={14} />
          </button>
        </div>

        <div className="stack" style={{ gap: 12, marginTop: 18 }}>
          {promos.map(p => (
            <div key={p.id} className="card">
              <div className="between">
                <span className={'pill pill-' + (p.tagColor === 'green' ? 'green' : p.tagColor === 'amber' ? 'amber' : 'demo')}>{p.tag}</span>
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{p.expires}</span>
              </div>
              <div style={{ fontSize: 16, fontWeight: 600, marginTop: 10 }}>{p.title}</div>
              <div style={{ fontSize: 13, color: 'var(--text-dim)', marginTop: 4, lineHeight: 1.5 }}>{p.desc}</div>
              <button className="btn btn-secondary btn-sm" onClick={() => toast(p.cta + ' — done')} style={{ marginTop: 14 }}>{p.cta}</button>
            </div>
          ))}
        </div>
      </div>
      {!desktop && <TabBar />}
    </div>
  );
}

window.Profile = Profile;
window.Settings = Settings;
window.Security = Security;
window.Promotions = Promotions;
window.SectionHead = SectionHead;
window.ListGroup = ListGroup;
window.ListItem = ListItem;
