/**
 * TutorialAutoplayModal — first-visit auto-play tutorial.
 *
 * Workflow:
 *   1. Watch the current route via useLocation().
 *   2. On every change, ask `/api/module-tutorials/me?path=<X>` whether a
 *      tutorial is configured for THIS user on this page.
 *   3. If yes AND localStorage has no `rbs_tutorial_seen_<path>` key, open
 *      a modal that auto-plays the video (YouTube iframe or <video>).
 *   4. Skip button is disabled for the first 5 seconds (configurable),
 *      after which it becomes clickable.
 *   5. On dismiss (Skip / Got it), mark the path as seen — never plays
 *      again unless the user clicks the rose "▶ Watch N-min tutorial"
 *      button inside the AI banner or admin saves a new URL.
 *
 * Mounted once at App-root inside `AppShell`.
 */
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import { X, Play, SkipForward, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { api } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";

const SKIP_DELAY_SECONDS = 5;
const LS_PREFIX = "rbs_tutorial_seen_v1_";

/** Try to extract a YouTube video ID from various URL shapes. */
function extractYoutubeId(url) {
    if (!url) return "";
    // youtu.be/<ID>
    const short = url.match(/youtu\.be\/([A-Za-z0-9_-]{6,15})/);
    if (short) return short[1];
    // youtube.com/watch?v=<ID>
    const watch = url.match(/[?&]v=([A-Za-z0-9_-]{6,15})/);
    if (watch) return watch[1];
    // youtube.com/embed/<ID>
    const embed = url.match(/youtube\.com\/embed\/([A-Za-z0-9_-]{6,15})/);
    if (embed) return embed[1];
    return "";
}

function isMp4(url) {
    return /\.(mp4|webm|ogg|mov)(\?|$)/i.test(url || "");
}

export default function TutorialAutoplayModal() {
    const { user } = useAuth();
    const location = useLocation();
    const [tutorial, setTutorial] = useState(null);     // current tutorial obj
    const [open, setOpen] = useState(false);
    const [skipCountdown, setSkipCountdown] = useState(SKIP_DELAY_SECONDS);
    const [dontShowAgain, setDontShowAgain] = useState(true);
    const timerRef = useRef(null);

    // Don't surface the modal on auth / public pages
    const isAuthPath = useMemo(() => {
        const p = location.pathname;
        return p.startsWith("/login") || p.startsWith("/register") || p.startsWith("/forgot") || p.startsWith("/portal") || p.startsWith("/storefront");
    }, [location.pathname]);

    // Per-path "seen" tracker
    const seenKey = `${LS_PREFIX}${location.pathname}`;
    const isSeen = () => {
        try { return localStorage.getItem(seenKey) === "1"; } catch (e) { return false; }
    };
    const markSeen = () => {
        try { localStorage.setItem(seenKey, "1"); } catch (e) { /* ignore */ }
    };

    // ----- Trigger on route change -----------------------------------------
    useEffect(() => {
        // Guard rails — only after user is logged in
        if (!user || isAuthPath) { setOpen(false); return; }
        // If user has previously dismissed for this path, skip
        if (isSeen()) { setOpen(false); return; }

        let alive = true;
        api.get("/module-tutorials/me", { params: { path: location.pathname } })
            .then((r) => {
                if (!alive) return;
                const t = r.data;
                if (t?.enabled && t?.video_url) {
                    setTutorial(t);
                    setOpen(true);
                    setSkipCountdown(SKIP_DELAY_SECONDS);
                } else {
                    setOpen(false);
                }
            })
            .catch(() => { if (alive) setOpen(false); });
        return () => { alive = false; };
    }, [location.pathname, user, isAuthPath]);

    // ----- Skip countdown tick ---------------------------------------------
    useEffect(() => {
        if (!open) return;
        if (skipCountdown <= 0) return;
        timerRef.current = setTimeout(() => setSkipCountdown((s) => s - 1), 1000);
        return () => { if (timerRef.current) clearTimeout(timerRef.current); };
    }, [open, skipCountdown]);

    if (!open || !tutorial?.video_url) return null;

    const ytId = extractYoutubeId(tutorial.video_url);

    const handleClose = (markIfChecked = true) => {
        setOpen(false);
        if (markIfChecked && dontShowAgain) markSeen();
        // Always mark seen even if checkbox unchecked — second visit should not auto-show
        markSeen();
    };

    const canSkip = skipCountdown <= 0;

    return (
        <div
            className="fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm animate-in fade-in duration-200"
            data-testid="tutorial-autoplay-modal"
        >
            <div className="relative bg-card border-2 border-amber-500/40 rounded-2xl shadow-2xl w-full max-w-3xl overflow-hidden">
                {/* Header */}
                <div className="flex items-center justify-between px-5 py-3 bg-gradient-to-r from-amber-500/10 via-rose-500/10 to-purple-500/10 border-b border-amber-500/30">
                    <div className="flex items-center gap-2 min-w-0">
                        <div className="h-9 w-9 rounded-full bg-rose-500/15 text-rose-600 flex items-center justify-center shrink-0">
                            <Play className="h-4 w-4 fill-current" />
                        </div>
                        <div className="min-w-0">
                            <div className="text-[10px] uppercase tracking-wider text-amber-600 font-semibold">First-time guide</div>
                            <div className="font-display font-bold text-base truncate" data-testid="tutorial-title">
                                {tutorial.title || "Quick walkthrough"}
                            </div>
                        </div>
                    </div>
                    {canSkip ? (
                        <button
                            onClick={() => handleClose(true)}
                            className="text-muted-foreground hover:text-foreground p-1 rounded-md hover:bg-muted transition"
                            aria-label="Close"
                            data-testid="tutorial-close"
                        >
                            <X className="h-5 w-5" />
                        </button>
                    ) : (
                        <div className="text-xs text-muted-foreground tabular-nums shrink-0 pr-1" data-testid="tutorial-countdown">
                            Skip in {skipCountdown}s
                        </div>
                    )}
                </div>

                {/* Description */}
                {tutorial.description && (
                    <div className="px-5 py-2 text-xs text-muted-foreground border-b">{tutorial.description}</div>
                )}

                {/* Player */}
                <div className="aspect-video bg-black" data-testid="tutorial-player">
                    {ytId ? (
                        <iframe
                            title="Tutorial video"
                            width="100%"
                            height="100%"
                            src={`https://www.youtube.com/embed/${ytId}?autoplay=1&rel=0&modestbranding=1`}
                            frameBorder="0"
                            allow="autoplay; encrypted-media; picture-in-picture"
                            allowFullScreen
                        />
                    ) : isMp4(tutorial.video_url) ? (
                        <video
                            src={tutorial.video_url}
                            autoPlay
                            controls
                            className="w-full h-full"
                            onEnded={() => handleClose(true)}
                        ></video>
                    ) : (
                        // Fallback: open in new tab
                        <div className="flex flex-col items-center justify-center h-full text-white text-sm gap-2">
                            <Play className="h-10 w-10 text-amber-400" />
                            <a href={tutorial.video_url} target="_blank" rel="noopener noreferrer" className="underline text-amber-300">Open tutorial video in new tab</a>
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div className="flex flex-wrap items-center justify-between gap-2 px-5 py-3 bg-muted/30 border-t">
                    <label className="flex items-center gap-2 text-xs cursor-pointer select-none">
                        <input
                            type="checkbox"
                            checked={dontShowAgain}
                            onChange={(e) => setDontShowAgain(e.target.checked)}
                            data-testid="tutorial-dont-show"
                            className="h-3.5 w-3.5"
                        />
                        Iss page par firse mat dikhao
                    </label>
                    <div className="flex items-center gap-2">
                        {!canSkip && (
                            <span className="text-[10px] text-muted-foreground" data-testid="tutorial-skip-locked">
                                Skip available in <strong className="tabular-nums">{skipCountdown}s</strong>
                            </span>
                        )}
                        <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleClose(true)}
                            disabled={!canSkip}
                            data-testid="tutorial-skip-btn"
                        >
                            <SkipForward className="h-3.5 w-3.5 mr-1" />
                            Skip
                        </Button>
                        <Button
                            size="sm"
                            onClick={() => handleClose(true)}
                            className="bg-emerald-600 hover:bg-emerald-700 text-white"
                            data-testid="tutorial-gotit-btn"
                        >
                            <CheckCircle2 className="h-3.5 w-3.5 mr-1" />
                            Got it!
                        </Button>
                    </div>
                </div>
            </div>
        </div>
    );
}
