"use client";

import { AnimatePresence, motion } from "framer-motion";
import Image from "next/image";
import { useEffect, useState } from "react";
import { getCareerCards, getCareerSection, getMediaUrl } from "../../../lib/strapiClient";
import { gaEvent } from "../../../lib/ga";

/* =======================
   KONFIG: Strapi base URL
   ======================= */
const STRAPI_BASE = "https://admin.laskar.pl";

// Animacje
const fadeInUp = {
    initial: { opacity: 0, y: 40 },
    animate: { opacity: 1, y: 0 },
};

// Typy Strapi
type InlineNode =
    | { type: "text"; text: string; bold?: boolean; italic?: boolean }
    | { type: "link"; url?: string; children: InlineNode[] }
    | {
    type: string;
    text?: string;
    bold?: boolean;
    italic?: boolean;
    url?: string;
    children?: InlineNode[];
};

type Block =
    | { type: "paragraph"; children: InlineNode[] }
    | { type: "heading"; level: number; children: InlineNode[] }
    | {
    type: "list";
    format: "ordered" | "unordered";
    children: { type: "list-item"; children: InlineNode[] }[];
}
    | { type: "quote"; children: InlineNode[] }
    | { type: "code"; children: InlineNode[] }
    | { type: "image"; image?: { url?: string }; alt?: string }
    | { type: "media"; file?: { url?: string } }
    | { type: string; children?: InlineNode[]; [k: string]: any };

/* =======================
   Helpers: URL + image/video
   ======================= */
function toAbsoluteStrapiUrl(url: string | null): string | null {
    if (!url) return null;
    const trimmed = url.trim();
    if (!trimmed) return null;
    if (/^https?:\/\//i.test(trimmed)) return trimmed;
    if (trimmed.startsWith("/")) return `${STRAPI_BASE}${trimmed}`;
    return `${STRAPI_BASE}/${trimmed}`;
}

function isVideoUrl(url: string): boolean {
    const clean = String(url).split("?")[0].split("#")[0].toLowerCase();
    return (
        clean.endsWith(".mp4") ||
        clean.endsWith(".webm") ||
        clean.endsWith(".ogg") ||
        clean.endsWith(".mov") ||
        clean.endsWith(".m4v") ||
        clean.endsWith(".m3u8")
    );
}

/**
 * Obsługuje:
 * - string: "/uploads/a.jpg"
 * - obiekt z url: { url: "/uploads/a.jpg" }
 * - Strapi single: { data: { attributes: { url } } }
 * - Strapi multiple: { data: [{ attributes: { url } }] } (bierze pierwsze)
 * - fallback: getMediaUrl(input)
 */
function safeMediaUrl(input: unknown): string | null {
    if (!input) return null;

    if (typeof input === "string") return toAbsoluteStrapiUrl(input);

    const anyInput = input as any;

    if (typeof anyInput?.url === "string") return toAbsoluteStrapiUrl(anyInput.url);

    const single = anyInput?.data?.attributes?.url;
    if (typeof single === "string") return toAbsoluteStrapiUrl(single);

    const first = anyInput?.data?.[0]?.attributes?.url;
    if (typeof first === "string") return toAbsoluteStrapiUrl(first);

    const raw = String(getMediaUrl(anyInput) || "").trim();
    return toAbsoluteStrapiUrl(raw);
}

/* =======================
   Render inline → React (z trackingiem linków)
   ======================= */
function Inline({
                    nodes = [] as InlineNode[],
                    onLinkClick,
                }: {
    nodes?: InlineNode[];
    onLinkClick?: (href: string) => void;
}) {
    return (
        <>
            {nodes.map((n, i) => {
                if (n.type === "link") {
                    const href = n.url || "#";
                    return (
                        <a
                            key={i}
                            href={href}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="underline underline-offset-2 hover:opacity-90"
                            onClick={(e) => {
                                e.stopPropagation();
                                onLinkClick?.(href);
                            }}
                        >
                            <Inline nodes={n.children || []} onLinkClick={onLinkClick} />
                        </a>
                    );
                }

                const text = (n as any).text ?? "";
                const bold = (n as any).bold;
                const italic = (n as any).italic;

                const className = [bold ? "font-semibold" : "", italic ? "italic" : ""].filter(Boolean).join(" ");

                return (
                    <span key={i} className={className}>
            {text}
          </span>
                );
            })}
        </>
    );
}

/* =======================
   Render block → React
   ======================= */
function Blocks({
                    blocks = [] as Block[],
                    onInlineLinkClick,
                }: {
    blocks?: Block[];
    onInlineLinkClick?: (href: string) => void;
}) {
    return (
        <div className="space-y-3">
            {blocks.map((b, i) => {
                if (b.type === "paragraph") {
                    return (
                        <p key={i} className="text-white/80 text-sm leading-relaxed">
                            <Inline nodes={b.children || []} onLinkClick={onInlineLinkClick} />
                        </p>
                    );
                }

                if (b.type === "heading") {
                    const lvl = Math.min(Math.max(Number((b as any).level || (b as any).headingLevel || 2), 1), 6);
                    type HeadingTag = "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
                    const Tag = `h${lvl}` as HeadingTag;

                    const cls =
                        lvl === 1 ? "text-xl font-bold" : lvl === 2 ? "text-lg font-semibold" : "text-base font-semibold";

                    return (
                        <Tag key={i} className={`${cls} text-white`}>
                            <Inline nodes={(b as any).children || []} onLinkClick={onInlineLinkClick} />
                        </Tag>
                    );
                }

                if (b.type === "list") {
                    const isOrdered = (b as any).format === "ordered";
                    const ListTag = (isOrdered ? "ol" : "ul") as "ol" | "ul";

                    return (
                        <ListTag
                            key={i}
                            className={`pl-5 text-white/80 text-sm leading-relaxed ${isOrdered ? "list-decimal" : "list-disc"}`}
                        >
                            {(b as any).children?.map((li: any, idx: number) => (
                                <li key={idx} className="mb-1">
                                    <Inline nodes={li.children || []} onLinkClick={onInlineLinkClick} />
                                </li>
                            ))}
                        </ListTag>
                    );
                }

                if (b.type === "quote") {
                    return (
                        <blockquote key={i} className="border-l-2 border-white/30 pl-4 italic text-white/80 text-sm">
                            <Inline nodes={b.children || []} onLinkClick={onInlineLinkClick} />
                        </blockquote>
                    );
                }

                if (b.type === "code") {
                    const codeText = (b.children || []).map((c: any) => c.text || "").join("");
                    return (
                        <pre
                            key={i}
                            className="bg-black/40 p-3 rounded-lg overflow-x-auto text-xs text-white/80"
                            onClick={(e) => e.stopPropagation()}
                        >
              <code>{codeText}</code>
            </pre>
                    );
                }

                if (b.type === "image") {
                    const url = (b as any).image?.url ? safeMediaUrl((b as any).image) : null;
                    if (!url) return null;

                    return (
                        <div key={i} className="relative w-full h-48 rounded-xl overflow-hidden" onClick={(e) => e.stopPropagation()}>
                            <Image src={url} alt={(b as any).alt || "Image"} fill className="object-cover" />
                        </div>
                    );
                }

                if (b.type === "media") {
                    const url = (b as any).file?.url ? safeMediaUrl((b as any).file) : null;
                    if (!url) return null;

                    const isVideo = isVideoUrl(url);

                    return (
                        <div key={i} className="relative w-full rounded-xl overflow-hidden" onClick={(e) => e.stopPropagation()}>
                            {isVideo ? (
                                <video src={url} autoPlay muted loop playsInline preload="metadata" className="w-full h-auto" />
                            ) : (
                                <a
                                    href={url}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="underline underline-offset-2 text-white/80 text-sm"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onInlineLinkClick?.(url);
                                    }}
                                >
                                    Otwórz plik
                                </a>
                            )}
                        </div>
                    );
                }

                return (
                    <div key={i} className="text-white/60 text-xs">
                        [Nieobsługiwany blok: {(b as any).type}]
                    </div>
                );
            })}
        </div>
    );
}

function blocksToPlainText(blocks: Block[]): string {
    const collectInlineText = (nodes: InlineNode[] = []) =>
        nodes
            .map((n: any) => {
                if (n.type === "link") return collectInlineText(n.children || []);
                return n.text || "";
            })
            .join("");

    return blocks
        .map((b: any) => {
            if (b.type === "paragraph" || b.type === "heading" || b.type === "quote") return collectInlineText(b.children || []);
            if (b.type === "list") return (b.children || []).map((li: any) => collectInlineText(li.children || [])).join(" ");
            if (b.type === "code") return (b.children || []).map((c: any) => c.text || "").join("");
            return "";
        })
        .join(" ")
        .replace(/\s+/g, " ")
        .trim();
}

function preview30(text: string): string {
    if (!text) return "";
    return text.length > 30 ? text.slice(0, 30) : text;
}

type CareerCard = {
    id: number | string;
    tytul_pracy: string;
    opis_pracy?: Block[];
    zdjecie_pracy?: unknown;
};

type CareerSection = {
    tytul_hero?: string;
    podtytul_hero?: string;

    hero_title?: string;
    hero_subtitle?: string;

    hero_image?: unknown;

    footer_title?: string;
    footer_subtitle?: string;
    footer_button_label?: string;
    mail_do_aplikowania?: string;
};

export default function CarrerModalContent({ locale = "pl" }: { locale?: import("../../../lib/locale").SupportedLocale }) {
    const [cards, setCards] = useState<CareerCard[]>([]);
    const [section, setSection] = useState<CareerSection | null>(null);
    const [expandedIndex, setExpandedIndex] = useState<number | null>(null);

    useEffect(() => {
        const load = async () => {
            try {
                const [cardsData, sectionData] = await Promise.all([getCareerCards(locale), getCareerSection(locale)]);
                setCards(cardsData || []);
                setSection(sectionData || null);
            } catch (e) {
                console.error("Career section load error:", e);
            }
        };
        load();
    }, []);

    const heroTitle = section?.hero_title || section?.tytul_hero || "Kariera";
    const heroSubtitle = section?.hero_subtitle || section?.podtytul_hero || "Przebieg mojej kariery zawodowej.";

    const heroMediaUrl = safeMediaUrl(section?.hero_image);
    const heroIsVideo = heroMediaUrl ? isVideoUrl(heroMediaUrl) : false;

    const footerTitle = section?.footer_title || "Chcesz dołączyć do zespołu?";
    const footerSubtitle = section?.footer_subtitle || "Wyślij zgłoszenie, a odezwiemy się do Ciebie.";
    const footerButtonLabel = section?.footer_button_label || "Aplikuj";
    const applyEmail = section?.mail_do_aplikowania || "biuro@laskar.pl";

    const onInlineLinkClick = (href: string) => {
        gaEvent("career_inline_link_click", { href });
    };

    const toggleExpand = (index: number, source: "card" | "button") => {
        setExpandedIndex((prev) => {
            const next = prev === index ? null : index;

            const job = cards[index];
            const title = job?.tytul_pracy ?? "unknown";
            const state = next === null ? "collapsed" : "expanded";

            gaEvent("career_card_toggle", { index, state, source, title });

            return next;
        });
    };

    const onApplyClick = () => {
        gaEvent("career_apply_click", { method: "mailto", email: applyEmail });
    };

    return (
        <motion.div
            className="w-full max-w-5xl mx-auto bg-white/5 backdrop-blur-sm rounded-2xl overflow-hidden border border-white/10 shadow-2xl text-white"
            initial={{ opacity: 0, scale: 0.95, y: 30 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 30 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
        >
            {/* HERO */}
            <div className="relative w-full h-48 sm:h-64">
                {heroMediaUrl ? (
                    heroIsVideo ? (
                        <video
                            src={heroMediaUrl}
                            autoPlay
                            muted
                            loop
                            playsInline
                            preload="metadata"
                            className="absolute inset-0 w-full h-full object-cover brightness-75"
                        />
                    ) : (
                        <Image src={heroMediaUrl} alt={heroTitle} fill priority className="object-cover brightness-75" />
                    )
                ) : (
                    <div className="absolute inset-0 w-full h-full bg-white/10" />
                )}

                <div className="absolute inset-0 bg-black/50" />
                <div className="absolute inset-0 flex flex-col items-center justify-center text-center px-4">
                    <h1 className="text-3xl sm:text-4xl font-bold">{heroTitle}</h1>
                    <p className="text-white/70 mt-2 text-sm sm:text-base max-w-md">{heroSubtitle}</p>
                </div>
            </div>

            {/* KARTY */}
            <div className="p-6 sm:p-8 grid grid-cols-1 sm:grid-cols-2 gap-6 items-start">
                {cards.map((job, index) => {
                    const title = job.tytul_pracy;
                    const blocks = job.opis_pracy || [];
                    const plain = blocksToPlainText(blocks);
                    const shortText = preview30(plain);
                    const longer = plain.length > 30;

                    const mediaUrl = safeMediaUrl(job.zdjecie_pracy);
                    const isVideo = mediaUrl ? isVideoUrl(mediaUrl) : false;

                    const isExpanded = expandedIndex === index;

                    return (
                        <motion.div
                            key={job.id ?? index}
                            initial="initial"
                            whileInView="animate"
                            viewport={{ once: true, amount: 0.2 }}
                            variants={fadeInUp}
                            transition={{ duration: 0.5, delay: 0.2 + index * 0.15 }}
                            className="bg-white/10 border border-white/10 rounded-xl overflow-hidden hover:bg-white/20 transition flex flex-col cursor-pointer"
                            onClick={() => longer && toggleExpand(index, "card")}
                            role={longer ? "button" : undefined}
                            tabIndex={longer ? 0 : -1}
                            onKeyDown={(e) => {
                                if (!longer) return;
                                if (e.key === "Enter" || e.key === " ") {
                                    e.preventDefault();
                                    toggleExpand(index, "card");
                                }
                            }}
                        >
                            <div className="relative w-full h-40 sm:h-52">
                                {mediaUrl ? (
                                    isVideo ? (
                                        <video
                                            src={mediaUrl}
                                            autoPlay
                                            muted
                                            loop
                                            playsInline
                                            preload="metadata"
                                            className="absolute inset-0 w-full h-full object-cover pointer-events-none"
                                        />
                                    ) : (
                                        <Image src={mediaUrl} alt={title} fill className="object-cover" />
                                    )
                                ) : (
                                    <div className="w-full h-full bg-white/10" />
                                )}
                            </div>

                            <div className="p-4 sm:p-6 flex flex-col flex-1">
                                <h3 className="text-lg sm:text-xl font-semibold mb-2">{title}</h3>

                                <AnimatePresence initial={false}>
                                    <motion.div
                                        key={isExpanded ? "expanded" : "collapsed"}
                                        initial={{ opacity: 0, height: 0 }}
                                        animate={{ opacity: 1, height: "auto" }}
                                        exit={{ opacity: 0, height: 0 }}
                                        transition={{ duration: 0.3, ease: "easeInOut" }}
                                        className="overflow-hidden text-white/80 text-sm leading-relaxed mb-2"
                                    >
                                        {isExpanded ? (
                                            <Blocks blocks={blocks} onInlineLinkClick={onInlineLinkClick} />
                                        ) : (
                                            <p>
                                                {shortText}
                                                {longer ? " [...]" : ""}
                                            </p>
                                        )}
                                    </motion.div>
                                </AnimatePresence>

                                {longer && (
                                    <button
                                        type="button"
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            gaEvent("career_card_toggle_button", {
                                                index,
                                                title,
                                                next_state: isExpanded ? "collapsed" : "expanded",
                                            });
                                            toggleExpand(index, "button");
                                        }}
                                        className="mt-auto text-[#eea71f] text-sm font-semibold self-start"
                                    >
                                        {isExpanded ? "Zwiń" : "Czytaj więcej"}
                                    </button>
                                )}
                            </div>
                        </motion.div>
                    );
                })}
            </div>

            {/* CTA / STOPKA */}
            <motion.div
                className="text-center px-6 pb-8"
                initial="initial"
                whileInView="animate"
                viewport={{ once: true, amount: 0.2 }}
                variants={fadeInUp}
                transition={{ duration: 0.5, delay: 0.2 }}
            >
                <h2 className="text-xl sm:text-2xl font-bold mb-3">{footerTitle}</h2>
                <p className="text-white/70 max-w-md mx-auto text-sm sm:text-base mb-6">{footerSubtitle}</p>

                <a
                    href={`mailto:${applyEmail}`}
                    className="text-sm font-medium text-[#eea71f] border border-[#eea71f] px-5 py-2 rounded-full hover:bg-[#eea71f]/10 transition duration-300 ease-in-out cursor-pointer"
                    onClick={(e) => {
                        e.stopPropagation();
                        onApplyClick();
                    }}
                >
                    {footerButtonLabel}
                </a>
            </motion.div>
        </motion.div>
    );
}
