/* ===== Mi Urbania · Home (Warranty Clock) + pre-delivery ===== */
window.MU = window.MU || {};
(function (MU) {
  const { useState, useMemo } = React;
  const e = React.createElement;

  function tmplNode(str, node) {
    const parts = String(str).split("{n}");
    return e(React.Fragment, null, parts[0], node, parts[1] || "");
  }

  /* ---- a single warranty ring card ---- */
  function RingCard({ cat, cov, lang, onTap, idx }) {
    const tt = (k, p) => MU.t(lang, k, p);
    const name = cat["name_" + lang];
    const isExpired = cov.status === "expired";
    const isMfr = cat.special === "mfr";
    let big, small;
    if (isExpired) { big = Math.abs(cov.daysLeft); small = MU.tn(lang, "expired_ago", Math.abs(cov.daysLeft)).replace(String(Math.abs(cov.daysLeft)), "").trim() || tt("status_expired"); }
    else { big = cov.daysLeft; small = lang === "es" ? "días" : "days"; }
    return e("button", { className: "mu-card", onClick: onTap, style: {
      textAlign: "left", padding: 14, display: "flex", flexDirection: "column", gap: 11, cursor: "pointer", minWidth: 0,
    } },
      e("div", { style: { display: "flex", alignItems: "center", gap: 9 } },
        e("div", { className: "mu-cat-ic", style: { width: 34, height: 34, background: MU.STATUS_SOFT[cov.status], color: MU.STATUS_COLOR[cov.status] } },
          e(MU.Icon, { name: cat.icon, size: 19, stroke: 1.8 })),
        e("div", { style: { fontWeight: 700, fontSize: 14, lineHeight: 1.15, letterSpacing: "-.01em" } }, name)
      ),
      e("div", { style: { display: "flex", justifyContent: "center", padding: "2px 0" } },
        e(MU.Ring, { fraction: isMfr ? 1 : cov.fraction, status: cov.status, size: 96, sw: 7, delay: idx * 70 },
          isMfr
            ? e("div", { style: { textAlign: "center" } }, e(MU.Icon, { name: "appliance", size: 22, color: "var(--active)" }), e("div", { style: { fontSize: 10.5, color: "var(--ink-3)", marginTop: 2, fontWeight: 600 } }, lang === "es" ? "Fabricante" : "Mfr"))
            : e("div", { style: { textAlign: "center" } },
              e("div", { className: "tnum", style: { fontFamily: "var(--display)", fontSize: 27, fontWeight: 800, letterSpacing: "-.03em", color: isExpired ? "var(--expired)" : "var(--ink)" } }, big),
              e("div", { style: { fontSize: 10.5, color: "var(--ink-3)", fontWeight: 600, marginTop: -1 } }, small)
            )
        )
      ),
      e("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6, flexWrap: "wrap", rowGap: 5 } },
        e(MU.StatusPill, { status: cov.status, small: true,
          label: cov.status === "crack" ? tt("crack_window_open") : tt("status_" + (cov.status === "soon" ? "soon" : cov.status === "active" ? "active" : "expired")) }),
        e("div", { style: { fontSize: 10.5, color: "var(--ink-4)", fontWeight: 600, textAlign: "right" } },
          (isExpired ? tt("expired_on", { date: "" }) : tt("expires_on", { date: "" })).replace("{date}", "").trim() + " " + MU.formatDateShort(cov.expiry, lang))
      )
    );
  }

  /* ---- timeline view ---- */
  function TimelineView({ cats, lang, handover, now }) {
    const tt = (k, p) => MU.t(lang, k, p);
    const minD = MU.startOfDay(handover);
    const maxEnd = cats.reduce((m, c) => Math.max(m, MU.addDays(handover, c.cat.durationDays).getTime()), minD.getTime());
    const span = Math.max(1, maxEnd - minD.getTime());
    const todayPct = Math.max(0, Math.min(100, ((MU.startOfDay(now) - minD) / span) * 100));
    return e("div", { className: "mu-card", style: { padding: "20px 16px 16px", position: "relative" } },
      e("div", { style: { position: "relative" } },
        // today line
        e("div", { style: { position: "absolute", top: -6, bottom: 8, left: todayPct + "%", width: 2, background: "var(--ink)", zIndex: 3 } },
          e("div", { style: { position: "absolute", top: -16, left: "50%", transform: "translateX(-50%)", background: "var(--ink)", color: "#fff", fontSize: 9.5, fontWeight: 800, letterSpacing: ".1em", padding: "2px 7px", borderRadius: 6, whiteSpace: "nowrap" } }, tt("today"))
        ),
        e("div", { style: { display: "flex", flexDirection: "column", gap: 12, paddingTop: 6 } },
          cats.map(({ cat, cov }, i) => {
            const endPct = Math.min(100, ((MU.addDays(handover, cat.durationDays) - minD) / span) * 100);
            const fillPct = Math.min(endPct, todayPct);
            return e("div", { key: cat.id },
              e("div", { style: { fontSize: 11.5, fontWeight: 600, color: "var(--ink-2)", marginBottom: 4 } }, cat["name_" + lang]),
              e("div", { style: { position: "relative", height: 9, background: "rgba(14,17,22,.05)", borderRadius: 9 } },
                e("div", { style: { position: "absolute", left: 0, height: "100%", borderRadius: 9, width: endPct + "%", background: MU.STATUS_SOFT[cov.status] } }),
                e("div", { style: { position: "absolute", left: 0, height: "100%", borderRadius: 9, width: fillPct + "%", background: MU.STATUS_COLOR[cov.status], transition: "width .8s cubic-bezier(.22,.8,.3,1)" } })
              )
            );
          })
        )
      )
    );
  }

  /* ---- pre-delivery construction timeline ---- */
  function PreDelivery({ unit, lang }) {
    const tt = (k, p) => MU.t(lang, k, p);
    const steps = MU.MILESTONES;
    const curIdx = steps.indexOf(unit.status);
    return e("div", { className: "mu-screen app-scroll", style: { overflowY: "auto", height: "100%" } },
      e("div", { style: { marginBottom: 16 } },
        e("div", { className: "mu-eyebrow" }, unit.projectName),
        e("h1", { className: "mu-h-title", style: { marginTop: 6 } }, tt("predelivery_title")),
        e("p", { className: "mu-sub", style: { marginTop: 6 } }, tt("predelivery_sub"))
      ),
      e(MU.Placeholder, { label: "render · " + unit.unitNumber, h: 150, style: { marginBottom: 16 } }),
      e("div", { className: "mu-card", style: { padding: 18 } },
        unit.estHandover && e("div", { style: { display: "flex", alignItems: "center", gap: 8, marginBottom: 18, padding: "10px 13px", background: "var(--brand-soft)", borderRadius: 12 } },
          e(MU.Icon, { name: "calendar", size: 17, color: "var(--brand)" }),
          e("div", null, e("div", { style: { fontSize: 11, color: "var(--ink-3)", fontWeight: 600 } }, tt("est_handover")), e("div", { style: { fontWeight: 700, color: "var(--brand-deep)" } }, unit.estHandover))
        ),
        steps.map((s, i) => {
          const done = i < curIdx, current = i === curIdx;
          return e("div", { key: s, style: { display: "flex", gap: 13, alignItems: "stretch" } },
            e("div", { style: { display: "flex", flexDirection: "column", alignItems: "center" } },
              e("div", { style: { width: 26, height: 26, borderRadius: 99, flex: "0 0 auto", display: "flex", alignItems: "center", justifyContent: "center", border: current ? "none" : "2px solid " + (done ? "var(--brand)" : "var(--line-2)"), background: done ? "var(--brand)" : current ? "var(--gold)" : "#fff", color: done || current ? "#fff" : "var(--ink-4)" } },
                done ? e(MU.Icon, { name: "check", size: 14, stroke: 2.4 }) : e("div", { style: { width: 7, height: 7, borderRadius: 9, background: current ? "#fff" : "var(--line-2)" } })),
              i < steps.length - 1 && e("div", { style: { width: 2, flex: 1, minHeight: 22, background: done ? "var(--brand)" : "var(--line)" } })
            ),
            e("div", { style: { paddingBottom: 18, paddingTop: 2 } },
              e("div", { style: { fontWeight: current ? 800 : 600, fontSize: 15, color: done ? "var(--ink-2)" : current ? "var(--ink)" : "var(--ink-4)" } }, tt("ms_" + s)),
              current && e("div", { style: { fontSize: 12.5, color: "var(--gold)", fontWeight: 700, marginTop: 2 } }, tt("current_stage"))
            )
          );
        })
      )
    );
  }

  /* ---- main Home ---- */
  function Home() {
    const app = window.MU.useApp();
    const { lang, unit, now } = app;
    const [view, setView] = useState("rings");
    const tt = (k, p) => MU.t(lang, k, p);

    const handover = MU.D(unit.handoverDate);
    const isPre = unit.status !== "delivered" || handover > now;
    const daysSince = Math.max(0, MU.daysBetween(handover, now));

    const cats = useMemo(() => {
      return MU.WARRANTY_CATEGORIES
        .filter((c) => c.special !== "routed")
        .map((cat) => ({ cat, cov: MU.computeCoverage(cat, handover, now) }))
        .sort((a, b) => {
          const order = (x) => x.cov.status === "expired" ? 1 : 0;
          if (order(a) !== order(b)) return order(a) - order(b);
          return a.cov.daysLeft - b.cov.daysLeft;
        });
    }, [unit.id, now.getTime()]);

    if (isPre) return e(PreDelivery, { unit, lang });

    const active = cats.filter((c) => c.cov.status !== "expired");
    const expired = cats.filter((c) => c.cov.status === "expired");
    const activeCount = cats.filter((c) => c.cov.status === "active" || c.cov.status === "soon" || c.cov.status === "crack").length;

    // crack-window banner
    const crackEntry = cats.find((c) => c.cat.special === "crack-window" && c.cov.status === "crack");
    const showCrack = crackEntry && crackEntry.cov.daysLeft <= 120;

    const openClaims = app.getUnitClaims().filter((c) => c.status !== "resolved").length;
    const careDone = MU.CARE_ITEMS.filter((c) => app.care[c.id]).length;

    return e("div", { className: "mu-screen app-scroll", style: { overflowY: "auto", height: "100%" } },
      /* HERO */
      e("div", { style: {
        borderRadius: 24, padding: "22px 20px 24px", marginBottom: 16, position: "relative", overflow: "hidden",
        background: "radial-gradient(120% 120% at 85% 0%, #2a8a72 0%, var(--brand) 42%, var(--brand-deep) 100%)",
        color: "#fff", boxShadow: "0 14px 40px rgba(19,75,62,.35)",
      } },
        e("div", { style: { position: "absolute", inset: 0, opacity: .14, background: "repeating-linear-gradient(115deg, #fff 0 1px, transparent 1px 26px)" } }),
        e("div", { style: { position: "relative" } },
          e("div", { className: "mu-eyebrow", style: { color: "rgba(255,255,255,.7)" } }, tt("warranties_active_n", { n: activeCount })),
          e("h1", { style: { fontSize: 28, fontWeight: 800, letterSpacing: "-.03em", lineHeight: 1.08, marginTop: 10, textWrap: "pretty" } },
            tmplNode(MU.tn(lang, "home_since_handover", daysSince, {}).replace(String(daysSince), "{n}"),
              e(MU.CountUp, { to: daysSince, className: "tnum", style: { color: "var(--gold)" } }))
          ),
          e("p", { style: { marginTop: 12, fontSize: 13, color: "rgba(255,255,255,.82)", display: "flex", alignItems: "center", gap: 7 } },
            e(MU.Icon, { name: "pin", size: 14, color: "rgba(255,255,255,.7)" }),
            tt("delivered_meta", { date: MU.formatDate(handover, lang), unit: "Apartamento " + unit.unitNumber + ", " + unit.projectName }))
        )
      ),

      /* CRACK WINDOW BANNER */
      showCrack && e("div", { style: {
        borderRadius: 18, padding: "15px 16px", marginBottom: 16, background: "var(--gold-soft)",
        border: "1px solid rgba(201,162,75,.4)", display: "flex", gap: 13, alignItems: "flex-start",
      } },
        e("div", { style: { width: 36, height: 36, borderRadius: 11, background: "var(--gold)", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" } },
          e(MU.Icon, { name: "crack", size: 19, stroke: 2 })),
        e("div", { style: { flex: 1 } },
          e("div", { style: { fontWeight: 800, fontSize: 14.5, color: "#6b5417", letterSpacing: "-.01em" } }, tt("crack_window_title")),
          e("p", { style: { fontSize: 12.5, color: "#7a6324", marginTop: 4, lineHeight: 1.45 } }, tt("crack_window_body", { n: crackEntry.cov.daysLeft })),
          e("button", { className: "mu-btn mu-btn-gold", style: { marginTop: 11, padding: "10px 15px", fontSize: 13.5 }, onClick: () => app.openReport({ issueId: "crack-hairline", crack: true }) },
            e(MU.Icon, { name: "crack", size: 16, stroke: 2 }), tt("crack_window_cta"))
        )
      ),

      /* QUICK ACTIONS */
      e("div", { style: { display: "grid", gridTemplateColumns: "1.4fr 1fr 1fr", gap: 9, marginBottom: 20 } },
        e("button", { className: "mu-btn mu-btn-primary", style: { flexDirection: "column", gap: 6, padding: "14px 8px", fontSize: 12.5 }, onClick: () => app.openReport(null) },
          e(MU.Icon, { name: "report", size: 20, stroke: 2.2 }), tt("qa_report")),
        e("button", { className: "mu-btn mu-btn-ghost", style: { flexDirection: "column", gap: 6, padding: "14px 6px", fontSize: 12, textAlign: "center", lineHeight: 1.2 }, onClick: () => app.setTab("warranties") },
          e(MU.Icon, { name: "shield", size: 20 }), tt("qa_warranties")),
        e("button", { className: "mu-btn mu-btn-ghost", style: { flexDirection: "column", gap: 6, padding: "14px 6px", fontSize: 12, textAlign: "center", lineHeight: 1.2 }, onClick: () => app.setTab("unit") },
          e(MU.Icon, { name: "doc", size: 20 }), tt("qa_docs"))
      ),

      /* VIEW TOGGLE */
      e("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 13, flexWrap: "wrap", gap: 10 } },
        e("div", { style: { fontWeight: 800, fontSize: 16, letterSpacing: "-.02em" } }, tt("nav_warranties")),
        e(MU.Segmented, {
          value: view, onChange: setView,
          options: [{ value: "rings", label: tt("view_rings"), icon: "grid" }, { value: "timeline", label: tt("view_timeline"), icon: "sliders" }],
        })
      ),

      view === "rings"
        ? e(React.Fragment, null,
          e("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(148px, 1fr))", gap: 11 } },
            active.map(({ cat, cov }, i) => e(RingCard, { key: cat.id, cat, cov, lang, idx: i, onTap: () => app.navigate({ tab: "warranties", cat: cat.id }) }))),
          expired.length > 0 && e(React.Fragment, null,
            e("div", { className: "mu-eyebrow", style: { margin: "20px 2px 11px", color: "var(--expired)" } }, tt("section_expired")),
            e("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(148px, 1fr))", gap: 11 } },
              expired.map(({ cat, cov }, i) => e(RingCard, { key: cat.id, cat, cov, lang, idx: i, onTap: () => app.navigate({ tab: "warranties", cat: cat.id }) })))
          )
        )
        : e(TimelineView, { cats, lang, handover, now }),

      /* HOME HEALTH */
      e("div", { className: "mu-card", style: { marginTop: 20, padding: 16, display: "flex", alignItems: "center", gap: 14 } },
        e("div", { style: { width: 46, height: 46, borderRadius: 14, background: "var(--brand-soft)", color: "var(--brand)", display: "flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" } },
          e(MU.Icon, { name: "spark", size: 22 })),
        e("div", { style: { flex: 1 } },
          e("div", { style: { fontWeight: 700, fontSize: 14.5 } }, tt("home_health")),
          e("div", { className: "mu-sub", style: { fontSize: 12.5, marginTop: 2 } }, tt("home_health_sub", { active: activeCount, open: openClaims, care: careDone }))
        )
      )
    );
  }

  MU.Home = Home;
})(window.MU);
