export const state = {
    isLoggedIn: false,
    phone: '',
    view: 'login', // 'login' | 'onboarding' | 'dashboard'
    currentStep: 1,
    registrationData: {
        nickname: '',
        gender: '',
        zodiac: '',
        mbti: '',
        profession: '',
        hobbies: [],
        childhood: { date: '', text: '' },
        joy: { date: '', text: '' },
        low: { date: '', text: '' },
        future: { vision: '', ideal: '' }
    },
    lifeEvents: [],
    scripts: [], // Array of { id, theme, style, length, content, date, character }
    selectedScriptId: null,
    selectedPath: null,
    
    save() {
        const dataToSave = {
            isLoggedIn: this.isLoggedIn,
            phone: this.phone,
            registrationData: this.registrationData,
            lifeEvents: this.lifeEvents,
            scripts: this.scripts,
            selectedScriptId: this.selectedScriptId,
            selectedPath: this.selectedPath,
            view: this.view
        };
        localStorage.setItem('life_trajectory_v3', JSON.stringify(dataToSave));
    },

    load() {
        const saved = localStorage.getItem('life_trajectory_v3');
        if (saved) {
            try {
                const parsed = JSON.parse(saved);
                Object.assign(this, parsed);
            } catch (e) {
                console.error("Failed to load state:", e);
            }
        }
    },

    updateRegistration(data) {
        this.registrationData = { ...this.registrationData, ...data };
        this.save();
    },

    addLifeEvent(event) {
        this.lifeEvents.push({ ...event, id: Date.now() });
        this.save();
    },

    addScript(script) {
        this.scripts.unshift({ ...script, id: Date.now(), date: new Date().toLocaleDateString() });
        this.selectedScriptId = this.scripts[0].id;
        this.save();
    },

    getSelectedScript() {
        return this.scripts.find(s => s.id === this.selectedScriptId);
    },

    setPath(path) {
        this.selectedPath = path;
        this.save();
    },

    clear() {
        localStorage.removeItem('life_trajectory_v3');
        window.location.reload();
    }
};
