<?php
$userId = $auth->requireAuth();

$profile = $db->selectById('user_profiles', $userId, 'user_id');
if ($profile && $profile['onboarding_complete']) {
    header('Location: /traderalign/dashboard');
    exit;
}

$step = (int)($_GET['step'] ?? 1);
$error = $_GET['error'] ?? '';

// Step 3 used to be rendered inline here (plain dead-end links that wrote
// nothing — journey_type/workflow_state/onboarding_complete were never
// set). /onboarding-stage3 is the real, working step 3 — redirect stale
// bookmarks/links there instead of maintaining two competing copies.
if ($step === 3) {
    header('Location: /traderalign/onboarding-stage3');
    exit;
}

// Get user name for greeting
$userName = htmlspecialchars($profile['display_name'] ?? 'Trader');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome - TraderAlign</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/traderalign/assets/tokens.css">
<link rel="icon" type="image/png" sizes="32x32" href="/traderalign/assets/favicon/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/traderalign/assets/favicon/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/traderalign/assets/favicon/apple-touch-icon.png">
    <link rel="shortcut icon" href="/traderalign/assets/favicon/favicon.ico">
<link rel="stylesheet" href="/traderalign/assets/css/brand.css">
<style>
.onboard-page{min-height:100vh;display:flex;align-items:center;justify-content:center;padding:2rem;background:var(--background)}
.onboard-card{width:100%;max-width:36rem;background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:2.5rem}
.onboard-card h1{font-size:1.5rem;font-weight:700;color:var(--foreground);margin-bottom:.25rem}
.onboard-card .sub{color:var(--foreground-muted);font-size:.9rem;margin-bottom:2rem;line-height:1.5}
.steps{display:flex;gap:.5rem;margin-bottom:2rem}
.step-dot{flex:1;height:4px;background:var(--border);border-radius:2px;transition:background var(--t)}
.step-dot.active{background:var(--primary)}
.step-dot.done{background:var(--positive)}
.form-group{margin-bottom:1.25rem}
.form-group label{display:block;font-size:.875rem;font-weight:500;color:var(--foreground);margin-bottom:.375rem}
.form-group select,.form-group input{width:100%;height:2.75rem;padding:0 .875rem;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--foreground);font-family:inherit;font-size:.95rem;transition:border-color var(--t-fast)}
.form-group select:focus,.form-group input:focus{outline:none;border-color:var(--ring)}
.form-group select{appearance:none;cursor:pointer}
.form-group .hint{font-size:.8rem;color:var(--foreground-dim);margin-top:.25rem;line-height:1.4}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
.btn-row{display:flex;gap:1rem;justify-content:flex-end;margin-top:2rem}
.error-msg{background:color-mix(in srgb,var(--negative) 15%,transparent);border:1px solid var(--negative);color:var(--negative);padding:.75rem 1rem;border-radius:var(--radius-md);font-size:.875rem;margin-bottom:1.5rem}
.radio-group{display:flex;flex-direction:column;gap:.5rem}
.radio-option{display:flex;align-items:center;gap:.75rem;padding:.75rem 1rem;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);cursor:pointer;transition:all var(--t-fast)}
.radio-option:hover{border-color:var(--primary)}
.radio-option input[type=radio]{accent-color:var(--primary);width:1rem;height:1rem}
.radio-option .ro-text{font-size:.9rem;color:var(--foreground)}
.radio-option .ro-sub{font-size:.75rem;color:var(--foreground-dim)}

/* Chip picker for multi-select */
.chip-picker{display:flex;flex-wrap:wrap;gap:.4rem;margin-top:.25rem}
.chip-pick{padding:.4rem .85rem;border-radius:var(--radius-full);font-size:.8rem;font-weight:500;color:var(--foreground-dim);border:1px solid var(--border);background:var(--background-surface);cursor:pointer;transition:all .15s;font-family:inherit}
.chip-pick:hover{color:var(--foreground);border-color:var(--primary)}
.chip-pick.selected{background:color-mix(in srgb,var(--primary) 15%,transparent);color:var(--primary);border-color:var(--primary)}

/* ── Step 3 Journey Cards ─────────────────────────── */
.step3-wide{max-width:52rem}
.journey-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:.75rem;margin-bottom:1.5rem}
.journey-card{background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:1.25rem;cursor:pointer;transition:all .2s ease;position:relative;text-decoration:none;color:inherit;display:block}
.journey-card:hover{border-color:color-mix(in srgb,var(--primary) 30%,transparent);transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.12)}
.journey-card .card-icon{font-size:1.5rem;margin-bottom:.5rem;display:block}
.journey-card .card-title{font-size:.9rem;font-weight:700;color:var(--foreground);margin-bottom:.35rem;line-height:1.3}
.journey-card .card-desc{font-size:.75rem;color:var(--foreground-dim);line-height:1.5;margin-bottom:.5rem}
.journey-card .card-features{list-style:none;padding:0;display:flex;flex-direction:column;gap:.2rem}
.journey-card .card-features li{font-size:.7rem;color:var(--foreground-muted);display:flex;align-items:center;gap:.3rem}
.journey-card .card-features li::before{content:'✓';color:var(--positive);font-weight:700;font-size:.65rem}

.btn-back{display:inline-flex;align-items:center;gap:.35rem;padding:.7rem 1.25rem;border-radius:var(--radius-lg);font-size:.85rem;font-weight:500;color:var(--foreground-dim);background:transparent;border:1px solid var(--border);cursor:pointer;text-decoration:none;font-family:var(--font-sans);transition:all .2s}
.btn-back:hover{border-color:var(--foreground-dim);color:var(--foreground)}

@media(max-width:768px){
  .onboard-page{padding:1rem}
  .onboard-card{padding:1.5rem}
  .journey-grid{grid-template-columns:1fr}
  .step3-wide{max-width:100%}
  .form-row{grid-template-columns:1fr}
}
.auth-brand{display:flex;justify-content:center;margin-bottom:1.75rem}
</style>
</head>
<body class="onboard-page">
<div class="onboard-card <?= $step === 3 ? 'step3-wide' : '' ?>">
    <div class="auth-brand"><a href="/traderalign/"><img src="/traderalign/images/logo.png" alt="TraderAlign" class="ta-logo ta-logo--xl"></a></div>
    <?php if ($step === 1): ?>
    <h1>Let's understand your journey</h1>
    <p class="sub">Every trader comes from somewhere. Help us understand where you are right now: the challenges, the experience, the goals. This becomes your baseline.</p>
    <?php elseif ($step === 2): ?>
    <h1>How are you showing up right now?</h1>
    <p class="sub">Be honest. There's no wrong answer. The more accurately you describe your current state, the better TraderAlign can track your growth over time.</p>
    <?php else: ?>
    <h1>Welcome, <?= $userName ?> 👋</h1>
    <p class="sub">Where are you on your trading journey? Choose the path that best describes your current situation, and we'll tailor TraderAlign to support you.</p>
    <?php endif; ?>

    <p class="sub" style="font-size:.8rem">Step <?= $step ?> of 3</p>
    <div class="steps">
        <div class="step-dot <?= $step >= 1 ? 'done' : '' ?>"></div>
        <div class="step-dot <?= $step >= 2 ? 'done' : '' ?>"></div>
        <div class="step-dot <?= $step >= 3 ? 'active' : '' ?>"></div>
    </div>

    <?php if ($error): ?>
    <div class="error-msg"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($step === 1): ?>
    <form method="POST" action="/traderalign/api/onboarding/step1">
        <?= Csrf::field() ?>
        <div class="form-group"><label>How long have you been trading?</label><select name="trading_experience" required><option value="">Select...</option><option value="less_than_6mo">Less than 6 months</option><option value="6_to_18mo">6 to 18 months</option><option value="18mo_to_5y">18 months to 5 years</option><option value="5y_plus">5+ years</option></select></div>
        <div class="form-group"><label>What kind of trader are you?</label><select name="trader_type" required><option value="">Select...</option><option value="scalper">Scalper</option><option value="day_trader">Day Trader</option><option value="swing">Swing</option><option value="position">Position</option><option value="funded_challenger">Funded Account Challenger</option><option value="funded_holder">Funded Account Holder</option><option value="investor">Investor</option><option value="beginner">Beginner</option></select></div>
        <div class="form-group"><label>Have you been journaling your trades?</label><select name="journaling" required><option value="">Select...</option><option value="never">Never: this is my first time</option><option value="inconsistently">I've tried but couldn't stay consistent</option><option value="regularly">Yes, I journal regularly</option><option value="another_tool">I use another tool but want more</option></select></div>
        <div class="form-group"><label>What's your biggest challenge right now?</label><select name="biggest_challenge" required><option value="">Select...</option><option value="discipline">Sticking to my trading plan</option><option value="overtrading">Overtrading / revenge trading</option><option value="consistency">Inconsistent results</option><option value="risk_management">Managing risk properly</option><option value="journaling">Keeping a consistent journal</option><option value="funded_pressure">Handling prop firm pressure</option><option value="confidence">Confidence after losses</option><option value="other">Something else</option></select></div>
        <div class="form-group"><label>What are you hoping TraderAlign will help you achieve?</label><input type="text" name="goal" placeholder="e.g. Build consistency, pass my prop firm challenge, understand my patterns"></div>
        <div class="btn-row"><button type="submit" class="btn btn-primary btn-lg">Continue →</button></div>
    </form>

    <?php elseif ($step === 2): ?>
    <form method="POST" action="/traderalign/api/onboarding/step2" id="step2-form">
        <?= Csrf::field() ?>
        <div class="form-group">
            <label>Preferred Username</label>
            <input type="text" name="preferred_username" required maxlength="40" placeholder="Enter your preferred username" value="<?= htmlspecialchars($_GET['preferred_username'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>How would you rate your trading discipline?</label>
            <select name="discipline_rating" required>
                <option value="">Select...</option>
                <option value="1">1: I frequently deviate from my plan</option>
                <option value="2">2: I struggle more often than I'd like</option>
                <option value="3">3: About half the time I stick to it</option>
                <option value="4">4: I mostly follow my plan</option>
                <option value="5">5: I'm highly disciplined</option>
            </select>
        </div>
        <div class="form-group">
            <label>How often do you deviate from your trading plan?</label>
            <select name="deviation_frequency" required>
                <option value="">Select...</option>
                <option value="rarely">Rarely: I'm fairly consistent</option>
                <option value="sometimes">Sometimes: a few times a week</option>
                <option value="often">Often: most sessions</option>
                <option value="always">I don't really have a fixed plan</option>
            </select>
        </div>
        <div class="form-group">
            <label>What emotions most affect your trading?</label>
            <select name="dominant_emotion" required>
                <option value="">Select...</option>
                <option value="fear">Fear of losing</option>
                <option value="greed">Greed / FOMO</option>
                <option value="frustration">Frustration after losses</option>
                <option value="overconfidence">Overconfidence after wins</option>
                <option value="anxiety">Anxiety about entering trades</option>
                <option value="impatience">Impatience: entering too early</option>
                <option value="none">I manage my emotions well</option>
            </select>
        </div>
        <div class="form-group">
            <label>What is your primary broker?</label>
            <input type="text" name="primary_broker" required placeholder="e.g. FTMO, OANDA, IC Markets">
            <div class="hint">The broker or prop firm you trade with most often.</div>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>What is your base currency?</label>
                <select name="base_currency" required>
                    <option value="USD" selected>USD</option>
                    <option value="EUR">EUR</option>
                    <option value="GBP">GBP</option>
                    <option value="JPY">JPY</option>
                    <option value="AUD">AUD</option>
                    <option value="CAD">CAD</option>
                    <option value="CHF">CHF</option>
                    <option value="NZD">NZD</option>
                </select>
            </div>
            <div class="form-group">
                <label>What is your timezone?</label>
                <select name="timezone" required>
                    <option value="UTC">UTC</option>
                    <option value="Africa/Nairobi">Africa/Nairobi (EAT, UTC+3)</option>
                    <option value="Europe/London">Europe/London (GMT/BST)</option>
                    <option value="Europe/Berlin">Europe/Berlin (CET/CEST)</option>
                    <option value="America/New_York">America/New York (EST/EDT)</option>
                    <option value="America/Chicago">America/Chicago (CST/CDT)</option>
                    <option value="America/Denver">America/Denver (MST/MDT)</option>
                    <option value="America/Los_Angeles">America/Los Angeles (PST/PDT)</option>
                    <option value="Asia/Tokyo">Asia/Tokyo (JST)</option>
                    <option value="Asia/Singapore">Asia/Singapore (SGT)</option>
                    <option value="Asia/Dubai">Asia/Dubai (GST)</option>
                    <option value="Australia/Sydney">Australia/Sydney (AEST/AEDT)</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label>What trading platforms do you use?</label>
            <div class="chip-picker" id="platforms-picker">
                <button type="button" class="chip-pick" data-value="MT4" onclick="toggleChip(this)">MT4</button>
                <button type="button" class="chip-pick" data-value="MT5" onclick="toggleChip(this)">MT5</button>
                <button type="button" class="chip-pick" data-value="cTrader" onclick="toggleChip(this)">cTrader</button>
                <button type="button" class="chip-pick" data-value="TradingView" onclick="toggleChip(this)">TradingView</button>
                <button type="button" class="chip-pick" data-value="Other" onclick="toggleChip(this)">Other</button>
            </div>
            <div class="hint">Select all platforms you actively use.</div>
        </div>
        <div class="form-group">
            <label>What markets do you trade?</label>
            <div class="chip-picker" id="markets-picker">
                <button type="button" class="chip-pick" data-value="Forex" onclick="toggleChip(this)">Forex</button>
                <button type="button" class="chip-pick" data-value="Indices" onclick="toggleChip(this)">Indices</button>
                <button type="button" class="chip-pick" data-value="Commodities" onclick="toggleChip(this)">Commodities</button>
                <button type="button" class="chip-pick" data-value="Crypto" onclick="toggleChip(this)">Crypto</button>
                <button type="button" class="chip-pick" data-value="Stocks" onclick="toggleChip(this)">Stocks</button>
            </div>
            <div class="hint">Select all markets you actively trade.</div>
        </div>
        <div class="btn-row">
            <a href="/traderalign/onboarding?step=1" class="btn btn-outline btn-lg">← Back</a>
            <button type="submit" class="btn btn-primary btn-lg">Continue →</button>
        </div>
    </form>

    <?php else: ?>
    <!-- Step 3: Journey Selection -->
    <div class="journey-grid">
        <!-- Card 1: Already Have an Edge -->
        <a href="/traderalign/trading-center" class="journey-card">
            <span class="card-icon">📈</span>
            <h3 class="card-title">I Already Have a Trading Edge</h3>
            <p class="card-desc">You have a proven strategy and consistent results. Jump right into tracking, journaling, and optimizing your performance.</p>
            <ul class="card-features">
                <li>Track live performance</li>
                <li>Advanced journaling</li>
                <li>Strategy optimization</li>
            </ul>
        </a>

        <!-- Card 2: Developing an Edge -->
        <a href="/traderalign/strategy-validation" class="journey-card">
            <span class="card-icon">🔬</span>
            <h3 class="card-title">I'm Developing a Trading Edge</h3>
            <p class="card-desc">You're actively working on your strategy and testing ideas. Use our validation tools to build and refine your edge systematically.</p>
            <ul class="card-features">
                <li>Strategy builder</li>
                <li>Backtesting suite</li>
                <li>Validation tracking</li>
            </ul>
        </a>

        <!-- Card 3: Don't Have an Edge Yet -->
        <a href="/traderalign/learning-center" class="journey-card">
            <span class="card-icon">📚</span>
            <h3 class="card-title">I Don't Yet Have a Trading Edge</h3>
            <p class="card-desc">You're new to trading or still learning the fundamentals. Start with our educational resources to build a strong foundation.</p>
            <ul class="card-features">
                <li>Trading fundamentals</li>
                <li>Structured learning paths</li>
                <li>Community support</li>
            </ul>
        </a>
    </div>

    <div class="btn-row" style="justify-content:flex-start">
        <a href="/traderalign/onboarding?step=2" class="btn-back">← Back</a>
    </div>
    <?php endif; ?>
</div>

<script>
<?php if ($step === 2): ?>
// Chip picker toggle
function toggleChip(btn) {
    btn.classList.toggle('selected');
    updateChipHiddenInputs();
}

function updateChipHiddenInputs() {
    // Platforms
    document.querySelectorAll('.platform-hidden-input').forEach(function(el) { el.remove(); });
    document.querySelectorAll('#platforms-picker .chip-pick.selected').forEach(function(el) {
        var input = document.createElement('input');
        input.type = 'hidden'; input.name = 'platforms[]'; input.value = el.dataset.value;
        input.className = 'platform-hidden-input';
        document.getElementById('step2-form').appendChild(input);
    });
    // Markets
    document.querySelectorAll('.market-hidden-input').forEach(function(el) { el.remove(); });
    document.querySelectorAll('#markets-picker .chip-pick.selected').forEach(function(el) {
        var input = document.createElement('input');
        input.type = 'hidden'; input.name = 'markets[]'; input.value = el.dataset.value;
        input.className = 'market-hidden-input';
        document.getElementById('step2-form').appendChild(input);
    });
}

// Update hidden inputs on form submit
document.getElementById('step2-form').addEventListener('submit', function() {
    updateChipHiddenInputs();
});
<?php endif; ?>
</script>

</body>
</html>