/* components/FilterModal.jsx */
(() => {
    const METRIC_LABELS = {
        cpo: "CPO",
        ctr: "CTR",
        cvr: "CVR",
        cvCount: "CV数",
        cost: "広告費",
        click: "クリック",
        imp: "IMP",
        transition: "LP遷移率",
        cpc: "CPC",
        cpm: "CPM",
    };

    const METRIC_UNITS = {
        cpo: "円",
        ctr: "%",
        cvr: "%",
        cvCount: "件",
        cost: "円",
        click: "",
        imp: "",
        transition: "%",
        cpc: "円",
        cpm: "円",
    };

    const MetricRow = ({ k, v, onChange }) => {
        const label = METRIC_LABELS[k] || k;
        const unit = METRIC_UNITS[k] || "";
        return (
            <div className="grid grid-cols-12 gap-2 items-center py-2 border-b border-white/5">
                <div className="col-span-4 text-sm">
                    <div className="font-medium">{label}</div>
                    <div className="text-xs opacity-60">範囲で絞り込み</div>
                </div>

                <div className="col-span-8 flex items-center gap-2">
                    <div className="flex-1">
                        <div className="text-[11px] opacity-60 mb-1">最小</div>
                        <input
                            value={v.min}
                            onChange={(e) =>
                                onChange(k, { ...v, min: e.target.value })
                            }
                            inputMode="decimal"
                            className="w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 focus:outline-none focus:ring-2 focus:ring-emerald-600 text-sm"
                            placeholder="例：100"
                        />
                    </div>
                    <div className="flex-1">
                        <div className="text-[11px] opacity-60 mb-1">最大</div>
                        <input
                            value={v.max}
                            onChange={(e) =>
                                onChange(k, { ...v, max: e.target.value })
                            }
                            inputMode="decimal"
                            className="w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 focus:outline-none focus:ring-2 focus:ring-emerald-600 text-sm"
                            placeholder="例：500"
                        />
                    </div>
                    <div className="w-10 text-xs opacity-70 text-right">
                        {unit}
                    </div>
                </div>
            </div>
        );
    };

    // アワード（ラベル）用のツールチップ（body に portal）
    // アワード（ラベル）用のツールチップ（body に portal）
    const AwardTipLabel = ({ id, def }) => {
        const ref = React.useRef(null);
        const tipRef = React.useRef(null);
        const [open, setOpen] = React.useState(false);
        const [anchorRect, setAnchorRect] = React.useState(null);
        const [pos, setPos] = React.useState({ left: 0, top: 0 });

        const computeAnchor = () => {
            const el = ref.current;
            if (!el) return null;
            return el.getBoundingClientRect();
        };

        const setInitialPos = (r) => {
            if (!r) return;
            const margin = 12;
            const vw = window.innerWidth || 1024;
            const tipW = 360;
            let left = r.left;
            if (left + tipW + margin > vw)
                left = Math.max(margin, vw - tipW - margin);
            if (left < margin) left = margin;
            setPos({ left, top: r.bottom + 10 });
        };

        const show = () => {
            const r = computeAnchor();
            setAnchorRect(r);
            setInitialPos(r);
            setOpen(true);
        };
        const hide = () => setOpen(false);

        React.useLayoutEffect(() => {
            if (!open) return;
            const r = anchorRect || computeAnchor();
            const el = tipRef.current;
            if (!r || !el) return;

            const margin = 12;
            const vw = window.innerWidth || 1024;
            const vh = window.innerHeight || 768;

            const rect = el.getBoundingClientRect();
            const tipW = rect.width || 360;
            const tipH = rect.height || 200;

            let left = r.left;
            if (left + tipW + margin > vw)
                left = Math.max(margin, vw - tipW - margin);
            if (left < margin) left = margin;

            let top = r.bottom + 10;
            if (top + tipH + margin > vh) top = r.top - tipH - 10;
            if (top < margin) top = margin;
            if (top + tipH + margin > vh)
                top = Math.max(margin, vh - tipH - margin);

            setPos({ left, top });
        }, [open, anchorRect]);

        const Tip = () => (
            <div
                ref={tipRef}
                className="fixed z-[9999] w-[360px] max-w-[82vw] rounded-2xl border border-white/10 bg-neutral-900 shadow-2xl p-4 text-sm opacity-100 pointer-events-auto cursor-default select-none"
                style={{ left: pos.left, top: pos.top }}
                onMouseEnter={() => setOpen(true)}
                onMouseLeave={hide}
            >
                {/* アイコン + タイトルのみセンタリング */}
                <div className="flex flex-col items-center">
                    {def.icon ? (
                        <div className="w-20 h-20 rounded-full overflow-hidden border border-black mb-3">
                            <img
                                src={def.icon}
                                alt=""
                                className="w-full h-full object-cover"
                                draggable="false"
                            />
                        </div>
                    ) : null}
                    <div className="font-semibold text-center">
                        {def.title || def.label || id}
                    </div>
                </div>

                {/* 本文・条件は左寄せ */}
                <div className="mt-3 text-left">
                    {def.desc ? (
                        <div className="text-xs opacity-90 leading-relaxed whitespace-pre-line">
                            {def.desc}
                        </div>
                    ) : null}
                    {def.cond ? (
                        <div className="mt-2 text-[11px] opacity-70 leading-relaxed whitespace-pre-line">
                            条件：{def.cond}
                        </div>
                    ) : null}
                </div>
            </div>
        );

        return (
            <span
                ref={ref}
                className="text-sm cursor-default select-none"
                onMouseEnter={show}
                onMouseLeave={hide}
            >
                {def.label || id}
                {open && ReactDOM && ReactDOM.createPortal
                    ? ReactDOM.createPortal(<Tip />, document.body)
                    : null}
            </span>
        );
    };

    function FilterModal(props) {
        const {
            open,
            onClose,
            filters,
            setFilters,
            awardFilter,
            setAwardFilter,
            awardDefs,
            matchedCount,
            totalCount,
        } = props;
        if (!open) return null;

        const onRowChange = (k, next) => {
            setFilters((prev) => ({ ...prev, [k]: next }));
        };

        const clearAll = () => {
            const cleared = {};
            Object.keys(filters || {}).forEach(
                (k) => (cleared[k] = { min: "", max: "" })
            );
            setFilters(cleared);
            if (setAwardFilter) {
                setAwardFilter({
                    click: false,
                    conversion: false,
                    market: false,
                    efficiency: false,
                    funnel: false,
                    outlier: false,
                });
            }
        };

        // UX: クリエイティブ担当がよく使う「まずCVありに寄せる」ショートカット
        const setHasCV = () => {
            setFilters((prev) => ({
                ...prev,
                cvCount: {
                    ...(prev.cvCount || { min: "", max: "" }),
                    min: "1",
                },
            }));
        };

        return (
            <div
                className="fixed inset-0 m-0 p-0 z-[95] flex items-end md:items-center justify-center"
                style={{ margin: 0 }}
                role="dialog"
                aria-modal="true"
            >
                <div
                    className="absolute inset-0 bg-black/70"
                    onClick={onClose}
                />
                <div className="relative w-full md:w-[720px] max-h-[85vh] overflow-hidden rounded-2xl border border-white/10 bg-neutral-900 shadow-2xl">
                    <div className="p-4 border-b border-white/10 flex items-center justify-between">
                        <div>
                            <div className="text-base font-semibold">
                                フィルター
                            </div>
                            <div className="text-xs opacity-60 mt-0.5">
                                {totalCount}件中{" "}
                                <span className="font-medium">
                                    {matchedCount}件
                                </span>{" "}
                                を表示
                            </div>
                        </div>
                        <div className="flex items-center gap-2">
                            <button
                                type="button"
                                className="px-3 py-2 rounded-lg bg-white/5 hover:bg-white/10 text-sm"
                                onClick={setHasCV}
                                title="CVが出ているものだけに寄せる"
                            >
                                CVあり
                            </button>
                            <button
                                type="button"
                                className="px-3 py-2 rounded-lg bg-white/5 hover:bg-white/10 text-sm"
                                onClick={clearAll}
                            >
                                クリア
                            </button>
                            <button
                                type="button"
                                className="px-3 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-sm text-white"
                                onClick={onClose}
                            >
                                閉じる
                            </button>
                        </div>
                    </div>

                    <div className="p-4 overflow-auto modal-scroll max-h-[calc(85vh-64px)]">
                        {/* ラベルで絞り込み */}
                        <div className="mb-4 p-3 rounded-xl border border-white/10 bg-white/5">
                            <div className="text-sm font-semibold mb-2">
                                ラベルで絞り込み
                            </div>
                            <div className="text-xs opacity-60 mb-3">
                                チェックしたラベルを
                                <strong className="font-medium">含む</strong>
                                バナーのみ表示します。
                            </div>

                            <div className="grid grid-cols-2 gap-2">
                                {[
                                    "click",
                                    "conversion",
                                    "market",
                                    "efficiency",
                                    "funnel",
                                    "outlier",
                                ].map((id) => {
                                    const def = (awardDefs &&
                                        awardDefs[id]) || {
                                        label: id,
                                        dotClass: "bg-white/40",
                                    };
                                    const checked = !!(
                                        awardFilter && awardFilter[id]
                                    );
                                    return (
                                        <label
                                            key={id}
                                            className="flex items-center gap-2 px-3 py-2 rounded-lg bg-black/20 hover:bg-black/30 border border-white/10 cursor-pointer select-none"
                                            title={def.label}
                                        >
                                            <input
                                                type="checkbox"
                                                className="accent-emerald-500"
                                                checked={checked}
                                                onChange={(e) => {
                                                    if (!setAwardFilter) return;
                                                    const next = {
                                                        ...(awardFilter || {}),
                                                    };
                                                    next[id] = e.target.checked;
                                                    setAwardFilter(next);
                                                }}
                                            />
                                            <span
                                                className={
                                                    "w-2.5 h-2.5 rounded-full " +
                                                    (def.dotClass ||
                                                        "bg-white/40")
                                                }
                                            />
                                            <AwardTipLabel id={id} def={def} />
                                        </label>
                                    );
                                })}
                            </div>
                        </div>

                        {/* よく使う項目を上に */}
                        {[
                            "cost",
                            "imp",
                            "click",
                            "cvCount",
                            "ctr",
                            "transition",
                            "cvr",
                            "cpo",
                            "cpc",
                            "cpm",
                        ].map((k) => (
                            <MetricRow
                                key={k}
                                k={k}
                                v={filters?.[k] || { min: "", max: "" }}
                                onChange={onRowChange}
                            />
                        ))}
                    </div>
                </div>
            </div>
        );
    }

    window.Cmp = window.Cmp || {};
    window.Cmp.FilterModal = FilterModal;
})();
