import { createContext, useContext, useState, type ReactNode } from 'react';

interface TimezoneContextType {
  tz: 'UTC' | 'IST';
  toggle: () => void;
  formatHour: (utcHour: number) => string;
  offsetHour: (utcHour: number) => number;
  formatTime: (isoString: string) => string;
  formatDate: (isoString: string) => string;
  tzLabel: string;
}

const TimezoneContext = createContext<TimezoneContextType>({
  tz: 'IST',
  toggle: () => {},
  formatHour: (h) => `${h}:00`,
  offsetHour: (h) => h,
  formatTime: (s) => s,
  formatDate: (s) => s,
  tzLabel: 'IST',
});

export function TimezoneProvider({ children }: { children: ReactNode }) {
  const [tz, setTz] = useState<'UTC' | 'IST'>('IST');

  const toggle = () => setTz(prev => prev === 'UTC' ? 'IST' : 'UTC');

  const offsetHour = (utcHour: number) => {
    if (tz === 'UTC') return utcHour;
    // IST = UTC + 5:30 — round to nearest hour for display
    return (utcHour + 5) % 24;
  };

  const formatHour = (utcHour: number) => {
    const h = offsetHour(utcHour);
    if (tz === 'IST') return `${h.toString().padStart(2, '0')}:30`;
    return `${h.toString().padStart(2, '0')}:00`;
  };

  const formatTime = (isoString: string) => {
    const d = new Date(isoString);
    const timeZone = tz === 'IST' ? 'Asia/Kolkata' : 'UTC';
    return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone });
  };

  const formatDate = (isoString: string) => {
    const d = new Date(isoString);
    const timeZone = tz === 'IST' ? 'Asia/Kolkata' : 'UTC';
    return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', timeZone });
  };

  const tzLabel = tz;

  return (
    <TimezoneContext.Provider value={{ tz, toggle, formatHour, offsetHour, formatTime, formatDate, tzLabel }}>
      {children}
    </TimezoneContext.Provider>
  );
}

export function useTimezone() {
  return useContext(TimezoneContext);
}
