// Mobile version — 390x844 (iPhone 14 size).
// Stacked vertically, scrollable. Reuses shared components.

function DashboardMobile({ tweaks }) {
  const D = window.DASHBOARD_DATA;
  const Avatar = window.ChatwootAvatar;
  const StatusPill = window.ChatwootStatusPill;
  const PriorityDot = window.ChatwootPriorityDot;
  const ChannelIcon = window.ChatwootChannelIcon;
  const Spark = window.ChatwootSpark;

  const t = tweaks || { dark: true, density: "regular", accent: "#1F93FF" };
  const dark = t.dark !== false;
  const accent = t.accent || "#1F93FF";

  const C = dark
    ? { bg: "#0B1220", surface: "#111827", surface2: "#1F2937", surface3: "#374151", border: "#1F2937", borderSoft: "#1A2233", text: "#F1F5F9", textDim: "#CBD5E1", textMuted: "#94A3B8" }
    : { bg: "#F9FAFB", surface: "#FFFFFF", surface2: "#F3F4F6", surface3: "#E5E7EB", border: "#E5E7EB", borderSoft: "#F3F4F6", text: "#0F172A", textDim: "#334155", textMuted: "#64748B" };

  const card = {
    background: C.surface,
    border: `1px solid ${C.border}`,
    borderRadius: 14,
    overflow: "hidden",
  };

  const kpis = [
    { label: "Unassigned",    val: D.stats.unassigned,  color: "#F87171", trend: "+3" },
    { label: "Today",         val: D.stats.today,       color: accent,    trend: "+12%" },
    { label: "In Progress",   val: D.stats.inProgress,  color: "#FBBF24", trend: "0" },
    { label: "Closed",        val: D.stats.closed,      color: "#34D399", trend: "+18" },
    { label: "Response Time", val: D.stats.avgResponse, color: "#22D3EE", trend: "\u221222s" },
  ];

  return (
    <div style={{
      width: 390, height: 844, background: C.bg, color: C.text,
      fontFamily: "'Inter', system-ui, -apple-system, sans-serif",
      display: "flex", flexDirection: "column", overflow: "hidden",
      "--c-surface": C.surface,
    }}>
      {/* iOS-ish status bar */}
      <div style={{ height: 44, padding: "0 24px", display: "flex", alignItems: "center", justifyContent: "space-between", fontSize: 13, fontWeight: 700, color: C.text, flexShrink: 0 }}>
        <span>9:41</span>
        <div style={{ display: "flex", alignItems: "center", gap: 5 }}>
          <svg width="16" height="11" viewBox="0 0 16 11" fill="currentColor"><rect y="6" width="3" height="5" rx="0.5"/><rect x="4" y="4" width="3" height="7" rx="0.5"/><rect x="8" y="2" width="3" height="9" rx="0.5"/><rect x="12" width="3" height="11" rx="0.5"/></svg>
          <svg width="22" height="11" viewBox="0 0 22 11" fill="none" stroke="currentColor" strokeWidth="1"><rect x="0.5" y="0.5" width="18" height="10" rx="2.5"/><rect x="2" y="2" width="14" height="7" rx="1" fill="currentColor"/><rect x="19.5" y="3.5" width="1.5" height="4" rx="0.5" fill="currentColor"/></svg>
        </div>
      </div>

      {/* Header */}
      <div style={{ padding: "8px 20px 16px", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ width: 38, height: 38, borderRadius: 11, background: `linear-gradient(135deg, ${accent}, ${shift(accent, -18)})`, display: "flex", alignItems: "center", justifyContent: "center", boxShadow: `0 6px 18px ${accent}50` }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d="M12 2C6.5 2 2 6.5 2 12c0 1.7.4 3.3 1.2 4.7L2 22l5.4-1.2C8.8 21.6 10.4 22 12 22c5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
          </div>
          <div>
            <div style={{ fontSize: 17, fontWeight: 800, color: C.text, letterSpacing: -0.4, lineHeight: 1.1 }}>Dashboard</div>
            <div style={{ fontSize: 11, color: C.textMuted, fontWeight: 500 }}>Senin · 19 Mei 2026</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <div style={{ position: "relative", width: 36, height: 36, background: C.surface, border: `1px solid ${C.border}`, borderRadius: 10, display: "flex", alignItems: "center", justifyContent: "center", color: C.textDim }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/></svg>
            <span style={{ position: "absolute", top: 7, right: 8, width: 7, height: 7, borderRadius: 999, background: "#EF4444", border: `2px solid ${C.bg}` }}></span>
          </div>
          <Avatar initials="MH" color="#A78BFA" online={true} size={36} />
        </div>
      </div>

      {/* Scroll body */}
      <div style={{ flex: 1, overflow: "auto", padding: "0 16px 24px", display: "flex", flexDirection: "column", gap: 14 }}>
        {/* KPI strip — 2x2 + full-width Response Time */}
        <div style={{ ...card, padding: 0, display: "grid", gridTemplateColumns: "1fr 1fr" }}>
          {kpis.map((k, i) => {
            const isLast = i === kpis.length - 1;
            return (
              <div key={i} style={{
                gridColumn: isLast ? "1 / -1" : "auto",
                padding: "14px 16px",
                borderRight: !isLast && i % 2 === 0 ? `1px solid ${C.borderSoft}` : "none",
                borderTop: i >= 2 ? `1px solid ${C.borderSoft}` : "none",
                display: "flex",
                flexDirection: isLast ? "row" : "column",
                alignItems: isLast ? "center" : "stretch",
                justifyContent: isLast ? "space-between" : "flex-start",
                gap: isLast ? 12 : 6,
              }}>
                {isLast ? (
                  <React.Fragment>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <span style={{ width: 7, height: 7, borderRadius: 999, background: k.color }}></span>
                      <div>
                        <div style={{ fontSize: 11, fontWeight: 600, color: C.textMuted, letterSpacing: 0.2 }}>{k.label}</div>
                        <div style={{ fontSize: 10.5, color: C.textMuted, marginTop: 1 }}>target ≤ 5m</div>
                      </div>
                    </div>
                    <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                      <div style={{ fontSize: 22, fontWeight: 800, color: C.text, letterSpacing: -0.8, lineHeight: 1 }}>{k.val}</div>
                      <div style={{ fontSize: 10, fontWeight: 700, color: k.color, padding: "2px 7px", background: k.color + "22", borderRadius: 999 }}>{k.trend}</div>
                    </div>
                  </React.Fragment>
                ) : (
                  <React.Fragment>
                    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <span style={{ width: 7, height: 7, borderRadius: 999, background: k.color }}></span>
                      <span style={{ fontSize: 11, fontWeight: 600, color: C.textMuted, letterSpacing: 0.2 }}>{k.label}</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
                      <div style={{ fontSize: 26, fontWeight: 800, color: C.text, letterSpacing: -1, lineHeight: 1 }}>{k.val}</div>
                      <div style={{ fontSize: 10, fontWeight: 700, color: k.color }}>{k.trend}</div>
                    </div>
                  </React.Fragment>
                )}
              </div>
            );
          })}
        </div>

        {/* Running Tickets */}
        <div style={card}>
          <div style={{ padding: "14px 16px 8px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: C.text, letterSpacing: -0.1 }}>Tiket Berjalan</div>
              <div style={{ fontSize: 11, color: C.textMuted, marginTop: 1 }}>{D.running.length} aktif</div>
            </div>
            <span style={{ fontSize: 11, color: accent, fontWeight: 700 }}>Lihat semua →</span>
          </div>
          {D.running.slice(0, 4).map((r, i) => {
            const ag = D.agents.find((a) => a.name === r.agent) || {};
            return (
              <div key={r.no} style={{ padding: "11px 16px", display: "flex", alignItems: "center", gap: 10, borderTop: `1px solid ${C.borderSoft}` }}>
                <Avatar initials={r.agentInit} color={ag.color || "#94A3B8"} online={ag.online} size={32} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", fontSize: 10.5, fontWeight: 700, color: accent }}>{r.ticket}</span>
                    <span style={{ fontSize: 10, color: C.textMuted }}>·</span>
                    <span style={{ fontSize: 10.5, color: C.textMuted, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.agent}</span>
                  </div>
                  <div style={{ fontSize: 12.5, color: C.text, fontWeight: 500, marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.subject}</div>
                </div>
                <StatusPill status={r.status} />
              </div>
            );
          })}
        </div>

        {/* Issues per Agent */}
        <div style={card}>
          <div style={{ padding: "14px 16px 8px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 700, color: C.text, letterSpacing: -0.1 }}>Issue per Agent</div>
              <div style={{ fontSize: 11, color: C.textMuted, marginTop: 1 }}>{D.agents.reduce((a,b)=>a+b.taken,0)} total hari ini</div>
            </div>
          </div>
          {[...D.agents].sort((a,b)=>b.taken-a.taken).slice(0, 5).map((a, i) => {
            const max = Math.max(...D.agents.map((x) => x.taken));
            const pct = (a.taken / max) * 100;
            return (
              <div key={i} style={{ padding: "10px 16px", display: "flex", alignItems: "center", gap: 10, borderTop: `1px solid ${C.borderSoft}` }}>
                <span style={{ fontSize: 10.5, fontWeight: 700, color: i < 3 ? accent : C.textMuted, width: 14 }}>#{i+1}</span>
                <Avatar initials={a.initials} color={a.color} online={a.online} size={28} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <div style={{ fontSize: 12, fontWeight: 600, color: C.text, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name.split(" ")[0]}</div>
                    <div style={{ fontSize: 12.5, fontWeight: 800, color: C.text }}>{a.taken}</div>
                  </div>
                  <div style={{ height: 3, background: C.surface2, borderRadius: 999, marginTop: 4, overflow: "hidden" }}>
                    <div style={{ width: pct + "%", height: "100%", background: `linear-gradient(90deg, ${a.color}, ${a.color}aa)`, borderRadius: 999 }}></div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Unassigned */}
        <div style={{ ...card, borderColor: "#EF444433" }}>
          <div style={{ padding: "14px 16px 8px", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <div style={{ width: 26, height: 26, borderRadius: 8, background: "#EF444422", display: "flex", alignItems: "center", justifyContent: "center" }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#F87171" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              </div>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: C.text, letterSpacing: -0.1 }}>Belum Di-Assign</div>
                <div style={{ fontSize: 11, color: C.textMuted, marginTop: 1 }}>{D.unassigned.length} menunggu</div>
              </div>
            </div>
            <button style={{ padding: "5px 11px", fontSize: 11, fontWeight: 700, color: "white", background: "#EF4444", border: "none", borderRadius: 7 }}>Assign</button>
          </div>
          {D.unassigned.slice(0, 3).map((u, i) => (
            <div key={u.id} style={{ padding: "10px 16px", display: "flex", alignItems: "center", gap: 10, borderTop: `1px solid ${C.borderSoft}` }}>
              <PriorityDot p={u.priority} />
              <div style={{ width: 26, height: 26, borderRadius: 7, background: C.surface2, display: "flex", alignItems: "center", justifyContent: "center", color: C.textDim }}><ChannelIcon channel={u.channel} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, color: C.text, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{u.subject}</div>
                <div style={{ fontSize: 10.5, color: C.textMuted, marginTop: 1 }}>{u.customer} · {u.age}</div>
              </div>
            </div>
          ))}
        </div>

      </div>

      {/* Bottom tab bar */}
      <div style={{ borderTop: `1px solid ${C.border}`, background: C.surface, padding: "8px 16px 28px", flexShrink: 0, display: "flex", justifyContent: "space-around" }}>
        {[
          { l: "Dashboard", active: true, href: "/",  i: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg> },
          { l: "Reports",   active: false, href: "/report-agent", i: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="M7 14l3-3 3 3 5-5"/></svg> },
        ].map((tab, i) => (
          <button key={i} onClick={() => { window.top.location.href = tab.href; }} style={{ position: "relative", display: "flex", flexDirection: "column", alignItems: "center", gap: 3, color: tab.active ? accent : C.textMuted, padding: "4px 10px", background: "transparent", border: "none" }}>
            {tab.i}
            <span style={{ fontSize: 10, fontWeight: 600 }}>{tab.l}</span>
            {tab.badge && <span style={{ position: "absolute", top: 0, right: 0, fontSize: 9, fontWeight: 700, padding: "1px 5px", background: "#EF4444", color: "white", borderRadius: 999, lineHeight: 1.3 }}>{tab.badge}</span>}
          </button>
        ))}
      </div>
    </div>
  );
}

function shift(hex, pct) {
  const h = hex.replace("#", "");
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  const f = (c) => Math.max(0, Math.min(255, Math.round(c + (pct / 100) * 255)));
  return `#${[f(r), f(g), f(b)].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
}

Object.assign(window, { DashboardMobile });
