// Global publish-date scheduling. // // Given one start date chosen by the user and a clip's virality RANK (1-based, // rank 1 = most viral — the order the results are presented in), produce the // concrete local date/time that clip should be posted at. // // The cadence posts three clips a day at 18:00 (6pm), 21:00 (9pm) and 13:00 // (1pm). Ranks are taken in pairs: the odd rank of each pair lands on one day // and the even rank of the same pair the next day, at the pair's shared time. // // rank 1 -> day 0 @ 18:00 rank 2 -> day 1 @ 18:00 // rank 3 -> day 0 @ 21:00 rank 4 -> day 1 @ 21:00 // rank 5 -> day 0 @ 13:00 rank 6 -> day 1 @ 13:00 // rank 7 -> day 2 @ 18:00 rank 8 -> day 3 @ 18:00 // rank 9 -> day 2 @ 21:00 rank 10 -> day 3 @ 21:00 // ... // // i.e. every three pairs (six clips) the pair of day-blocks advances by two // days and the time cycles back to 18:00. // The three posting times, in the order they are handed to pairs. const SLOT_TIMES = ['18:00', '21:00', '13:00']; const pad2 = (n) => String(n).padStart(2, '0'); // Shift a 'YYYY-MM-DD' string by `days`, built from LOCAL date parts so it never // crosses the UTC day boundary the way `new Date(...).toISOString()` would for // users west of Greenwich. Returns null when the input is not a plain date. export function addDays(dateStr, days) { const m = String(dateStr || '').match(/^(\d{4})-(\d{2})-(\d{2})$/); if (!m) return null; const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])); d.setDate(d.getDate() + Number(days)); return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`; } // rank: 1-based position in the virality-ordered results. // Returns { date: 'YYYY-MM-DD', time: 'HH:MM' } in the user's local timezone, // or null when there is no start date / no valid rank. export function scheduleForRank(startDate, rank) { if (!startDate) return null; const r = Number(rank); if (!Number.isInteger(r) || r < 1) return null; const pairIndex = Math.floor((r - 1) / 2); // 0 for ranks 1-2, 1 for 3-4, … const time = SLOT_TIMES[pairIndex % 3]; // Every three pairs (6 clips) move the two day-blocks forward by two days. const dayOffset = Math.floor(pairIndex / 3) * 2 + ((r - 1) % 2); const date = addDays(startDate, dayOffset); if (!date) return null; return { date, time }; }