// Widget planifié (`.tpc-fast-hero` sur "Mon suivi" / `.ft-hero` sur l'écran dédié
// "Jeûne" — même widget aux deux endroits depuis la demande explicite utilisateur de
// remplacer l'ancien compteur réactif de l'écran dédié par celui-ci) : suit une fenêtre
// de jeûne PLANIFIÉE et fixe — ancrée sur `windowStartHour` (heure de début de la
// fenêtre de repas, librement réglable, cf. FastingScreen.tsx) — indépendante des repas
// réellement saisis. Seul le statut de la fenêtre déjà conclue (réussie/loupée,
// `previousFastOutcome`) vient des vraies saisies. Reproduit côté web par
// `tkFastPhase()`/`ftPhase()` (tracking.js/fasting-tracking.js) et côté PHP par
// `FastingTrackingService::buildPreviousFastOutcome()`.
function pad(n: number): string {
  return String(n).padStart(2, '0');
}

export function formatHMS(ms: number): string {
  const totalSeconds = Math.max(0, Math.floor(ms / 1000));
  const h = Math.floor(totalSeconds / 3600);
  const m = Math.floor((totalSeconds % 3600) / 60);
  const s = totalSeconds % 60;
  return `${h} h ${pad(m)} min ${pad(s)} s`;
}

export function formatHM(ms: number): string {
  const totalMinutes = Math.max(0, Math.round(ms / 60000));
  const h = Math.floor(totalMinutes / 60);
  const m = totalMinutes % 60;
  if (h <= 0) return `${m} min`;
  return `${h} h ${pad(m)} min`;
}

const FT_CONCLUSION_WINDOW_HOURS = 6;

export type FastPhase = 'in-progress' | 'concluded' | 'waiting';

export function computeFastPhase(
  goalHours: number,
  windowStartHour: number,
  now: Date
): { phase: FastPhase; start: Date; target: Date } {
  const eatingMs = (24 - goalHours) * 3_600_000;
  const goalMs = goalHours * 3_600_000;
  const conclusionMs = Math.min(FT_CONCLUSION_WINDOW_HOURS * 3_600_000, eatingMs);
  const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const todayAnchor = new Date(midnight.getTime() + windowStartHour * 3_600_000);
  const fastStartYesterday = new Date(todayAnchor.getTime() - goalMs);
  const conclusionEnd = new Date(todayAnchor.getTime() + conclusionMs);
  const eatingEndToday = new Date(todayAnchor.getTime() + eatingMs);

  const nowMs = now.getTime();

  if (nowMs < todayAnchor.getTime()) {
    return { phase: 'in-progress', start: fastStartYesterday, target: todayAnchor };
  }
  if (nowMs < conclusionEnd.getTime()) {
    return { phase: 'concluded', start: todayAnchor, target: conclusionEnd };
  }
  if (nowMs < eatingEndToday.getTime()) {
    return { phase: 'waiting', start: conclusionEnd, target: eatingEndToday };
  }
  return { phase: 'in-progress', start: eatingEndToday, target: new Date(eatingEndToday.getTime() + goalMs) };
}

export type FastHeroTone = 'in-progress' | 'waiting' | 'concluded-success' | 'concluded-missed';

// Mêmes couleurs que `.tpc-fast-hero`/`.is-waiting`/`.is-concluded-success`/
// `.is-concluded-missed` (assets/styles/tracking.css) et `.ft-hero`/`.is-waiting`/
// `.is-concluded-success`/`.is-concluded-missed` (assets/styles/fasting-tracking.css).
export const FAST_HERO_GRADIENT: Record<FastHeroTone, [string, string]> = {
  'in-progress': ['#4f46e5', '#8b5cf6'],
  'concluded-success': ['#15803d', '#22c55e'],
  'concluded-missed': ['#b45309', '#d97706'],
  waiting: ['#475569', '#64748b'],
};

export type FastHeroView = {
  tone: FastHeroTone;
  label: string;
  timer: string;
  sub: string;
  showProgress: boolean;
  progressPct: number;
};

export type FastOverviewForHero = {
  goalHours: number;
  windowStartHour: number;
  previousFastOutcome: { success: boolean; missedMs: number | null } | null;
};

function clampPct(pct: number): number {
  return Math.min(100, Math.max(0, pct));
}

export function buildFastHeroView(overview: FastOverviewForHero, now: Date): FastHeroView {
  const { phase, start, target } = computeFastPhase(overview.goalHours, overview.windowStartHour, now);
  const targetHm = target.toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' });

  if (phase === 'concluded') {
    const outcome = overview.previousFastOutcome;
    const success = !outcome || outcome.success;
    return {
      tone: success ? 'concluded-success' : 'concluded-missed',
      label: 'Jeûne terminé',
      timer: success ? 'Réussi' : `Loupé à ${formatHM(outcome?.missedMs ?? 0)}`,
      sub: success
        ? `Jeûne de ${overview.goalHours} h effectué, bravo !`
        : `Il manquait ${formatHM(outcome?.missedMs ?? 0)} pour atteindre l'objectif de ${overview.goalHours} h`,
      showProgress: false,
      progressPct: 0,
    };
  }

  const remainingMs = target.getTime() - now.getTime();
  const progressPct = clampPct(((now.getTime() - start.getTime()) / (target.getTime() - start.getTime())) * 100);

  if (phase === 'waiting') {
    return {
      tone: 'waiting',
      label: 'Prochain jeûne dans',
      timer: formatHMS(remainingMs),
      sub: `Objectif ${overview.goalHours} h — reprise à ${targetHm}`,
      showProgress: true,
      progressPct,
    };
  }

  return {
    tone: 'in-progress',
    label: 'Jeûne en cours',
    timer: formatHMS(remainingMs),
    sub: `Objectif ${overview.goalHours} h — fin prévue à ${targetHm}`,
    showProgress: true,
    progressPct,
  };
}
