
const currentPage = document.body.dataset.page;
document.querySelector(`[data-nav="${currentPage}"]`)?.classList.add("active");

const groupFilter = document.getElementById("equipment-group-filter");
groupFilter?.addEventListener("change", () => {
  window.location.href = groupFilter.value
    ? `/equipment-overview?group=${encodeURIComponent(groupFilter.value)}`
    : "/equipment-overview";
});

function bindTextFilter(inputId, rowSelector) {
  const input = document.getElementById(inputId);
  if (!input) return;
  input.addEventListener("input", () => {
    const query = input.value.trim().toLowerCase();
    document.querySelectorAll(rowSelector).forEach(row => {
      row.style.display = (row.dataset.search || "").toLowerCase().includes(query) ? "" : "none";
    });
  });
}
bindTextFilter("equipment-search", ".equipment-row-wrap");
bindTextFilter("user-search", ".user-row");
bindTextFilter("audit-search", ".audit-row");

function drawSpark(svg, values) {
  if (!values.length) {
    svg.innerHTML = '<text x="20" y="65" fill="#8a9aab" font-size="14">No history</text>';
    return;
  }
  const w=600,h=130,p=12,min=Math.min(...values),max=Math.max(...values),span=Math.max(max-min,.001);
  const points=values.map((v,i)=>{
    const x=p+(i/Math.max(values.length-1,1))*(w-p*2);
    const y=h-p-((v-min)/span)*(h-p*2);
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(" ");
  svg.innerHTML = `<line x1="12" y1="118" x2="588" y2="118" stroke="#dfe6ef"/><polyline points="${points}" fill="none" stroke="#3979e8" stroke-width="2.5" vector-effect="non-scaling-stroke"/>`;
}

document.querySelectorAll("[data-expand-equipment]").forEach(button => {
  button.addEventListener("click", async () => {
    const id = button.dataset.expandEquipment;
    const panel = document.getElementById(`expand-${id}`);
    const opening = panel.hidden;
    panel.hidden = !opening;
    button.classList.toggle("open", opening);
    if (!opening || panel.dataset.loaded) return;
    panel.dataset.loaded = "loading";
    const svg = panel.querySelector(".equipment-sparkline");
    const current = panel.querySelector(".spark-current");
    try {
      const response = await fetch(`/equipment/${encodeURIComponent(id)}/measurements/history?limit=120`, {cache:"no-store"});
      if(!response.ok) throw new Error(`HTTP ${response.status}`);
      const history = await response.json();
      if(!Array.isArray(history)) throw new Error("Invalid history response");
      const temps = history.map(row => Number(row.internal_temperature_c)).filter(Number.isFinite);
      drawSpark(svg, temps);
      current.textContent = temps.length ? `${temps.at(-1).toFixed(2)} °C` : "No data";
      panel.dataset.loaded = "1";
    } catch (_) {
      drawSpark(svg, []);
      current.textContent = "Unavailable — click again to retry";
      delete panel.dataset.loaded;
    }
  });
});

async function apiRequest(url, options={}) {
  const response = await fetch(url, {
    headers: {"Content-Type":"application/json"},
    ...options
  });
  if (!response.ok) {
    let message = `HTTP ${response.status}`;
    try { const body = await response.json(); message = body.detail || message; } catch (_) {}
    throw new Error(message);
  }
  return response.json();
}

// Calendar
const scheduleNode = document.getElementById("schedule-json");
if (scheduleNode) {
  const schedules = JSON.parse(scheduleNode.textContent || "[]");
  const calendar = document.getElementById("alarm-calendar");
  const title = document.getElementById("calendar-title");
  let cursor = new Date();
  cursor.setHours(12,0,0,0);
  let view = "month";

  const isoDate = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,"0")}-${String(d.getDate()).padStart(2,"0")}`;
  const scheduleDate = value => new Date(value);

  function eventsForDay(day) {
    const start = new Date(day); start.setHours(0,0,0,0);
    const end = new Date(day); end.setHours(23,59,59,999);
    return schedules.filter(item => {
      const a = scheduleDate(item.starts_at), b = scheduleDate(item.ends_at);
      return a <= end && b >= start && Number(item.enabled) === 1;
    });
  }

  function renderMonth() {
    const year=cursor.getFullYear(), month=cursor.getMonth();
    title.textContent = cursor.toLocaleDateString(undefined,{month:"long",year:"numeric"});
    const first=new Date(year,month,1), last=new Date(year,month+1,0);
    const mondayIndex=(first.getDay()+6)%7;
    const start=new Date(year,month,1-mondayIndex);
    let html='<div class="month-grid">';
    ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].forEach(d=>html+=`<div class="calendar-weekday">${d}</div>`);
    for(let i=0;i<42;i++){
      const day=new Date(start); day.setDate(start.getDate()+i);
      const other=day.getMonth()!==month, today=isoDate(day)===isoDate(new Date());
      html+=`<div class="calendar-day ${other?"other":""} ${today?"today":""}"><span class="calendar-day-number">${day.getDate()}</span>`;
      eventsForDay(day).slice(0,4).forEach(ev=>{
        const t=scheduleDate(ev.starts_at).toLocaleTimeString([], {hour:"2-digit",minute:"2-digit"});
        html+=`<button type="button" class="calendar-event" data-edit-deviation="${ev.id}" title="${ev.reason}">${t} · ${ev.name}</button>`;
      });
      html+='</div>';
    }
    html+='</div>'; calendar.innerHTML=html;
  }

  function renderAgenda(days) {
    const range=[];
    const base=new Date(cursor);
    if(days===7){ const idx=(base.getDay()+6)%7; base.setDate(base.getDate()-idx); }
    for(let i=0;i<days;i++){ const d=new Date(base); d.setDate(base.getDate()+i); range.push(d); }
    title.textContent = days===1
      ? cursor.toLocaleDateString(undefined,{weekday:"long",day:"numeric",month:"long",year:"numeric"})
      : `${range[0].toLocaleDateString()} — ${range.at(-1).toLocaleDateString()}`;
    let rows=[];
    range.forEach(day => eventsForDay(day).forEach(ev=>rows.push({day,ev})));
    calendar.innerHTML = `<div class="${days===1?"day-list":"week-list"}">${
      rows.length ? rows.map(({day,ev})=>`<button type="button" class="agenda-row" data-edit-deviation="${ev.id}"><time>${day.toLocaleDateString()}<br>${scheduleDate(ev.starts_at).toLocaleTimeString([], {hour:"2-digit",minute:"2-digit"})}</time><div><strong>${ev.name}</strong><br><span>${ev.scope_type} · ${ev.scope_id}</span></div><span>${ev.reason}</span></button>`).join("") : '<div class="empty-state">No deviations in this period.</div>'
    }</div>`;
  }

  function render(){ view==="month" ? renderMonth() : renderAgenda(view==="week"?7:1); }
  render();

  document.getElementById("cal-prev").onclick=()=>{ view==="month"?cursor.setMonth(cursor.getMonth()-1):cursor.setDate(cursor.getDate()-(view==="week"?7:1));render(); };
  document.getElementById("cal-next").onclick=()=>{ view==="month"?cursor.setMonth(cursor.getMonth()+1):cursor.setDate(cursor.getDate()+(view==="week"?7:1));render(); };
  document.getElementById("cal-today").onclick=()=>{ cursor=new Date();render(); };
  document.querySelectorAll("[data-calendar-view]").forEach(btn=>btn.addEventListener("click",()=>{
    view=btn.dataset.calendarView;
    document.querySelectorAll("[data-calendar-view]").forEach(b=>b.classList.toggle("active",b===btn));
    render();
  }));

  const modal=document.getElementById("deviation-modal"), form=document.getElementById("calendar-schedule-form");
  const syncDeviationTarget=()=>{const type=form.elements.scope_type.value; document.getElementById("deviation-equipment-target").hidden=type!=="EQUIPMENT"; document.getElementById("deviation-group-target").hidden=type!=="GROUP"; document.getElementById("deviation-scope-id").value=type==="EQUIPMENT"?document.getElementById("deviation-equipment").value:type==="GROUP"?document.getElementById("deviation-group").value:"SITE";};
  const openModal=(item=null)=>{ form.reset(); form.elements.schedule_id.value=item?.id||""; document.getElementById("deviation-modal-title").textContent=item?"View / edit deviation":"Create a new deviation"; if(item){form.elements.scope_type.value=item.scope_type; form.elements.name.value=item.name||""; form.elements.starts_at.value=(item.starts_at||"").slice(0,16); form.elements.ends_at.value=(item.ends_at||"").slice(0,16); form.elements.alarm_category.value=item.alarm_category||""; form.elements.reason.value=item.reason||""; form.elements.created_by.value=item.created_by||""; if(item.scope_type==="EQUIPMENT")document.getElementById("deviation-equipment").value=item.scope_id; if(item.scope_type==="GROUP")document.getElementById("deviation-group").value=item.scope_id;} syncDeviationTarget(); modal.hidden=false; };
  const closeModal=()=>{ modal.hidden=true; };
  document.getElementById("add-deviation-btn").onclick=()=>openModal();
  document.getElementById("close-deviation").onclick=closeModal; document.getElementById("cancel-deviation").onclick=closeModal;
  form.elements.scope_type.addEventListener("change",syncDeviationTarget); document.getElementById("deviation-equipment").addEventListener("change",syncDeviationTarget); document.getElementById("deviation-group").addEventListener("change",syncDeviationTarget);
  calendar.addEventListener("click",e=>{const target=e.target.closest("[data-edit-deviation]"); if(!target)return; const item=schedules.find(x=>String(x.id)===String(target.dataset.editDeviation)); if(item)openModal(item);});

  form.addEventListener("submit", async e=>{
    e.preventDefault(); syncDeviationTarget(); const data=Object.fromEntries(new FormData(form).entries()); const scheduleId=data.schedule_id; delete data.schedule_id; data.alarm_category=data.alarm_category||null; data.enabled=true;
    try{ await apiRequest(scheduleId?`/api/alarm-schedules/${scheduleId}`:"/api/alarm-schedules",{method:scheduleId?"PUT":"POST",body:JSON.stringify(data)}); window.location.reload(); }catch(error){ window.alert(error.message); }
  });
}
