// data.jsx — single source of truth for trips, members, chores

// MEMBERS: the "drenge whitelist". Add `email` to anyone who's given us one;
// drenge without email can still be on the wheel but can't log in until they
// supply one (via the "Invitér dreng"-flow in the app or by editing this file).
const MEMBERS = [
  { id: 'jonathan',   name: 'Jonathan',   initials: 'JO', email: 'jonathan.thorsen@dbac.dk' },
  { id: 'jens',       name: 'Jens',       initials: 'JE', email: 'jens@husfar.org' },
  { id: 'andreas',    name: 'Andreas',    initials: 'AN', email: 'agotfredsen@gmail.com' },
  { id: 'laes',       name: 'Læs',        initials: 'LÆ', email: 'v4rnold@gmail.com' },
  { id: 'christoffer',name: 'Christoffer',initials: 'CH', email: 'christofferg@gmail.com' },
  { id: 'tobias',     name: 'Tobias',     initials: 'TO', email: null },
  { id: 'simon',      name: 'Simon',      initials: 'SI', email: null },
  { id: 'mads',       name: 'Mads',       initials: 'MA', email: null },
  { id: 'martin',     name: 'Martin',     initials: 'MR', email: 'martinme8@gmail.com' },
  { id: 'anders',     name: 'Anders',     initials: 'AD', email: 'andersgrunth@gmail.com' },
  { id: 'mikkel',     name: 'Mikkel',     initials: 'MI', email: 'mikkel.hougs@gmail.com' },
  { id: 'stemgodt',   name: 'Stemgodt',   initials: 'ST', email: 'stemgodt@gmail.com' },
];

// Helpers — all dates are 2026/2027 (Mon-Sun extended weekend trips)
const TRIPS = [
  {
    id: 'foraar-2026',
    name: 'Forårsturen',
    subtitle: 'Anno MMXXVI',
    season: 'spring',
    quadrant: 0,        // brackets months around the trip
    angle: { from: 60,  to: 150 },  // mar-may
    start: '2026-05-21',
    end:   '2026-05-24',
    location: 'Sommerhuset, Asserbo Plantage',
    epigraph: 'Bøgen er sprunget ud. Lyngen vågner. Drengene samles for første gang.',
    motif: 'Bøgeløv & anemoner',
  },
  {
    id: 'sommer-2026',
    name: 'Sommerturen',
    subtitle: 'Højsommer',
    season: 'summer',
    quadrant: 1,
    angle: { from: 150, to: 240 },  // jun-aug
    start: '2026-08-21',
    end:   '2026-08-23',
    location: 'Sommerhuset, Asserbo Plantage',
    epigraph: 'Solen står højt over fyrretræerne. Liefenes lugt af harpiks. Bål om aftenen.',
    motif: 'Fyrretræ & lyng',
  },
  {
    id: 'blackfriday-2026',
    name: 'Black Friday-turen',
    subtitle: 'Kulminationen',
    season: 'autumn',
    quadrant: 2,
    angle: { from: 240, to: 330 },  // sep-nov
    start: '2026-11-27',
    end:   '2026-11-29',
    location: 'Sommerhuset, Asserbo Plantage',
    epigraph: 'Mørket falder kl. 16. Kaminen tændes. Dette er årets ankerpunkt.',
    motif: 'Bark & rav',
    anchor: true,
  },
  {
    id: 'vinter-2027',
    name: 'Vinterturen',
    subtitle: 'Mørkningens ende',
    season: 'winter',
    quadrant: 3,
    angle: { from: 330, to: 420 },  // dec-feb (wraps)
    start: '2027-02-26',
    end:   '2027-02-28',
    location: 'Sommerhuset, Asserbo Plantage',
    epigraph: 'Rimfrosten knaser. Kaffe og cognac. Lyset vender.',
    motif: 'Rim & måneskin',
  },
];

// Past trips — galleriet
const PAST_TRIPS = [
  { id: 'p1', name: 'Black Friday-turen', year: 2025, color: '#5a3a24', motif: 'Bark & rav', tag: 'Anker' },
  { id: 'p2', name: 'Sommerturen',         year: 2025, color: '#7a6a3a', motif: 'Fyrretræ & lyng' },
  { id: 'p3', name: 'Forårsturen',         year: 2025, color: '#8a7a4a', motif: 'Bøgeløv' },
  { id: 'p4', name: 'Vinterturen',         year: 2025, color: '#3a3530', motif: 'Rim' },
  { id: 'p5', name: 'Black Friday-turen', year: 2024, color: '#4a2e1c', motif: 'Bark & rav' },
  { id: 'p6', name: 'Sommerturen',         year: 2024, color: '#6a5a2a', motif: 'Fyrretræ' },
];

// Chore catalog — generated per trip-day
function toLocalIso(d) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function choresForTrip(trip) {
  const start = new Date(trip.start + 'T00:00:00');
  const end   = new Date(trip.end + 'T00:00:00');
  const days = [];
  for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
    days.push(new Date(d));
  }
  // Day 1 (arrival): forberedelser + aftensmad + opvask. No frokost (we arrive afternoon).
  // Last day (departure): frokost + opvask + slutoprydning. No aftensmad.
  // Middle days: frokost + frokost-opvask + aftensmad + aftensmad-opvask.
  // Each chore can have up to 3 people.
  const result = [];
  days.forEach((d, i) => {
    const isFirst = i === 0;
    const isLast  = i === days.length - 1;
    const dateStr = toLocalIso(d);
    if (isFirst) {
      result.push({ id: `${trip.id}-${dateStr}-forberedelser`, day: dateStr, dayIdx: i,
                    type: 'Forberedelser',     icon: 'prep',   max: 3 });
    }
    if (!isFirst) {
      result.push({ id: `${trip.id}-${dateStr}-frokost`, day: dateStr, dayIdx: i,
                    type: 'Frokost + opvask',  icon: 'lunch',  max: 3 });
    }
    if (!isLast) {
      result.push({ id: `${trip.id}-${dateStr}-aftensmad`, day: dateStr, dayIdx: i,
                    type: 'Aftensmad',         icon: 'dinner', max: 3 });
      result.push({ id: `${trip.id}-${dateStr}-opvask`, day: dateStr, dayIdx: i,
                    type: 'Aftensmad-opvask',  icon: 'dishes', max: 3 });
    }
    if (isLast) {
      result.push({ id: `${trip.id}-${dateStr}-slutoprydning`, day: dateStr, dayIdx: i,
                    type: 'Slutoprydning',     icon: 'cleanup', max: 3 });
    }
  });
  return result;
}

// Format helpers
const MONTHS_DA = ['januar','februar','marts','april','maj','juni',
                   'juli','august','september','oktober','november','december'];
const MONTHS_SHORT_DA = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
const WEEKDAYS_DA = ['søn','man','tir','ons','tor','fre','lør'];
const WEEKDAYS_LONG_DA = ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'];

function fmtDate(iso, opts = {}) {
  const d = new Date(iso + 'T00:00:00');
  if (opts.short) return `${d.getDate()}. ${MONTHS_SHORT_DA[d.getMonth()]}`;
  return `${d.getDate()}. ${MONTHS_DA[d.getMonth()]} ${d.getFullYear()}`;
}

function fmtDateRange(start, end) {
  const a = new Date(start + 'T00:00:00');
  const b = new Date(end   + 'T00:00:00');
  if (a.getMonth() === b.getMonth() && a.getFullYear() === b.getFullYear()) {
    return `${a.getDate()}.–${b.getDate()}. ${MONTHS_DA[b.getMonth()]} ${b.getFullYear()}`;
  }
  return `${a.getDate()}. ${MONTHS_SHORT_DA[a.getMonth()]} – ${b.getDate()}. ${MONTHS_SHORT_DA[b.getMonth()]} ${b.getFullYear()}`;
}

function daysBetween(from, toIso) {
  const a = new Date(from);
  const b = new Date(toIso + 'T00:00:00');
  return Math.ceil((b - a) / (1000 * 60 * 60 * 24));
}

// Day-of-year angle for the sun-marker on the year wheel.
// 0° = top (1. jan), goes clockwise.
function dateToAngle(date) {
  const d = new Date(date);
  const start = new Date(d.getFullYear(), 0, 1);
  const diff = (d - start) / (1000 * 60 * 60 * 24);
  return (diff / 365) * 360;
}

// Convert iso date to angle on the wheel (0 = top, clockwise)
function isoToWheelAngle(iso) {
  const d = new Date(iso + 'T00:00:00');
  return dateToAngle(d);
}

// Build .ics file content for a trip
function buildIcs(trip) {
  const dt = (iso) => iso.replace(/-/g, '');
  const stamp = new Date().toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
  // Convert end iso to date for DTEND-exclusive (add 1 day in local time)
  const endDate = new Date(trip.end + 'T00:00:00');
  endDate.setDate(endDate.getDate() + 1);
  const endIso = window.toLocalIso ? window.toLocalIso(endDate) : (() => {
    const y = endDate.getFullYear();
    const m = String(endDate.getMonth() + 1).padStart(2, '0');
    const day = String(endDate.getDate()).padStart(2, '0');
    return `${y}-${m}-${day}`;
  })();
  return [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//De Dekadente Drenge//Aarshjulet//DA',
    'CALSCALE:GREGORIAN',
    'BEGIN:VEVENT',
    `UID:${trip.id}@dekadente-drenge`,
    `DTSTAMP:${stamp}`,
    `DTSTART;VALUE=DATE:${dt(trip.start)}`,
    `DTEND;VALUE=DATE:${dt(endIso)}`,
    `SUMMARY:De Dekadente Drenge — ${trip.name}`,
    `LOCATION:${trip.location}`,
    `DESCRIPTION:${trip.epigraph}\\n\\nMotiv: ${trip.motif}`,
    'END:VEVENT',
    'END:VCALENDAR',
  ].join('\r\n');
}

function downloadIcs(trip) {
  const blob = new Blob([buildIcs(trip)], { type: 'text/calendar;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${trip.id}.ics`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

Object.assign(window, {
  MEMBERS, TRIPS, PAST_TRIPS, choresForTrip, toLocalIso,
  MONTHS_DA, MONTHS_SHORT_DA, WEEKDAYS_DA, WEEKDAYS_LONG_DA,
  fmtDate, fmtDateRange, daysBetween, dateToAngle, isoToWheelAngle,
  buildIcs, downloadIcs,
});
