import ICAL from 'ical.js';

export const fetchAndParseCalendar = async (url) => {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Failed to fetch calendar: ${response.statusText}`);
    }
    const text = await response.text();
    
    // Basic validation to check if it looks like an ICS file
    if (!text.includes('BEGIN:VCALENDAR')) {
      throw new Error('Invalid calendar format. Expected ICS data.');
    }

    const jcalData = ICAL.parse(text);
    const comp = new ICAL.Component(jcalData);
    const vevents = comp.getAllSubcomponents('vevent');

    return vevents.map(vevent => {
      const event = new ICAL.Event(vevent);
      
      // Handle different date types (Date vs DateTime)
      let startDate = event.startDate.toJSDate();
      let endDate = event.endDate.toJSDate();
      
      // Adjust for all-day events if needed (though toJSDate usually handles it)
      // If it's all day, start/end might be at 00:00 UTC, which is fine.

      return {
        uid: event.uid,
        summary: event.summary,
        description: event.description,
        location: event.location,
        startDate: startDate,
        endDate: endDate,
        isRecurring: event.isRecurring(),
        // We could extract recurrence rules here if needed
        recurrenceRule: event.component.getFirstPropertyValue('rrule') ? event.component.getFirstPropertyValue('rrule').toString() : null
      };
    });
  } catch (error) {
    console.error("Error parsing calendar:", error);
    throw new Error(`Calendar import failed: ${error.message}`);
  }
};

export const validateCalendarUrl = (url) => {
  if (!url) return false;
  try {
    const parsed = new URL(url);
    return parsed.protocol === 'http:' || parsed.protocol === 'https:';
  } catch (e) {
    return false;
  }
};