/** @odoo-module **/

import { Component, useState, useRef, onMounted, xml } from "@odoo/owl";

async function rpc(url, params) {
    const resp = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ jsonrpc: "2.0", method: "call", id: 1, params: params || {} }),
    });
    const data = await resp.json();
    if (data.error) throw new Error(data.error.data?.message || "RPC error");
    return data.result;
}

const STEPS = [
    { key: "goal", title: "Learning Goal", icon: "fa-bullseye" },
    { key: "level", title: "Target Level", icon: "fa-signal" },
    { key: "prefs", title: "Study Preferences", icon: "fa-sliders" },
    { key: "placement", title: "Placement Test", icon: "fa-tasks" },
];

const FALLBACK_GOALS = [
    { id: "ielts", label: "IELTS Preparation", icon: "fa-language", desc: "Prepare for your IELTS exam" },
    { id: "general", label: "General English", icon: "fa-comments", desc: "Improve everyday English" },
    { id: "academic", label: "Academic English", icon: "fa-graduation-cap", desc: "University-level English" },
    { id: "math", label: "Mathematics", icon: "fa-calculator", desc: "Strengthen maths skills" },
    { id: "it", label: "IT Skills", icon: "fa-laptop", desc: "Computer and IT proficiency" },
];

const ICON_MAP = {
    "ielts": "fa-language",
    "general_english": "fa-comments",
    "general": "fa-comments",
    "academic": "fa-graduation-cap",
    "math": "fa-calculator",
    "mathematics": "fa-calculator",
    "it": "fa-laptop",
    "information_technology": "fa-laptop",
};

const LEVELS = [
    { id: "A1", label: "A1 \u2013 Beginner" },
    { id: "A2", label: "A2 \u2013 Elementary" },
    { id: "B1", label: "B1 \u2013 Intermediate" },
    { id: "B2", label: "B2 \u2013 Upper Intermediate" },
    { id: "C1", label: "C1 \u2013 Advanced" },
    { id: "C2", label: "C2 \u2013 Proficiency" },
    { id: "band_5", label: "IELTS Band 5.0" },
    { id: "band_6", label: "IELTS Band 6.0" },
    { id: "band_7", label: "IELTS Band 7.0+" },
];

const STUDY_PREFS = [
    { id: "self_paced", label: "Self-Paced", icon: "fa-user", desc: "Learn at your own speed" },
    { id: "structured", label: "Structured", icon: "fa-calendar", desc: "Follow a weekly schedule" },
    { id: "intensive", label: "Intensive", icon: "fa-bolt", desc: "Fast-track learning" },
];

export class OnboardingWizard extends Component {
    static template = xml`
    <div class="ec-wizard" t-ref="root">
        <div class="ec-wizard-progress mb-4">
            <div class="d-flex justify-content-between mb-2">
                <t t-foreach="steps" t-as="step" t-key="step.key">
                    <div t-attf-class="ec-wizard-step text-center flex-fill #{ step_index &lt;= state.currentStep ? 'active' : '' } #{ step_index &lt; state.currentStep ? 'completed' : '' }">
                        <span t-attf-class="d-inline-flex align-items-center justify-content-center rounded-circle mb-1 #{ step_index &lt;= state.currentStep ? 'bg-primary text-white' : 'bg-light text-muted' }" style="width:36px;height:36px;">
                            <i t-attf-class="fa #{ step_index &lt; state.currentStep ? 'fa-check' : step.icon }"/>
                        </span>
                        <small class="d-block" t-esc="step.title"/>
                    </div>
                </t>
            </div>
            <div class="progress rounded-pill" style="height:6px;">
                <div class="progress-bar bg-primary rounded-pill" t-attf-style="width: #{ progressPercent }%;"/>
            </div>
        </div>

        <div t-if="state.currentStep === 0" class="ec-wizard-panel">
            <h4 class="fw-bold mb-1 text-center">What would you like to learn?</h4>
            <p class="text-muted text-center mb-4">Choose your primary learning goal</p>
            <div class="row g-3">
                <t t-foreach="goals" t-as="goal" t-key="goal.id">
                    <div class="col-md-6">
                        <div t-attf-class="card border-2 rounded-4 h-100 ec-selectable-card #{ state.selectedGoal === goal.id ? 'border-primary shadow-sm' : 'border-light' }"
                             t-on-click="onClickGoal" t-att-data-id="goal.id" role="button">
                            <div class="card-body p-3 d-flex align-items-center">
                                <span t-attf-class="d-inline-flex align-items-center justify-content-center rounded-3 me-3 #{ state.selectedGoal === goal.id ? 'bg-primary text-white' : 'bg-light text-muted' }" style="width:44px;height:44px;">
                                    <i t-attf-class="fa #{ goal.icon }"/>
                                </span>
                                <div>
                                    <h6 class="fw-bold mb-0" t-esc="goal.label"/>
                                    <small class="text-muted" t-esc="goal.desc"/>
                                </div>
                            </div>
                        </div>
                    </div>
                </t>
            </div>
        </div>

        <div t-if="state.currentStep === 1" class="ec-wizard-panel">
            <h4 class="fw-bold mb-1 text-center">What level are you aiming for?</h4>
            <p class="text-muted text-center mb-4">Select your target proficiency</p>
            <div class="row g-2 justify-content-center">
                <t t-foreach="levels" t-as="lvl" t-key="lvl.id">
                    <div class="col-sm-6 col-md-4">
                        <div t-attf-class="card border-2 rounded-3 ec-selectable-card #{ state.selectedLevel === lvl.id ? 'border-primary shadow-sm' : 'border-light' }"
                             t-on-click="onClickLevel" t-att-data-id="lvl.id" role="button">
                            <div class="card-body p-3 text-center">
                                <span class="fw-semibold" t-esc="lvl.label"/>
                            </div>
                        </div>
                    </div>
                </t>
            </div>
        </div>

        <div t-if="state.currentStep === 2" class="ec-wizard-panel">
            <h4 class="fw-bold mb-1 text-center">How do you prefer to study?</h4>
            <p class="text-muted text-center mb-4">Pick the style that suits you best</p>
            <div class="row g-3 justify-content-center">
                <t t-foreach="studyPrefs" t-as="pref" t-key="pref.id">
                    <div class="col-md-4">
                        <div t-attf-class="card border-2 rounded-4 h-100 ec-selectable-card #{ state.selectedPref === pref.id ? 'border-primary shadow-sm' : 'border-light' }"
                             t-on-click="onClickPref" t-att-data-id="pref.id" role="button">
                            <div class="card-body p-4 text-center">
                                <span t-attf-class="d-inline-flex align-items-center justify-content-center rounded-circle mb-2 #{ state.selectedPref === pref.id ? 'bg-primary text-white' : 'bg-light text-muted' }" style="width:52px;height:52px;">
                                    <i t-attf-class="fa fa-lg #{ pref.icon }"/>
                                </span>
                                <h6 class="fw-bold mb-1" t-esc="pref.label"/>
                                <small class="text-muted" t-esc="pref.desc"/>
                            </div>
                        </div>
                    </div>
                </t>
            </div>
        </div>

        <div t-if="state.currentStep === 3" class="ec-wizard-panel">
            <h4 class="fw-bold mb-1 text-center">Take Your Placement Test</h4>
            <p class="text-muted text-center mb-4">We recommend a quick placement test to personalise your learning path</p>
            <div class="card border-0 bg-light rounded-4 mb-4">
                <div class="card-body p-4">
                    <div class="row g-3">
                        <div class="col-sm-4 text-center">
                            <small class="text-muted d-block mb-1">Goal</small>
                            <span class="fw-bold" t-esc="state.selectedGoal"/>
                        </div>
                        <div class="col-sm-4 text-center">
                            <small class="text-muted d-block mb-1">Target Level</small>
                            <span class="fw-bold" t-esc="state.selectedLevel"/>
                        </div>
                        <div class="col-sm-4 text-center">
                            <small class="text-muted d-block mb-1">Study Style</small>
                            <span class="fw-bold" t-esc="state.selectedPref"/>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card border-2 border-primary rounded-4 mb-3">
                <div class="card-body p-4 text-center">
                    <span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-primary bg-opacity-10 text-primary mb-3" style="width:56px;height:56px;">
                        <i class="fa fa-tasks fa-lg"/>
                    </span>
                    <h5 class="fw-bold mb-2">Adaptive Placement Test</h5>
                    <p class="text-muted mb-0">20-30 minutes \u2014 covers Grammar, Vocabulary, Reading, and Speaking</p>
                    <p class="text-muted">Your results will unlock a personalised course tailored to your level</p>
                </div>
            </div>
            <t t-if="state.error">
                <div class="alert alert-danger rounded-3 mt-3" t-esc="state.error"/>
            </t>
        </div>

        <div class="d-flex justify-content-between mt-4">
            <button t-attf-class="btn btn-outline-secondary rounded-3 px-4 #{ isFirstStep ? 'invisible' : '' }"
                    t-on-click="prevStep">
                <i class="fa fa-arrow-left me-2"/>Back
            </button>
            <t t-if="!isLastStep">
                <button class="btn btn-primary rounded-3 px-4"
                        t-att-disabled="!canProceed"
                        t-on-click="nextStep">
                    Next<i class="fa fa-arrow-right ms-2"/>
                </button>
            </t>
            <t t-else="">
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-secondary rounded-3 px-4"
                            t-att-disabled="state.saving"
                            t-on-click="skipPlacement">
                        <t t-if="state.saving"><span class="spinner-border spinner-border-sm me-2"/></t>
                        <t t-else="">Skip for now</t>
                    </button>
                    <button class="btn btn-primary rounded-3 px-4"
                            t-att-disabled="state.saving"
                            t-on-click="takePlacement">
                        <t t-if="state.saving"><span class="spinner-border spinner-border-sm me-2"/>Saving\u2026</t>
                        <t t-else=""><i class="fa fa-play me-2"/>Take Placement Test</t>
                    </button>
                </div>
            </t>
        </div>
    </div>`;

    static props = {};

    setup() {
        this.rootRef = useRef("root");
        this.steps = STEPS;
        this.goals = FALLBACK_GOALS;
        this.levels = LEVELS;
        this.studyPrefs = STUDY_PREFS;

        this.state = useState({
            currentStep: 0,
            selectedGoal: null,
            selectedLevel: null,
            selectedPref: null,
            saving: false,
            error: null,
            goalsLoaded: false,
        });

        onMounted(async () => {
            const el = document.getElementById("ec_onboarding_wizard");
            if (el) {
                this.userId = el.dataset.userId;
                this.profileId = el.dataset.profileId;
            }
            await this._loadGoals();
        });
    }

    async _loadGoals() {
        try {
            const resp = await rpc("/encoach/onboarding/goals");
            if (resp && resp.goals && resp.goals.length) {
                this.goals = resp.goals.map((g) => ({
                    id: g.id,
                    label: g.name || g.label || g.id,
                    icon: g.icon || ICON_MAP[g.id] || "fa-book",
                    desc: g.desc || g.description || "",
                }));
            }
        } catch (e) {
            // Fallback to hardcoded goals on error
        }
        this.state.goalsLoaded = true;
    }

    get isFirstStep() { return this.state.currentStep === 0; }
    get isLastStep() { return this.state.currentStep === STEPS.length - 1; }

    get canProceed() {
        switch (this.state.currentStep) {
            case 0: return !!this.state.selectedGoal;
            case 1: return !!this.state.selectedLevel;
            case 2: return !!this.state.selectedPref;
            case 3: return true;
            default: return false;
        }
    }

    get progressPercent() {
        return Math.round(((this.state.currentStep + 1) / STEPS.length) * 100);
    }

    onClickGoal(ev) {
        const el = ev.target.closest("[data-id]");
        if (el) this.state.selectedGoal = el.dataset.id;
    }
    onClickLevel(ev) {
        const el = ev.target.closest("[data-id]");
        if (el) this.state.selectedLevel = el.dataset.id;
    }
    onClickPref(ev) {
        const el = ev.target.closest("[data-id]");
        if (el) this.state.selectedPref = el.dataset.id;
    }

    nextStep() { if (this.canProceed && !this.isLastStep) this.state.currentStep++; }
    prevStep() { if (!this.isFirstStep) this.state.currentStep--; }

    async submit(skipPlacement) {
        this.state.saving = true;
        this.state.error = null;
        try {
            await rpc("/encoach/onboarding/save", {
                goal: this.state.selectedGoal,
                target_level: this.state.selectedLevel,
                study_preference: this.state.selectedPref,
                skip_placement: !!skipPlacement,
            });
            window.location.href = skipPlacement ? "/my/dashboard" : "/my/placement";
        } catch (e) {
            this.state.error = "Something went wrong. Please try again.";
            this.state.saving = false;
        }
    }

    takePlacement() { this.submit(false); }
    skipPlacement() { this.submit(true); }
}

function mountOnboardingWizard() {
    const target = document.getElementById("ec_onboarding_wizard");
    if (!target) return;
    const { mount } = owl;
    mount(OnboardingWizard, target);
}

if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", mountOnboardingWizard);
} else {
    mountOnboardingWizard();
}
