<?php
/**
 * Signup View — Helmyx Auth Page
 */
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Your Organization — Helmyx</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=Montserrat:wght@600;700&family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="icon" type="image/png" sizes="32x32" href="<?= defined('APP_URL') ? APP_URL : '' ?>/assets/brand/favicon/helmyx-icon-32.png">
    <link rel="stylesheet" href="<?= defined('APP_URL') ? APP_URL : '' ?>/assets/css/hx-tokens.css">
    <link rel="stylesheet" href="<?= defined('APP_URL') ? APP_URL : '' ?>/assets/css/style.css">
    <link rel="stylesheet" href="<?= defined('APP_URL') ? APP_URL : '' ?>/assets/css/auth.css">
    <style>
        .password-wrapper { position: relative; }
        .password-toggle { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: var(--text-muted); padding: 0; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .field-hint { font-size: 0.75rem; color: var(--text-muted); margin-top: 4px; }
        .section-label { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-muted); margin: 24px 0 12px; }
        .section-label:first-of-type { margin-top: 0; }
        @media (max-width: 480px) { .form-row { grid-template-columns: 1fr; } }
        .searchable-select { position: relative; }
        .searchable-select-dropdown { position: absolute; top: calc(100% + 4px); left: 0; right: 0; background: #fff; border: 1px solid var(--border-color); border-radius: 8px; box-shadow: 0 8px 24px rgba(0,0,0,0.08); max-height: 220px; overflow-y: auto; z-index: 20; display: none; }
        .searchable-select-dropdown.open { display: block; }
        .searchable-select-option { padding: 8px 12px 8px 20px; cursor: pointer; font-size: 0.87rem; color: var(--text-primary); }
        .searchable-select-option:hover, .searchable-select-option.active { background: rgba(10,58,107,0.08); color: var(--primary); }
        .searchable-select-option.no-results { color: var(--text-muted); cursor: default; padding-left: 12px; }
        .searchable-select-option.no-results:hover { background: none; }
        .searchable-select-group-label { padding: 8px 12px 4px; font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.04em; color: var(--text-muted); background: var(--page-bg); }
        .searchable-select-group-label:not(:first-child) { margin-top: 2px; border-top: 1px solid var(--border-color); }
    </style>
</head>
<body class="auth-body">

<div class="auth-wrapper">
    <div class="auth-shapes">
        <div class="shape shape-1"></div>
        <div class="shape shape-2"></div>
        <div class="shape shape-3"></div>
        <div class="shape shape-4"></div>
    </div>

    <div class="auth-card" style="max-width:520px;">
        <div class="auth-logo">
            <img src="<?= APP_URL ?>/assets/brand/logo/helmyx-horizontal.svg" alt="Helmyx — Steer. Plan. Deliver." style="height:46px;">
        </div>

        <h1 class="auth-title">Create your organization</h1>
        <p class="auth-subtitle">Sign up to get started — your 7-day free trial begins immediately, no waiting and no card required.</p>

        <?php if (!empty($_SESSION['flash'])): ?>
            <?php foreach ($_SESSION['flash'] as $type => $message): ?>
                <div class="alert alert-<?= htmlspecialchars($type) ?>" style="margin-bottom:16px;">
                    <span><?= htmlspecialchars($message) ?></span>
                    <button class="alert-dismiss" onclick="this.parentElement.remove()">&times;</button>
                </div>
            <?php endforeach; unset($_SESSION['flash']); ?>
        <?php endif; ?>

        <?php $old = $old ?? []; ?>
        <form method="POST" action="<?= APP_URL ?>/signup" id="signupForm" novalidate>
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">

            <div class="section-label">Organization</div>

            <div class="form-group">
                <label class="form-label" for="org_name">Organization Name *</label>
                <input type="text" id="org_name" name="org_name" class="form-control" placeholder="Acme Construction Ltd" required value="<?= htmlspecialchars($old['org_name'] ?? '') ?>">
            </div>

            <div class="form-group">
                <label class="form-label" for="industry_search">Industry</label>
                <div class="searchable-select" id="industrySelect">
                    <input type="text" id="industry_search" class="form-control" placeholder="Search industry…" autocomplete="off" value="<?= htmlspecialchars($old['industry'] ?? '') ?>">
                    <input type="hidden" id="industry" name="industry" value="<?= htmlspecialchars($old['industry'] ?? '') ?>">
                    <div class="searchable-select-dropdown" id="industry_dropdown">
                        <?php foreach (getIndustryGroups() as $sector => $subIndustries): ?>
                            <?php if (empty($subIndustries)): ?>
                                <div class="searchable-select-option" data-value="<?= htmlspecialchars($sector) ?>" data-group=""><?= htmlspecialchars($sector) ?></div>
                            <?php else: ?>
                                <div class="searchable-select-group-label" data-group="<?= htmlspecialchars($sector) ?>"><?= htmlspecialchars($sector) ?></div>
                                <?php foreach ($subIndustries as $sub): ?>
                                    <div class="searchable-select-option" data-value="<?= htmlspecialchars($sub) ?>" data-group="<?= htmlspecialchars($sector) ?>"><?= htmlspecialchars($sub) ?></div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="section-label">Your Details</div>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label" for="first_name">First Name *</label>
                    <input type="text" id="first_name" name="first_name" class="form-control" required value="<?= htmlspecialchars($old['first_name'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label class="form-label" for="last_name">Last Name *</label>
                    <input type="text" id="last_name" name="last_name" class="form-control" required value="<?= htmlspecialchars($old['last_name'] ?? '') ?>">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label" for="email">Work Email *</label>
                <input type="email" id="email" name="email" class="form-control" placeholder="you@company.com" autocomplete="email" required value="<?= htmlspecialchars($old['email'] ?? '') ?>">
            </div>

            <div class="form-group">
                <label class="form-label" for="phone">Phone</label>
                <input type="text" id="phone" name="phone" class="form-control" value="<?= htmlspecialchars($old['phone'] ?? '') ?>">
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label class="form-label" for="password">Password *</label>
                    <div class="password-wrapper input-group">
                        <input type="password" id="password" name="password" class="form-control" placeholder="Create a password" autocomplete="new-password" required style="padding-right:44px;">
                        <button type="button" class="password-toggle" onclick="togglePassword('password')" title="Show/hide password">👁</button>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="password_confirm">Confirm Password *</label>
                    <input type="password" id="password_confirm" name="password_confirm" class="form-control" placeholder="Repeat password" autocomplete="new-password" required>
                </div>
            </div>
            <p class="field-hint">Must be at least 8 characters, with uppercase, lowercase, a number and a special character.</p>

            <button type="submit" class="btn btn-primary w-full btn-lg" style="justify-content:center;margin-top:20px;" id="signupBtn">
                <span id="signupBtnText">Create Organization</span>
                <span id="signupSpinner" class="spinner spinner-sm" style="display:none;border-color:rgba(255,255,255,0.3);border-top-color:white;"></span>
            </button>
        </form>

        <p style="text-align:center;margin-top:24px;font-size:0.85rem;">
            Already have an account? <a href="<?= APP_URL ?>/login" style="color:var(--primary);text-decoration:none;font-weight:600;">Sign in</a>
        </p>
    </div>
</div>

<script>
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    input.type = input.type === 'password' ? 'text' : 'password';
}

(function initIndustrySelect() {
    const wrapper  = document.getElementById('industrySelect');
    const search   = document.getElementById('industry_search');
    const hidden   = document.getElementById('industry');
    const dropdown   = document.getElementById('industry_dropdown');
    const options    = Array.from(dropdown.querySelectorAll('.searchable-select-option'));
    const groupLabels = Array.from(dropdown.querySelectorAll('.searchable-select-group-label'));
    let activeIndex = -1;

    function openDropdown() {
        dropdown.classList.add('open');
    }
    function closeDropdown() {
        dropdown.classList.remove('open');
        activeIndex = -1;
    }
    function filter() {
        const term = search.value.trim().toLowerCase();
        let visibleCount = 0;
        options.forEach(opt => {
            const group = (opt.dataset.group || '').toLowerCase();
            const match = opt.dataset.value.toLowerCase().includes(term) || (term !== '' && group.includes(term));
            opt.style.display = match ? '' : 'none';
            opt.classList.remove('active');
            if (match) visibleCount++;
        });
        groupLabels.forEach(label => {
            const hasVisibleChild = options.some(o => o.dataset.group === label.dataset.group && o.style.display !== 'none');
            label.style.display = hasVisibleChild ? '' : 'none';
        });
        activeIndex = -1;
        let noResults = dropdown.querySelector('.no-results');
        if (visibleCount === 0) {
            if (!noResults) {
                noResults = document.createElement('div');
                noResults.className = 'searchable-select-option no-results';
                noResults.textContent = 'No matching industry';
                dropdown.appendChild(noResults);
            }
        } else if (noResults) {
            noResults.remove();
        }
    }
    function selectOption(opt) {
        search.value = opt.dataset.value;
        hidden.value = opt.dataset.value;
        closeDropdown();
    }
    function visibleOptions() {
        return options.filter(o => o.style.display !== 'none');
    }
    function setActive(index) {
        const visible = visibleOptions();
        visible.forEach(o => o.classList.remove('active'));
        if (index >= 0 && index < visible.length) {
            visible[index].classList.add('active');
            visible[index].scrollIntoView({ block: 'nearest' });
        }
    }

    search.addEventListener('focus', () => { filter(); openDropdown(); });
    search.addEventListener('input', () => {
        hidden.value = '';
        filter();
        openDropdown();
    });
    search.addEventListener('keydown', (e) => {
        const visible = visibleOptions();
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            openDropdown();
            activeIndex = Math.min(activeIndex + 1, visible.length - 1);
            setActive(activeIndex);
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            activeIndex = Math.max(activeIndex - 1, 0);
            setActive(activeIndex);
        } else if (e.key === 'Enter') {
            if (dropdown.classList.contains('open') && activeIndex >= 0 && visible[activeIndex]) {
                e.preventDefault();
                selectOption(visible[activeIndex]);
            }
        } else if (e.key === 'Escape') {
            closeDropdown();
        }
    });

    options.forEach(opt => {
        opt.addEventListener('mousedown', (e) => {
            e.preventDefault(); // keep focus/avoid blur closing before click registers
            selectOption(opt);
        });
    });

    document.addEventListener('click', (e) => {
        if (!wrapper.contains(e.target)) closeDropdown();
    });

    // On blur, if the typed text doesn't exactly match a known industry, clear it
    // so we don't silently submit an unlisted value.
    search.addEventListener('blur', () => {
        setTimeout(() => {
            const match = options.find(o => o.dataset.value === search.value);
            if (!match) {
                search.value = '';
                hidden.value = '';
            }
        }, 150);
    });
})();

document.getElementById('signupForm').addEventListener('submit', function() {
    const btn = document.getElementById('signupBtn');
    document.getElementById('signupBtnText').textContent = 'Creating...';
    document.getElementById('signupSpinner').style.display = 'inline-block';
    btn.disabled = true;
});
</script>
</body>
</html>
