// Helper utilities

const CLARA_API = window.location.origin;
window.CLARA_API = CLARA_API;

// Date helpers
function daysBetween(a, b) {
  const ms = new Date(b).getTime() - new Date(a).getTime();
  return Math.round(ms / (1000 * 60 * 60 * 24));
}

function fmtDate(iso, opts = {}) {
  if (!iso) return "—";
  const d = new Date(iso);
  if (opts.relative) {
    const days = daysBetween(d, new Date());
    if (days === 0) return "hoy";
    if (days === 1) return "ayer";
    if (days < 7) return `hace ${days} d`;
    if (days < 30) return `hace ${Math.floor(days / 7)} sem`;
    if (days < 365) return `hace ${Math.floor(days / 30)} mes`;
    return `hace ${Math.floor(days / 365)} año`;
  }
  return d.toLocaleDateString("es-ES", { day: "2-digit", month: "short", year: opts.year ? "numeric" : undefined });
}

function fmtDateTime(iso) {
  if (!iso) return "—";
  return new Date(iso).toLocaleString("es-ES", {
    day: "2-digit",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function fmtClock(d = new Date()) {
  return d.toLocaleTimeString("es-ES", { hour: "2-digit", minute: "2-digit" });
}

function getMadridGreeting(date = new Date()) {
  // Madrid is CET/CEST — for prototype, just use local hours
  const h = date.getHours();
  if (h >= 6 && h < 13) return "Buenos días";
  if (h >= 13 && h < 21) return "Buenas tardes";
  return "Buenas noches";
}

function priorityClass(p) {
  if (p === "alta") return { bg: "bg-rose-500/10", text: "text-rose-300", ring: "ring-rose-500/30", dot: "bg-rose-400", label: "Alta" };
  if (p === "media") return { bg: "bg-amber-500/10", text: "text-amber-300", ring: "ring-amber-500/30", dot: "bg-amber-400", label: "Media" };
  return { bg: "bg-emerald-500/10", text: "text-emerald-300", ring: "ring-emerald-500/30", dot: "bg-emerald-400", label: "Baja" };
}

function urgencyClass(u) {
  if (u === "critical") return { bg: "bg-rose-500/10", text: "text-rose-300", ring: "ring-rose-500/40", label: "Crítica" };
  if (u === "urgent") return { bg: "bg-amber-500/10", text: "text-amber-300", ring: "ring-amber-500/30", label: "Urgente" };
  return { bg: "bg-sky-500/10", text: "text-sky-300", ring: "ring-sky-500/30", label: "Normal" };
}

function statusLabel(s) {
  if (s === "urgent") return "Urgente";
  if (s === "waiting") return "En espera";
  if (s === "resolved") return "Resuelta";
  if (s === "pending") return "Pendiente";
  return s;
}

function channelMeta(c) {
  if (c === "voice") return { label: "Voz", icon: "Phone", color: "text-sky-300", bg: "bg-sky-500/10" };
  if (c === "whatsapp") return { label: "WhatsApp", icon: "Whatsapp", color: "text-emerald-300", bg: "bg-emerald-500/10" };
  if (c === "sms") return { label: "SMS", icon: "MessageSquare", color: "text-violet-300", bg: "bg-violet-500/10" };
  if (c === "email") return { label: "Email", icon: "Mail", color: "text-zinc-300", bg: "bg-zinc-500/10" };
  return { label: c, icon: "MessageSquare", color: "text-zinc-300", bg: "bg-zinc-500/10" };
}

function outcomeLabel(o) {
  return ({
    contacted: "Contactado",
    no_answer: "Sin respuesta",
    escalated: "Escalado",
    busy: "Ocupado",
  })[o] || o;
}

function isOverdue(p) {
  if (!p.lastContactDate || !p.contactFrequencyDays) return false;
  const days = daysBetween(p.lastContactDate, new Date());
  return days > p.contactFrequencyDays;
}

function daysSinceContact(p) {
  if (!p.lastContactDate) return null;
  return daysBetween(p.lastContactDate, new Date());
}

function daysWaiting(p) {
  return daysBetween(p.requestDate, new Date());
}

// Parse the "👤 ... / 🤖 ... / 🔧 ... / ✅ ..." transcript into structured turns
function parseTranscript(summary) {
  if (!summary) return { header: "", turns: [] };
  const lines = summary.split("\n");
  const header = [];
  const turns = [];
  let mode = "header";
  for (const raw of lines) {
    const line = raw.trim();
    if (!line) {
      if (mode === "header") header.push("");
      continue;
    }
    if (line.startsWith("👤") || line.startsWith("🤖")) {
      mode = "turns";
      turns.push({
        speaker: line.startsWith("🤖") ? "bot" : "patient",
        text: line.slice(2).trim(),
      });
    } else if (line.startsWith("🔧")) {
      mode = "turns";
      turns.push({
        speaker: "tool_call",
        text: line.slice(2).trim(),
      });
    } else if (line.startsWith("✅")) {
      mode = "turns";
      turns.push({
        speaker: "tool_result",
        text: line.slice(2).trim(),
      });
    } else if (mode === "header") {
      header.push(line);
    } else {
      // continuation of last turn
      if (turns.length) turns[turns.length - 1].text += " " + line;
    }
  }
  return { header: header.join(" ").trim(), turns };
}

Object.assign(window, {
  daysBetween, fmtDate, fmtDateTime, fmtClock, getMadridGreeting,
  priorityClass, urgencyClass, statusLabel, channelMeta, outcomeLabel,
  isOverdue, daysSinceContact, daysWaiting, parseTranscript,
});
