// Dashboard — all-in-one overview
function timeAgo(iso, lang) {
  if (!iso) return "";
  const ms = Date.now() - new Date(iso).getTime();
  if (ms < 0) return lang === "es" ? "ahora" : "now";
  const sec = Math.floor(ms / 1000);
  if (sec < 60) return lang === "es" ? "hace un momento" : "just now";
  const min = Math.floor(sec / 60);
  if (min < 60) return lang === "es" ? `hace ${min} min` : `${min}m ago`;
  const hr  = Math.floor(min / 60);
  if (hr < 24)  return lang === "es" ? `hace ${hr} h`   : `${hr}h ago`;
  const day = Math.floor(hr / 24);
  if (day < 30) return lang === "es" ? `hace ${day} d`  : `${day}d ago`;
  const mo  = Math.floor(day / 30);
  if (mo < 12)  return lang === "es" ? `hace ${mo} mes` : `${mo}mo ago`;
  return new Date(iso).toLocaleDateString();
}

function actorDisplay(activity, t) {
  // System actor → translate to localized name; real users render as "you" if matches current user, else their name.
  if (activity.actorInitials === "SYS") return t("system") || "Sistema";
  return activity.actorName;
}

window.DashboardScreen = function DashboardScreen({ t, lang, subTab, setSubTab, setActive }) {
  const sub = subTab || "overview";
  const greeting = (() => {
    const h = new Date().getHours();
    if (h < 12) return t("good_morning");
    if (h < 19) return t("good_afternoon");
    return t("good_evening");
  })();

  // Recent invoices + clients (for name lookup) — fetched together once on mount.
  const [recentInvoices, setRecentInvoices] = React.useState([]);
  const [clientsById, setClientsById] = React.useState({});
  React.useEffect(() => {
    if (sub !== "overview") return;
    let cancelled = false;
    Promise.all([window.api.invoices.list(), window.api.clients.list()])
      .then(([invoices, clients]) => {
        if (cancelled) return;
        setRecentInvoices(invoices.slice(0, 5));
        setClientsById(Object.fromEntries(clients.map(c => [c.id, c])));
      })
      .catch(() => { /* silent — empty state covers it */ });
    return () => { cancelled = true; };
  }, [sub]);
  const Icons = window.Icons;
  const STATUS_TO_STR = { 1: "draft", 2: "pending", 3: "paid", 4: "overdue", 5: "cancelled" };
  const currencySymbol = c => c === "USD" ? "$" : c === "GBP" ? "£" : "€";

  // Activity from API. Overview fetches latest 5; full sub-tab fetches paged history.
  const [activities, setActivities] = React.useState([]);
  const [activityLoading, setActivityLoading] = React.useState(true);
  const [activityError, setActivityError] = React.useState(null);
  React.useEffect(() => {
    if (sub !== "overview" && sub !== "activity") return;
    let cancelled = false;
    setActivityLoading(true);
    const limit = sub === "activity" ? 100 : 5;
    window.api.activity.recent(limit)
      .then(items => { if (!cancelled) { setActivities(items); setActivityError(null); } })
      .catch(err => { if (!cancelled) setActivityError(err.message); })
      .finally(() => { if (!cancelled) setActivityLoading(false); });
    return () => { cancelled = true; };
  }, [sub]);

  // Modules grid. Counts in `meta` will come from a dashboard KPI endpoint
  // once it's built (TODO.md). For now the meta is empty for active modules.
  const modules = [
    { id: "fiscal", icon: "FileText", title: t("fiscal"), meta: "", tone: "active" },
    { id: "alerts", icon: "Bell",     title: t("alerts"), meta: "", tone: "active" },
    { id: "docs",   icon: "Book",     title: t("docs"),   meta: "", tone: "active" },
    { id: "drive",  icon: "Folder",   title: t("drive"),  meta: "", tone: "active" },
    { id: "tasks",  icon: "CheckSquare", title: t("tasks"), meta: "", tone: "active" },
    { id: "chat",   icon: "Chat",     title: t("chat"),   meta: t("coming_soon"), tone: "soon" },
    { id: "social", icon: "Hash",     title: t("social"), meta: t("coming_soon"), tone: "soon" },
    { id: "servers", icon: "Server",  title: t("servers"), meta: t("coming_soon"), tone: "soon" },
  ];

  return (
    <div className="page">
      <window.PageHeader
        title={greeting}
        subtitle={t("dash_subtitle")}
        actions={
          <>
            <window.Btn variant="ghost" icon={Icons.Download} onClick={() => setActive && setActive("fiscal")}>{t("export")}</window.Btn>
            <window.Btn variant="brand" icon={Icons.Plus} onClick={() => setActive && setActive("fiscal")}>{t("new_invoice")}</window.Btn>
          </>
        }
      />

      {/* KPIs are placeholders until a dashboard KPI endpoint exists.
          See TODO.md ("Dashboard KPIs and modules — derived data"). */}
      <div className="stat-grid stag">
        <div onClick={() => setActive && setActive("fiscal")} style={{ cursor: "pointer" }}>
          <window.Stat label={t("billed")} value="—" icon={Icons.TrendUp} tone="brand" t={t} />
        </div>
        <div onClick={() => setActive && setActive("fiscal")} style={{ cursor: "pointer" }}>
          <window.Stat label={t("total_invoices")} value="—" icon={Icons.FileText} tone="blue" t={t} />
        </div>
        <div onClick={() => setActive && setActive("fiscal")} style={{ cursor: "pointer" }}>
          <window.Stat label={t("pending_amount")} value="—" icon={Icons.Clock} tone="amber" t={t} />
        </div>
        <div onClick={() => setActive && setActive("fiscal")} style={{ cursor: "pointer" }}>
          <window.Stat label={t("active_clients")} value="—" icon={Icons.Users} tone="green" t={t} />
        </div>
      </div>

      {sub === "performance" && (
        <div className="card" style={{ marginBottom: 16 }}>
          <div className="card-header"><h3>{lang === "es" ? "Rendimiento mensual" : "Monthly performance"}</h3></div>
          <div style={{ padding: 24 }}>
            <BigChart lang={lang} />
          </div>
        </div>
      )}

      {sub === "calendar" && (
        <div className="card" style={{ padding: 48, textAlign: "center", marginBottom: 16 }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>
            {lang === "es" ? "Próximos eventos" : "Upcoming events"}
          </div>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)", maxWidth: 480, margin: "0 auto", lineHeight: 1.6 }}>
            {t("coming_soon_sub")}
          </div>
        </div>
      )}

      {(sub === "overview" || sub === "activity") && (
      <div style={{ display: "grid", gridTemplateColumns: sub === "activity" ? "1fr" : "1fr 320px", gap: 16, marginBottom: 16 }}>
        {sub !== "activity" && (
        <div className="card">
          <div className="card-header">
            <h3>{t("recent_invoices")}</h3>
            <button className="btn ghost sm" onClick={() => setActive && setActive("fiscal")}>{t("view_all")} →</button>
          </div>
          <table className="tbl">
            <thead>
              <tr>
                <th>{t("number")}</th>
                <th>{t("date")}</th>
                <th>{t("client")}</th>
                <th>{t("status")}</th>
                <th className="right">{t("total")}</th>
              </tr>
            </thead>
            <tbody>
              {recentInvoices.length === 0 && (
                <tr><td colSpan={5} style={{ textAlign: "center", padding: 24, color: "var(--text-muted)", fontSize: 12 }}>
                  {lang === "es" ? "Aún no hay facturas." : "No invoices yet."}
                </td></tr>
              )}
              {recentInvoices.map((inv) => (
                <tr key={inv.id}>
                  <td className="mono" style={{ color: "var(--brand)", fontWeight: 500 }}>#{inv.number}</td>
                  <td className="num" style={{ color: "var(--text-muted)" }}>{inv.issueDate}</td>
                  <td>{clientsById[inv.clientId]?.name || "—"}</td>
                  <td><window.StatusBadge status={STATUS_TO_STR[inv.status] || "?"} t={t} /></td>
                  <td className="right num" style={{ fontWeight: 600 }}>{currencySymbol(inv.currency)}{window.formatAmount(inv.total)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        )}

        <div
          className="card"
          onClick={sub !== "activity" && setSubTab ? () => setSubTab("activity") : undefined}
          style={sub !== "activity" ? { cursor: "pointer" } : undefined}
          title={sub !== "activity" ? t("view_all") : undefined}
        >
          <div className="card-header">
            <h3>{t("activity")}</h3>
            {sub !== "activity" && (
              <button
                className="btn ghost sm"
                onClick={(e) => { e.stopPropagation(); setSubTab && setSubTab("activity"); }}
              >
                {t("view_all")} →
              </button>
            )}
          </div>
          <div style={{ padding: "8px 0" }}>
            {activityLoading && activities.length === 0 && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--text-muted)", fontSize: 12.5 }}>Cargando…</div>
            )}
            {activityError && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--danger)", fontSize: 12.5 }}>{activityError}</div>
            )}
            {!activityLoading && !activityError && activities.length === 0 && (
              <div style={{ padding: 24, textAlign: "center", color: "var(--text-muted)", fontSize: 12.5 }}>{t("activity_empty")}</div>
            )}
            {!activityError && activities.map((a) => {
              const verb = t(`act.${a.action}`);
              const verbDisplay = verb === `act.${a.action}` ? a.action : verb; // fallback: raw code if not translated
              return (
                <div key={a.id} style={{ display: "flex", gap: 10, padding: "8px 16px", alignItems: "flex-start" }}>
                  <window.Avatar initials={a.actorInitials} size="sm" />
                  <div style={{ flex: 1, fontSize: 12.5, lineHeight: 1.5 }}>
                    <div>
                      <span style={{ fontWeight: 500 }}>{actorDisplay(a, t)}</span>{" "}
                      <span style={{ color: "var(--text-muted)" }}>{verbDisplay}</span>{" "}
                      {a.targetLabel && <span className="mono" style={{ color: "var(--text)" }}>{a.targetLabel}</span>}
                    </div>
                    <div style={{ color: "var(--text-faint)", fontSize: 11, marginTop: 2 }}>{timeAgo(a.occurredAt, lang)}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
      )}

      {sub === "overview" && (
        <>
      <div style={{ marginBottom: 12, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0, letterSpacing: "-0.01em" }}>{t("your_modules")}</h3>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }} className="stag">
        {modules.map((m) => {
          const Icon = Icons[m.icon];
          const isSoon = m.tone === "soon";
          return (
            <div key={m.id} className="feat" onClick={() => setActive && setActive(m.id)} style={{ cursor: "pointer", opacity: isSoon ? 0.85 : 1, transition: "border-color 150ms, transform 150ms" }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--border-strong)"}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--border)"}
            >
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
                <div className="feat-icon"><Icon /></div>
                {isSoon && <span className="soon-tag">{t("soon")}</span>}
              </div>
              <h4>{m.title}</h4>
              <p>{m.meta}</p>
            </div>
          );
        })}
      </div>
        </>
      )}
    </div>
  );
};

// Simple bar chart for "performance" sub-tab
function BigChart({ lang }) {
  const data = [42, 58, 49, 73, 64, 88, 95, 82, 110, 96, 124, 140];
  const max = Math.max(...data);
  const labels = lang === "es"
    ? ["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"]
    : ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  return (
    <div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height: 180, padding: "8px 0" }}>
        {data.map((v, i) => (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
            <div style={{ flex: 1, width: "100%", display: "flex", alignItems: "flex-end" }}>
              <div style={{
                width: "100%",
                height: `${(v / max) * 100}%`,
                background: i === data.length - 1 ? "var(--brand)" : "var(--bg-active)",
                borderRadius: "3px 3px 0 0",
                transition: "height 400ms cubic-bezier(.2,.8,.2,1)",
                animation: "stagIn 320ms cubic-bezier(.2,.8,.2,1) both",
                animationDelay: `${i * 30}ms`,
              }} />
            </div>
            <span style={{ fontSize: 10, color: "var(--text-faint)", fontFamily: "var(--font-mono)" }}>{labels[i]}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { DashboardScreen: window.DashboardScreen });
