"use client"; import { useState } from "react"; import type { ChannelResponse } from "@/lib/types"; export function useChannelOrder(channels: ChannelResponse[] | undefined) { const [channelOrder, setChannelOrder] = useState(() => { try { const stored = localStorage.getItem("k-tv-channel-order"); return stored ? JSON.parse(stored) : []; } catch { return []; } }); const saveOrder = (order: string[]) => { setChannelOrder(order); try { localStorage.setItem("k-tv-channel-order", JSON.stringify(order)); } catch {} }; const sortedChannels = channels ? [...channels].sort((a, b) => { const ai = channelOrder.indexOf(a.id); const bi = channelOrder.indexOf(b.id); if (ai === -1 && bi === -1) return 0; if (ai === -1) return 1; if (bi === -1) return -1; return ai - bi; }) : []; const handleMoveUp = (channelId: string) => { const ids = sortedChannels.map((c) => c.id); const idx = ids.indexOf(channelId); if (idx <= 0) return; const next = [...ids]; [next[idx - 1], next[idx]] = [next[idx], next[idx - 1]]; saveOrder(next); }; const handleMoveDown = (channelId: string) => { const ids = sortedChannels.map((c) => c.id); const idx = ids.indexOf(channelId); if (idx === -1 || idx >= ids.length - 1) return; const next = [...ids]; [next[idx], next[idx + 1]] = [next[idx + 1], next[idx]]; saveOrder(next); }; return { channelOrder, sortedChannels, handleMoveUp, handleMoveDown }; }