// dashboard.jsx — portal home
function Dashboard({ bookings, notices, currency, nav, accountName, runs, savedQuotes, onReopenQuote, accessLevel }) {
  const open = window.isOpenNow();
  const pinnedAnn = window.FX.activeAnnouncements(window.FX.loadAnnouncements()).filter(a => a.audience !== "Customer service team (internal)")[0];
  const pinned = pinnedAnn || notices.find(n => n.pinned) || notices[0];
  const recent = [
    ...(bookings || []).map(b => ({ id: b.tracking, from: b.pickup.suburb, to: b.dropoff.suburb, vehicleId: b.vehicleId, price: b.total, status: "In transit", date: b.date })),
    ...window.FX.HISTORY,
  ].slice(0, 5);

  const activeRuns = (runs || window.FX.DELIVERY_RUNS).filter(r => r.status !== "Completed").length;
  const stats = [
    { l: "Deliveries this week", v: String(6 + (bookings ? bookings.length : 0)), d: "+2 vs last week", icon: "package", tone: "var(--brand)" },
    { l: "Active runs", v: String(activeRuns), d: "On the road", icon: "navigation", tone: "var(--accent)" },
  ];
  const clerk = accessLevel === "clerk";
  const visibleStats = clerk ? stats.filter(s => s.l !== "Spend this month") : stats;
  const activeQuotes = (savedQuotes || []).filter(q => window.FX.quoteDaysLeft(q.expiresAt) > 0 && q.status !== "booked");

  const actions = [
    { id: "book", t: "Book a delivery", d: "Same-day pickup in 7 steps", icon: "plus", primary: true },
    { id: "createRun", t: "Create delivery run", d: "Plan a driver's stops", icon: "navigation" },
    { id: "quote", t: "Get a quote", d: "Instant price by suburb", icon: "calculator" },
  ];

  return (
    <div className="fade-up">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 20, flexWrap: "wrap", marginBottom: 24 }}>
        <div>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h1 style={{ margin: 0, fontSize: 30, fontWeight: 700, letterSpacing: "-0.8px", color: "var(--fg-strong)" }}>Good morning, {accountName || "Fedex Express"}</h1>
            <Badge tone={open ? "success" : "warn"}><StatusDot color={open ? "#22b86e" : "var(--warn)"} pulse={open} /> {open ? "Open now" : "Closed"}</Badge>
          </div>
          <p style={{ margin: "8px 0 0", fontSize: 15, color: "var(--fg-mute)" }}>Here's what's moving across your same-day network today.</p>
        </div>
        <Button variant="primary" size="lg" icon="plus" onClick={() => nav("book")}>New booking</Button>
      </div>

      {pinned && (
        <div style={{ display: "flex", gap: 13, alignItems: "center", padding: "14px 18px", borderRadius: "var(--r-lg)", background: "var(--brand)", color: "#fff", marginBottom: 22 }}>
          <Icon name="megaphone" size={19} style={{ flex: "none" }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <span style={{ fontWeight: 700, fontSize: 14 }}>{pinned.title}</span>
            <span style={{ fontSize: 13.5, opacity: 0.82, marginLeft: 8 }}>{pinned.body}</span>
          </div>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.6px", textTransform: "uppercase", opacity: 0.6, whiteSpace: "nowrap" }}>Fedex notice</span>
        </div>
      )}

      {/* quick actions */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16, marginBottom: 16 }}>
        {actions.map(a => (
          <Card key={a.id} hover onClick={() => nav(a.id)} pad={22} style={a.primary ? { background: "var(--accent-soft)", borderColor: "transparent" } : {}}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <span style={{ width: 48, height: 48, borderRadius: 13, flex: "none", display: "inline-flex", alignItems: "center", justifyContent: "center", background: a.primary ? "var(--accent)" : "var(--brand-soft)", color: a.primary ? "#fff" : "var(--brand)" }}>
                <Icon name={a.icon} size={23} />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 16, color: "var(--fg-strong)" }}>{a.t}</div>
                <div style={{ fontSize: 13, color: "var(--fg-mute)", marginTop: 2 }}>{a.d}</div>
              </div>
              <Icon name="arrow-right" size={18} color={a.primary ? "var(--accent-700)" : "var(--fg-faint)"} />
            </div>
          </Card>
        ))}
      </div>

      {/* stats */}
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${visibleStats.length},1fr)`, gap: 16, marginBottom: 24 }}>
        {visibleStats.map(s => (
          <Card key={s.l} pad={20}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, letterSpacing: "0.8px", textTransform: "uppercase", color: "var(--fg-mute)" }}>{s.l}</div>
              <Icon name={s.icon} size={17} color={s.tone} />
            </div>
            <div style={{ fontSize: 32, fontWeight: 900, letterSpacing: "-1px", color: "var(--fg-strong)", marginTop: 10 }}>{s.v}</div>
            <div style={{ fontSize: 12.5, color: "var(--fg-mute)", marginTop: 4 }}>{s.d}</div>
          </Card>
        ))}
      </div>

      {/* saved quotes (item 1 / 11) */}
      {activeQuotes.length > 0 && (
        <Card pad={0} style={{ overflow: "hidden", marginBottom: 24 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 22px", borderBottom: "1px solid var(--border)" }}>
            <span style={{ fontWeight: 700, fontSize: 15.5, color: "var(--fg-strong)" }}>Saved quotes <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, color: "var(--fg-mute)", fontWeight: 500 }}>· {activeQuotes.length}</span></span>
            <button onClick={() => nav("quote")} style={{ background: "transparent", border: "none", color: "var(--accent-700)", fontSize: 13, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 4 }}>New quote <Icon name="arrow-right" size={14} /></button>
          </div>
          {activeQuotes.map((q, i) => {
            const days = window.FX.quoteDaysLeft(q.expiresAt);
            const svc = window.FX.SERVICES.find(s => s.id === q.serviceId);
            return (
              <div key={q.no} style={{ display: "flex", alignItems: "center", gap: 14, padding: "14px 22px", borderTop: i ? "1px solid var(--border)" : "none" }}>
                <span style={{ width: 36, height: 36, borderRadius: 10, background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="calculator" size={17} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 700, color: "var(--brand)" }}>{q.no}</span>
                    <span style={{ fontSize: 13.5, fontWeight: 500, color: "var(--fg-strong)" }}>{q.from} → {q.to}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--fg-mute)", marginTop: 2 }}>{svc ? svc.name : ""}{q.km ? " · " + q.km + " km" : ""}</div>
                </div>
                <Badge tone={days <= 3 ? "warn" : "neutral"}><Icon name="clock" size={11} /> Valid {days} day{days === 1 ? "" : "s"}</Badge>
                <span style={{ fontWeight: 800, fontSize: 15, color: "var(--fg-strong)", width: 78, textAlign: "right" }}>{window.FX.money(q.total, currency)}</span>
                <Button variant="primary" size="sm" icon="plus" onClick={() => onReopenQuote && onReopenQuote(q)}>Book</Button>
              </div>
            );
          })}
        </Card>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.5fr) minmax(0,1fr)", gap: 16, alignItems: "start" }}>
        {/* recent */}
        <Card pad={0} style={{ overflow: "hidden" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 22px", borderBottom: "1px solid var(--border)" }}>
            <span style={{ fontWeight: 700, fontSize: 15.5, color: "var(--fg-strong)" }}>Recent deliveries</span>
            <button onClick={() => nav("history")} style={{ background: "transparent", border: "none", color: "var(--accent-700)", fontSize: 13, fontWeight: 500, display: "inline-flex", alignItems: "center", gap: 4 }}>View all <Icon name="arrow-right" size={14} /></button>
          </div>
          {recent.map((d, i) => {
            const v = window.FX.VEHICLES.find(x => x.id === d.vehicleId);
            const inTransit = d.status === "In transit";
            return (
              <div key={d.id + i} onClick={() => nav("history")} style={{ display: "flex", alignItems: "center", gap: 13, padding: "14px 22px", borderTop: i ? "1px solid var(--border)" : "none", cursor: "pointer" }}
                onMouseEnter={e => e.currentTarget.style.background = "var(--bg-mist)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                <span style={{ width: 36, height: 36, borderRadius: 10, background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={v ? v.icon : "package"} size={17} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 500, color: "var(--fg-strong)" }}>{d.from} → {d.to}</div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--fg-mute)" }}>{d.id}</div>
                </div>
                {inTransit && (
                  <a href={"Fedex Track.html#t=" + encodeURIComponent(d.id)} target="_blank" rel="noopener" onClick={e => e.stopPropagation()} style={{ textDecoration: "none", display: "inline-flex", alignItems: "center", gap: 5, fontSize: 12, fontWeight: 500, color: "var(--accent-700)" }}>
                    <Icon name="external-link" size={13} /> Track
                  </a>
                )}
                <Badge tone={d.status === "Delivered" ? "success" : "brand"}><StatusDot color={d.status === "Delivered" ? "#22b86e" : "var(--brand)"} pulse={inTransit} /> {d.status}</Badge>
                <span style={{ fontWeight: 700, fontSize: 14, color: "var(--fg-strong)", width: 72, textAlign: "right" }}>{window.FX.money(d.price, currency)}</span>
              </div>
            );
          })}
        </Card>

        {/* runs + support */}
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card pad={20} hover onClick={() => nav("manageRuns")}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <span style={{ fontWeight: 700, fontSize: 14.5, color: "var(--fg-strong)" }}>Delivery runs</span>
              <Badge tone="brand">{activeRuns} active</Badge>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {(runs || window.FX.DELIVERY_RUNS).filter(r => r.status !== "Completed").slice(0, 3).map(r => {
                const dr = window.FX.DRIVERS.find(d => d.id === r.driverId);
                const pr = window.FX.runProgress(r);
                return (
                  <div key={r.id} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <span style={{ width: 30, height: 30, borderRadius: "50%", background: dr ? "var(--brand)" : "var(--bg-mist-2)", color: dr ? "#fff" : "var(--fg-mute)", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 700, fontSize: 11, flex: "none" }}>{dr ? dr.initials : "–"}</span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.name}</div>
                      <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--fg-mute)" }}>{dr ? dr.name.split(/\s+/)[0] : "Unassigned"} · {pr.done}/{pr.total}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>
          <Card pad={20}>
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <span style={{ width: 40, height: 40, borderRadius: 10, background: "var(--brand-soft)", color: "var(--brand)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="headset" size={20} /></span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, fontSize: 14, color: "var(--fg-strong)" }}>Need a hand?</div>
                <a href="tel:1300131150" style={{ fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--brand)", textDecoration: "none" }}>1300 131 150</a>
              </div>
              <Button variant="secondary" size="sm" onClick={() => nav("contact")}>Contact</Button>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
