/* ===== Mi Urbania · i18n strings + date/format utilities ===== */
window.MU = window.MU || {};
(function (MU) {
  const STRINGS = {
    es: {
      app_name: "Mi Urbania",
      app_tagline: "Portal del Propietario",
      nav_home: "Inicio", nav_unit: "Mi Unidad", nav_report: "Reportar",
      nav_warranties: "Garantías", nav_help: "Ayuda",

      lang_label: "Idioma",
      switch_unit: "Cambiar unidad",
      your_units: "Tus unidades",
      notifications: "Notificaciones",
      mark_all_read: "Marcar todo como leído",
      no_notifications: "No tienes notificaciones nuevas.",
      back: "Atrás", close: "Cerrar", done: "Listo", cancel: "Cancelar", next: "Siguiente", continue: "Continuar",
      see_all: "Ver todo", search: "Buscar",

      /* Home / clock */
      home_since_handover: "Han pasado {n} días desde la entrega de tu hogar.",
      home_since_handover_one: "Ha pasado {n} día desde la entrega de tu hogar.",
      delivered_meta: "Entregado el {date} · {unit}",
      view_rings: "Anillos", view_timeline: "Línea de tiempo",
      today: "HOY",
      warranties_active_n: "{n} garantías activas",
      section_active: "Vigentes", section_expiring: "Por vencer", section_expired: "Vencidas",
      days_left: "Faltan {n} días", days_left_one: "Falta {n} día",
      expired_ago: "Vencida hace {n} días", expired_ago_one: "Vencida hace {n} día",
      expires_on: "Vence el {date}", expired_on: "Venció el {date}",
      status_active: "En garantía", status_soon: "Por vencer", status_expired: "Fuera de garantía",
      of_warranty: "de garantía",

      crack_window_title: "Estás en el mejor momento para reportar fisuras.",
      crack_window_body: "Faltan ~{n} días para el cierre de la ventana de fisuras (8 meses). Repórtalas todas juntas y las revisamos en una sola visita.",
      crack_window_cta: "Reportar fisuras",
      crack_window_open: "Ventana de fisuras abierta",

      qa_report: "Reportar un problema", qa_warranties: "Ver mis garantías", qa_docs: "Mis documentos",
      home_health: "Salud de tu hogar",
      home_health_sub: "{active} activas · {open} reportes abiertos · {care} cuidados al día",

      /* Warranties + lookup */
      warranties_title: "Garantías",
      warranties_sub: "Cobertura por categoría, calculada desde tu fecha de entrega.",
      lookup_title: "¿Qué cubre mi garantía?",
      lookup_sub: "Busca tu problema y mira al instante si está cubierto.",
      lookup_search_ph: "Busca: puerta, filtración, grieta, AC…",
      filter_room: "Ambiente", filter_category: "Categoría", filter_all: "Todos",
      results_n: "{n} resultados", no_results: "Sin resultados para tu búsqueda.",
      not_listed: "Mi problema no está en la lista",
      not_listed_sub: "Descríbelo y te ayudamos a clasificarlo.",
      covered: "Qué cubre", not_covered: "Qué no cubre",
      what_it_means: "Qué suele significar", what_to_do: "Qué hacer ahora", photo_tip: "Tip de foto",
      report_this: "Reportar esto", report_category: "Reportar algo de esta categoría",
      coverage_for_unit: "Cobertura para tu unidad",
      verdict_in_short: "En garantía · faltan {n} días",
      verdict_soon_short: "Por vencer · faltan {n} días",
      verdict_out_short: "Fuera de garantía desde {date}",
      verdict_crack_short: "Ventana de fisuras · faltan {n} días",
      verdict_safety_short: "Posible tema de seguridad",
      severity_cosmetic: "Cosmético", severity_functional: "Funcional", severity_urgent: "Urgente · Seguridad",
      routed_admin: "Se registra y se enruta a la administración / PH",

      /* Open path */
      open_title: "Cuéntanos qué pasa",
      open_desc_ph: "Descríbelo en tus palabras…",
      open_suggest: "Esto parece relacionarse con:",
      open_confirm: "¿Es correcto?",
      open_yes: "Sí, es correcto", open_no: "Elegir otra categoría",
      new_issue_tag: "Nuevo tipo de incidencia",

      /* Report / claim flow */
      report_title: "Reportar",
      report_intro: "Reporta en 30 segundos. Una foto vale más que mil palabras.",
      step_what: "¿Qué pasó?", step_where: "¿Dónde?", step_photo: "Foto", step_details: "Detalles",
      step_verdict: "Veredicto de garantía", step_confirm: "Confirmación",
      step_of: "Paso {a} de {b}",
      pick_issue: "Elige de la lista", describe_instead: "Describir mi problema",
      where_room: "Ambiente", where_subloc: "Ubicación específica (opcional)",
      subloc_ph: "Ej. puerta principal, baño máster…",
      photo_required: "Agrega una foto o video", photo_required_sub: "Sube o toma fotos y videos del daño. De 1 a 5 archivos.",
      add_photo: "Agregar foto", add_media: "Agregar foto o video", add_media_hint: "Toca para tomar o subir", photo_logged: "Registrado el {datetime}",
      details_optional: "Detalles (opcional)",
      details_ph: "Describe brevemente lo que ves…",
      details_hint: "Mantenlo simple — la foto lleva el peso.",
      verdict_heading: "Veredicto de garantía",
      verdict_in: "La garantía de {item} está activa: faltan {n} días. Tu reporte fue recibido y será revisado.",
      verdict_soon: "La garantía de {item} sigue activa pero vence pronto: faltan {n} días. La revisaremos a tiempo.",
      verdict_out: "Tu unidad fue entregada el {date}. La garantía de {item} venció el {expiry}. Podemos repararlo como servicio.",
      verdict_crack: "Estás dentro de la ventana de fisuras. Repórtalas todas juntas; las revisamos en una sola visita.",
      verdict_safety: "Esto puede ser un tema de seguridad. Lo atendemos de inmediato.",
      offer_service: "Solicitar reparación como servicio",
      submit_claim: "Enviar reporte",
      claim_created: "Reporte creado",
      claim_id: "Folio", claim_status: "Estado",
      claim_receipt_note: "Te avisaremos por aquí y por WhatsApp.",
      view_my_claims: "Ver mis reportes", new_report: "Nuevo reporte",
      my_claims: "Mis reportes", my_claims_empty: "Aún no has hecho ningún reporte.",
      filed_on: "Reportado el {date}",
      claim_received: "Recibido", claim_review: "En revisión", claim_scheduled: "Programado", claim_resolved: "Resuelto",
      verdict_frozen: "Veredicto al momento del reporte",

      /* My unit */
      unit_title: "Mi Unidad",
      unit_handover: "Fecha de entrega", unit_model: "Modelo", unit_area: "Área",
      unit_floor: "Piso", unit_parking: "Estacionamiento", unit_storage: "Depósito",
      unit_admin: "Administración del edificio", unit_address: "Dirección",
      handover_video: "Recorrido de entrega",
      handover_video_sub: "El video del estado de tu hogar el día de la entrega — tu prueba de referencia.",
      play_video: "Reproducir", upload_video: "Subir recorrido", replace_video: "Reemplazar",
      video_recorded_on: "Grabado el {date}", video_doc: "Recorrido de entrega (video)",
      key_facts: "Datos clave",
      components: "Componentes", components_sub: "La ficha técnica de tu hogar.",
      component_warranty: "Garantía", component_issues: "Problemas comunes",

      /* Documents */
      docs_title: "Documentos", docs_sub: "Tus documentos, en un lugar seguro.",
      doc_view: "Ver", doc_download: "Descargar",
      doc_all: "Todos", doc_manual: "Manuales", doc_acta: "Actas", doc_cert: "Certificados", doc_plan: "Planos", doc_contract: "Contrato",

      /* Help */
      help_title: "Ayuda", help_sub: "Respuestas, cuidados y contacto.",
      faq: "Preguntas frecuentes",
      contact_postventa: "Contactar postventa",
      contact_sub: "Estamos para ayudarte.",
      message_in_app: "Enviar mensaje", whatsapp: "WhatsApp",
      maintenance: "Mantenimiento y cuidado",
      care_reminders: "Recordatorios de cuidado",
      care_calendar: "Calendario de cuidado",
      protect_warranty: "Cómo cuidar tu garantía",
      done_label: "Hecho", mark_done: "Marcar hecho",

      /* GaaS */
      gaas_title: "Reparaciones fuera de garantía",
      gaas_sub: "Tu garantía venció, pero podemos repararlo.",
      gaas_quote: "Cotización a solicitud",
      gaas_request: "Solicitar cotización",
      gaas_no_price: "Sin compromiso · sin precio mostrado",
      service_catalog: "Servicios disponibles",

      /* Pre-delivery */
      predelivery_title: "¿Dónde va mi unidad?",
      predelivery_sub: "Sigue el avance de tu hogar hasta la entrega.",
      est_handover: "Entrega estimada",
      ms_reserved: "Reservado", ms_contract: "Contrato firmado", ms_construction: "En construcción",
      ms_finishes: "Acabados", ms_inspection: "Inspección", ms_ready: "Listo para entrega", ms_delivered: "Entregado",
      current_stage: "Etapa actual",

      /* Onboarding */
      ob_lang_title: "Elige tu idioma", ob_lang_sub: "Puedes cambiarlo cuando quieras.",
      ob_confirm_title: "Confirma tu unidad", ob_confirm_sub: "Busca por proyecto y número, o usa tu código de entrega.",
      ob_select: "Seleccionar",
      ob_tour_1_t: "Tu reloj de garantía", ob_tour_1_b: "Mira de un vistazo cuánto tiempo te queda en cada garantía.",
      ob_tour_2_t: "Reporta en segundos", ob_tour_2_b: "Una foto, un toque, y la fecha queda registrada para siempre.",
      ob_tour_3_t: "Todo en un solo lugar", ob_tour_3_b: "Documentos, garantías y cuidados de tu hogar, en tu idioma.",
      ob_start: "Entrar a mi hogar", ob_skip: "Omitir",

      /* Demo control */
      demo_title: "Control de demo", demo_sub: "Avanza el tiempo y mira las garantías agotarse.",
      demo_age: "Edad de la unidad", demo_days: "{n} días desde la entrega",
      demo_reset: "Hoy real", demo_mode: "Modo",
      mode_delivered: "Entregada", mode_predelivery: "Pre-entrega",

      months_full: ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],
    },
    en: {
      app_name: "Mi Urbania",
      app_tagline: "Owner Portal",
      nav_home: "Home", nav_unit: "My Unit", nav_report: "Report",
      nav_warranties: "Warranties", nav_help: "Help",

      lang_label: "Language",
      switch_unit: "Switch unit",
      your_units: "Your units",
      notifications: "Notifications",
      mark_all_read: "Mark all as read",
      no_notifications: "You have no new notifications.",
      back: "Back", close: "Close", done: "Done", cancel: "Cancel", next: "Next", continue: "Continue",
      see_all: "See all", search: "Search",

      home_since_handover: "It's been {n} days since your home was delivered.",
      home_since_handover_one: "It's been {n} day since your home was delivered.",
      delivered_meta: "Delivered {date} · {unit}",
      view_rings: "Rings", view_timeline: "Timeline",
      today: "TODAY",
      warranties_active_n: "{n} active warranties",
      section_active: "Active", section_expiring: "Expiring soon", section_expired: "Expired",
      days_left: "{n} days left", days_left_one: "{n} day left",
      expired_ago: "Expired {n} days ago", expired_ago_one: "Expired {n} day ago",
      expires_on: "Expires {date}", expired_on: "Expired {date}",
      status_active: "Under warranty", status_soon: "Expiring soon", status_expired: "Out of warranty",
      of_warranty: "of warranty",

      crack_window_title: "Now is the best time to report cracks.",
      crack_window_body: "~{n} days until the crack-reporting window (8 months) closes. Report them all at once and we'll review them in a single visit.",
      crack_window_cta: "Report cracks",
      crack_window_open: "Crack window open",

      qa_report: "Report an issue", qa_warranties: "View my warranties", qa_docs: "My documents",
      home_health: "Home health",
      home_health_sub: "{active} active · {open} open reports · {care} care tasks done",

      warranties_title: "Warranties",
      warranties_sub: "Coverage by category, computed from your handover date.",
      lookup_title: "What does my warranty cover?",
      lookup_sub: "Search your issue and instantly see if it's covered.",
      lookup_search_ph: "Search: door, leak, crack, AC…",
      filter_room: "Room", filter_category: "Category", filter_all: "All",
      results_n: "{n} results", no_results: "No results for your search.",
      not_listed: "My issue isn't listed",
      not_listed_sub: "Describe it and we'll help you classify it.",
      covered: "What's covered", not_covered: "What's not covered",
      what_it_means: "What it usually means", what_to_do: "What to do now", photo_tip: "Photo tip",
      report_this: "Report this", report_category: "Report something in this category",
      coverage_for_unit: "Coverage for your unit",
      verdict_in_short: "Under warranty · {n} days left",
      verdict_soon_short: "Expiring soon · {n} days left",
      verdict_out_short: "Out of warranty since {date}",
      verdict_crack_short: "Crack window · {n} days left",
      verdict_safety_short: "Possible safety issue",
      severity_cosmetic: "Cosmetic", severity_functional: "Functional", severity_urgent: "Urgent · Safety",
      routed_admin: "Logged and routed to building administration / PH",

      open_title: "Tell us what's happening",
      open_desc_ph: "Describe it in your words…",
      open_suggest: "This looks related to:",
      open_confirm: "Is that right?",
      open_yes: "Yes, that's right", open_no: "Choose another category",
      new_issue_tag: "New issue type",

      report_title: "Report",
      report_intro: "Report in 30 seconds. A photo is worth a thousand words.",
      step_what: "What happened?", step_where: "Where?", step_photo: "Photo", step_details: "Details",
      step_verdict: "Warranty verdict", step_confirm: "Confirmation",
      step_of: "Step {a} of {b}",
      pick_issue: "Pick from the list", describe_instead: "Describe my issue",
      where_room: "Room", where_subloc: "Specific location (optional)",
      subloc_ph: "e.g. front door, master bath…",
      photo_required: "Add a photo or video", photo_required_sub: "Upload or take photos and videos of the damage. 1 to 5 files.",
      add_photo: "Add photo", add_media: "Add photo or video", add_media_hint: "Tap to capture or upload", photo_logged: "Logged {datetime}",
      details_optional: "Details (optional)",
      details_ph: "Briefly describe what you see…",
      details_hint: "Keep it simple — the photo carries the weight.",
      verdict_heading: "Warranty verdict",
      verdict_in: "Your {item} warranty is active: {n} days remaining. Your report has been received and will be reviewed.",
      verdict_soon: "Your {item} warranty is still active but expires soon: {n} days left. We'll review it in time.",
      verdict_out: "Your unit was delivered on {date}. The {item} warranty expired on {expiry}. We can repair it as a service.",
      verdict_crack: "You're within the crack-reporting window. Report them all at once; we'll review in a single visit.",
      verdict_safety: "This may be a safety issue. We'll address it immediately.",
      offer_service: "Request repair as a service",
      submit_claim: "Submit report",
      claim_created: "Report created",
      claim_id: "Ticket", claim_status: "Status",
      claim_receipt_note: "We'll update you here and via WhatsApp.",
      view_my_claims: "View my reports", new_report: "New report",
      my_claims: "My reports", my_claims_empty: "You haven't filed any reports yet.",
      filed_on: "Reported {date}",
      claim_received: "Received", claim_review: "In review", claim_scheduled: "Scheduled", claim_resolved: "Resolved",
      verdict_frozen: "Verdict at time of filing",

      unit_title: "My Unit",
      unit_handover: "Handover date", unit_model: "Model", unit_area: "Area",
      unit_floor: "Floor", unit_parking: "Parking", unit_storage: "Storage",
      unit_admin: "Building administration", unit_address: "Address",
      handover_video: "Handover walkthrough",
      handover_video_sub: "Video of your home's condition on handover day — your reference proof.",
      play_video: "Play", upload_video: "Upload walkthrough", replace_video: "Replace",
      video_recorded_on: "Recorded {date}", video_doc: "Handover walkthrough (video)",
      key_facts: "Key facts",
      components: "Components", components_sub: "Your home's spec sheet.",
      component_warranty: "Warranty", component_issues: "Common issues",

      docs_title: "Documents", docs_sub: "Your documents, in one secure place.",
      doc_view: "View", doc_download: "Download",
      doc_all: "All", doc_manual: "Manuals", doc_acta: "Records", doc_cert: "Certificates", doc_plan: "Plans", doc_contract: "Contract",

      help_title: "Help", help_sub: "Answers, care tips, and contact.",
      faq: "Frequently asked questions",
      contact_postventa: "Contact post-sales",
      contact_sub: "We're here to help.",
      message_in_app: "Send message", whatsapp: "WhatsApp",
      maintenance: "Maintenance & care",
      care_reminders: "Care reminders",
      care_calendar: "Care calendar",
      protect_warranty: "How to protect your warranty",
      done_label: "Done", mark_done: "Mark done",

      gaas_title: "Out-of-warranty repairs",
      gaas_sub: "Your warranty expired, but we can repair it.",
      gaas_quote: "Quote on request",
      gaas_request: "Request a quote",
      gaas_no_price: "No obligation · no price shown",
      service_catalog: "Available services",

      predelivery_title: "Where's my unit?",
      predelivery_sub: "Follow your home's progress to handover.",
      est_handover: "Estimated handover",
      ms_reserved: "Reserved", ms_contract: "Contract signed", ms_construction: "Under construction",
      ms_finishes: "Finishes", ms_inspection: "Inspection", ms_ready: "Ready for handover", ms_delivered: "Delivered",
      current_stage: "Current stage",

      ob_lang_title: "Choose your language", ob_lang_sub: "You can change it anytime.",
      ob_confirm_title: "Confirm your unit", ob_confirm_sub: "Search by project and number, or use your handover code.",
      ob_select: "Select",
      ob_tour_1_t: "Your warranty clock", ob_tour_1_b: "See at a glance how much time is left on each warranty.",
      ob_tour_2_t: "Report in seconds", ob_tour_2_b: "One photo, one tap, and the date is logged forever.",
      ob_tour_3_t: "Everything in one place", ob_tour_3_b: "Documents, warranties, and home care — in your language.",
      ob_start: "Enter my home", ob_skip: "Skip",

      demo_title: "Demo control", demo_sub: "Fast-forward time and watch warranties deplete.",
      demo_age: "Unit age", demo_days: "{n} days since handover",
      demo_reset: "Real today", demo_mode: "Mode",
      mode_delivered: "Delivered", mode_predelivery: "Pre-delivery",

      months_full: ["January","February","March","April","May","June","July","August","September","October","November","December"],
    }
  };

  function t(lang, key, params) {
    let s = (STRINGS[lang] && STRINGS[lang][key]);
    if (s == null) s = (STRINGS.es[key] != null ? STRINGS.es[key] : key);
    if (typeof s === "string" && params) {
      // pluralization: if a "{n}" with value 1 has a _one variant, caller handles via key choice
      s = s.replace(/\{(\w+)\}/g, (_, k) => (params[k] != null ? params[k] : "{" + k + "}"));
    }
    return s;
  }

  // day-aware string: picks `${key}_one` when n===1
  function tn(lang, key, n, extra) {
    const k = (Math.abs(n) === 1 && STRINGS[lang][key + "_one"]) ? key + "_one" : key;
    return t(lang, k, Object.assign({ n: Math.abs(n) }, extra || {}));
  }

  const MS_DAY = 86400000;
  // parse "YYYY-MM-DD" as a LOCAL date (avoids UTC off-by-one); pass through Dates/ISO.
  function D(x) {
    if (x instanceof Date) return x;
    if (typeof x === "string" && /^\d{4}-\d{2}-\d{2}$/.test(x)) { const p = x.split("-").map(Number); return new Date(p[0], p[1] - 1, p[2]); }
    return new Date(x);
  }
  function startOfDay(d) { const x = new Date(D(d)); x.setHours(0, 0, 0, 0); return x; }
  function addDays(d, n) { const x = new Date(d); x.setDate(x.getDate() + n); return x; }
  function daysBetween(a, b) { return Math.round((startOfDay(b) - startOfDay(a)) / MS_DAY); }

  function formatDate(d, lang) {
    const date = D(d);
    const day = date.getDate();
    const mon = STRINGS[lang].months_full[date.getMonth()];
    const yr = date.getFullYear();
    if (lang === "es") return `${day} de ${mon} de ${yr}`;
    return `${mon} ${day}, ${yr}`;
  }
  function formatDateShort(d, lang) {
    const date = D(d);
    const dd = String(date.getDate()).padStart(2, "0");
    const mm = String(date.getMonth() + 1).padStart(2, "0");
    const yy = date.getFullYear();
    return lang === "es" ? `${dd}/${mm}/${yy}` : `${mm}/${dd}/${yy}`;
  }
  function formatDateTime(d, lang) {
    const date = D(d);
    let h = date.getHours(); const m = String(date.getMinutes()).padStart(2, "0");
    const ampm = h >= 12 ? (lang === "es" ? "p.m." : "PM") : (lang === "es" ? "a.m." : "AM");
    h = h % 12; if (h === 0) h = 12;
    return `${formatDate(date, lang)}, ${h}:${m} ${ampm}`;
  }

  MU.STRINGS = STRINGS;
  MU.D = D;
  MU.t = t;
  MU.tn = tn;
  MU.startOfDay = startOfDay;
  MU.addDays = addDays;
  MU.daysBetween = daysBetween;
  MU.formatDate = formatDate;
  MU.formatDateShort = formatDateShort;
  MU.formatDateTime = formatDateTime;
})(window.MU);
