/**
 * Login Panel Component
 * Simple panel with login content
 */
import { requireElement } from "iemjs";
import { doLogin } from "../core/app-control.js";
import { doAnonymousLogin } from "../xmpp/handlers.js";

const LAST_USERNAME_STORAGE_KEY = "weatherim:last-username";

function loadLastUsername() {
    try {
        return localStorage.getItem(LAST_USERNAME_STORAGE_KEY) || "";
    } catch {
        return "";
    }
}

function storeLastUsername(username) {
    try {
        if (!username) {
            localStorage.removeItem(LAST_USERNAME_STORAGE_KEY);
            return;
        }
        localStorage.setItem(LAST_USERNAME_STORAGE_KEY, username);
    } catch {
        // Ignore storage failures and proceed with login.
    }
}

/**
 * Creates a login panel with HTML content
 */
export const LoginPanel = {
    id: "loginpanel",
    xtype: "panel",
    html: `
            <div class="login-shell">
              <div class="login-panel">
                <div class="login-header">
                    <img src="images/nws.png" width="92" alt="NWS Logo" />
                    <h2>Weather.IM Live</h2>
                    <p class="welcome-text">Browser chat access for weather.im</p>
                </div>
                <div id="login-status" class="login-status" hidden></div>

                <div class="login-section primary-section">
                    <h3>Sign In</h3>
                    <p class="login-copy">Welcome to Weather.IM. Please sign in with your user account.</p>
                    <form id="login-form" class="login-form">
                        <div class="form-group">
                            <label for="username">Username</label>
                            <input type="text" id="username" name="username" class="form-control" autocomplete="username" />
                        </div>
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" id="password" name="password" class="form-control" autocomplete="current-password" />
                        </div>
                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">Login</button>
                            <button type="button" id="debug-btn" class="btn btn-secondary">Debug</button>
                        </div>
                        <div class="form-footer">
                            <a href="/pwupdate.php">Forgot your password?</a>
                        </div>
                    </form>
                </div>

                <div class="login-section">
                    <h3>Anonymous Access</h3>
                    <p class="login-copy">You can log in without registering. Anonymous users cannot chat within rooms or save preferences.</p>
                    <button type="button" id="anonymous-btn" class="btn btn-secondary btn-block">
                        Login Anonymously
                    </button>
                </div>

                <div class="login-section">
                    <h3>New User?</h3>
                    <p class="login-copy">Due to spam prevention, new users must register for an account.</p>
                    <a href="/create.php" class="btn btn-secondary btn-block">Create Account</a>
                </div>
              </div>
            </div>
        `,
    border: false,
    autoScroll: true,
    cls: "login-panel-wrapper",
    addMessage(text) {
        const statusEl = document.getElementById("login-status");
        if (!statusEl) {
            return;
        }
        statusEl.textContent = text || "";
        statusEl.hidden = !text;
    },
    setConnectionMessage(text) {
        this.addMessage(text);
    },
    clearMessage() {
        this.addMessage("");
    },
    focusPreferredField() {
        const usernameInput = document.getElementById("username");
        const passwordInput = document.getElementById("password");
        if (!usernameInput) {
            return;
        }
        if (usernameInput.value && passwordInput) {
            passwordInput.focus();
            passwordInput.select();
            return;
        }
        usernameInput.focus();
        usernameInput.select();
    },
    listeners: {
        afterrender: () => {
            // Attach event listeners after panel is rendered
            const form = requireElement("login-form");
            const usernameInput = requireElement("username");
            const savedUsername = loadLastUsername();
            if (!usernameInput.value && savedUsername) {
                usernameInput.value = savedUsername;
            }
            form.addEventListener("submit", (e) => {
                e.preventDefault();
                storeLastUsername(usernameInput.value.trim().toLowerCase());
                doLogin();
            });

            const debugBtn = requireElement("debug-btn");
            debugBtn.addEventListener("click", () => {
                Ext.getCmp("debug").show();
            });

            const anonBtn = requireElement("anonymous-btn");
            anonBtn.addEventListener("click", (e) => {
                const btn = e.currentTarget;
                if (btn && typeof btn.blur === "function") {
                    btn.blur();
                }
                doAnonymousLogin();
            });

            const loginPanel = Ext.getCmp("loginpanel");
            Ext.defer(() => {
                if (loginPanel && loginPanel.focusPreferredField) {
                    loginPanel.focusPreferredField();
                }
            }, 50);
        },
    },
};
