// Dashboard view — operator cockpit
const { ACTIVITY, DELINQUENTS, BOOKINGS, AI_NUDGES, UNITS } = window.VAULT_DATA;

// Tiny inline sparkline
const Sparkline = ({ data, color = "var(--accent-400)", w = 90, h = 24, fill = true }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const span = max - min || 1;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / span) * (h - 4) - 2;
    return [x, y];
  });
  const path = pts.map(([x, y], i) => `${i === 0 ? "M" : "L"}${x.toFixed(1)} ${y.toFixed(1)}`).join(" ");
  const area = `${path} L${w} ${h} L0 ${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: "block" }}>
      {fill && (
        <>
          <defs>
            <linearGradient id={`spark-${color}`} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0" stopColor={color} stopOpacity="0.3" />
              <stop offset="1" stopColor={color} stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d={area} fill={`url(#spark-${color})`} />
        </>
      )}
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
};

const KPI = ({ label, val, unit, delta, deltaTone, trend, trendColor, tag }) => (
  <div className="kpi">
    {tag && <div className="kpi-tag">{tag}</div>}
    <div className="kpi-label">{label}</div>
    <div className="kpi-val">
      <span className="tnum">{val}</span>
      {unit && <span className="unit">{unit}</span>}
    </div>
    {delta != null && (
      <div className={`kpi-delta ${deltaTone}`}>
        <Icon name={deltaTone === "up" ? "trend-up" : "trend-down"} size={11} stroke={2} />
        {delta}
      </div>
    )}
    {trend && <div className="kpi-spark"><Sparkline data={trend} color={trendColor || "var(--accent-400)"} w={80} h={28} /></div>}
  </div>
);

const ActivityIcon = ({ type }) => {
  const map = {
    "gate-in":  { i: "gate",   tone: "info" },
    "gate-out": { i: "gate",   tone: "info" },
    "payment":  { i: "billing",tone: "ok"   },
    "alarm":    { i: "alert",  tone: "bad"  },
    "move-in":  { i: "key",    tone: "ok"   },
    "move-out": { i: "door",   tone: "info" },
    "delinq":   { i: "alert",  tone: "bad"  },
    "lock":     { i: "lock",   tone: "warn" },
    "ai":       { i: "ai",     tone: "violet" },
  };
  const m = map[type] || map["gate-in"];
  const colors = {
    info: "var(--info)", ok: "var(--ok)", bad: "var(--bad)",
    warn: "var(--warn)", violet: "var(--violet)"
  };
  return (
    <div style={{
      width: 26, height: 26, borderRadius: 7,
      background: `color-mix(in oklab, ${colors[m.tone]} 18%, transparent)`,
      color: colors[m.tone],
      display: "grid", placeItems: "center",
      flexShrink: 0,
    }}>
      <Icon name={m.i} size={13} stroke={1.8} />
    </div>
  );
};

const ActivityFeed = ({ items, onSelectUnit }) => (
  <div style={{ display: "flex", flexDirection: "column" }}>
    {items.map((a, i) => (
      <div key={i} style={{
        display: "flex", gap: 10, alignItems: "flex-start",
        padding: "8px 4px", borderBottom: "1px solid var(--line-1)",
      }}>
        <ActivityIcon type={a.type} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", gap: 6, alignItems: "baseline", flexWrap: "wrap" }}>
            <span style={{ fontWeight: 500, fontSize: 12.5 }}>{a.actor}</span>
            {a.unit && (
              <span
                onClick={() => onSelectUnit && onSelectUnit(a.unit)}
                className="mono"
                style={{
                  fontSize: 11, color: "var(--tx-2)",
                  background: "var(--bg-3)", padding: "0 5px", borderRadius: 4,
                  cursor: onSelectUnit ? "pointer" : "default",
                }}
              >{a.unit}</span>
            )}
            <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--tx-3)" }} className="mono">{a.t}</span>
          </div>
          <div style={{ fontSize: 12, color: "var(--tx-2)", marginTop: 1 }}>{a.note}</div>
        </div>
      </div>
    ))}
  </div>
);

// Donut for occupancy
const Donut = ({ pct, size = 96, color = "var(--accent-500)", label, sub }) => {
  const r = size / 2 - 8, c = 2 * Math.PI * r;
  const off = c * (1 - pct / 100);
  return (
    <div style={{ position: "relative", width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={size/2} cy={size/2} r={r} stroke="var(--bg-3)" strokeWidth="6" fill="none" />
        <circle cx={size/2} cy={size/2} r={r} stroke={color} strokeWidth="6" fill="none"
          strokeDasharray={c} strokeDashoffset={off} strokeLinecap="round"
          style={{ transition: "stroke-dashoffset 600ms var(--ease)" }} />
      </svg>
      <div style={{
        position: "absolute", inset: 0, display: "flex", flexDirection: "column",
        alignItems: "center", justifyContent: "center"
      }}>
        <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.02em" }} className="tnum">
          {pct}<span style={{ fontSize: 11, color: "var(--tx-3)" }}>%</span>
        </div>
        {sub && <div style={{ fontSize: 10, color: "var(--tx-3)", marginTop: -2 }}>{sub}</div>}
      </div>
    </div>
  );
};

// Hourly gate activity bars
const GateBars = ({ data, height = 64 }) => {
  const max = Math.max(...data);
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 3, height }}>
      {data.map((v, i) => (
        <div key={i} style={{
          flex: 1,
          height: `${(v/max) * 100}%`,
          background: i === data.length - 1 ? "var(--accent-500)" : "var(--bg-4)",
          borderRadius: 2,
          minHeight: 2,
          transition: "all 200ms var(--ease)"
        }} title={`${i}:00 — ${v} events`} />
      ))}
    </div>
  );
};

const AINudge = ({ nudge, onAct }) => {
  const colorMap = {
    pricing:  "var(--violet)",
    vacancy:  "var(--info)",
    ops:      "var(--warn)",
    churn:    "var(--bad)",
  };
  const c = colorMap[nudge.kind] || "var(--violet)";
  return (
    <div style={{
      padding: "12px 14px",
      borderRadius: 8,
      background: "var(--bg-2)",
      border: "1px solid var(--line-1)",
      borderLeft: `2px solid ${c}`,
      display: "flex", flexDirection: "column", gap: 6,
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <div style={{ color: c }}><Icon name="ai" size={13} /></div>
        <div style={{ fontSize: 12.5, fontWeight: 500, flex: 1 }}>{nudge.title}</div>
        <span className="chip" style={{ borderColor: "transparent", background: "var(--bg-3)", color: "var(--tx-3)" }}>
          {Math.round(nudge.confidence * 100)}%
        </span>
      </div>
      <div style={{ fontSize: 12, color: "var(--tx-2)", lineHeight: 1.45 }}>{nudge.body}</div>
      <div style={{ display: "flex", gap: 6, marginTop: 2 }}>
        <button className="btn sm" onClick={() => onAct && onAct(nudge, "apply")}>Apply</button>
        <button className="btn sm ghost" onClick={() => onAct && onAct(nudge, "later")}>Later</button>
      </div>
    </div>
  );
};

const Dashboard = ({ onSelectUnit, onGoTo }) => {
  // Hourly gate activity (24 hours, 0..23)
  const gateData = [2,1,0,0,0,1,3,8,14,18,12,9,11,15,13,10,8,12,9,5,3,2,1, 6];
  const occTrend = [82,84,85,86,86,87,87,88,89,90,91,91];
  const revTrend = [28,30,31,32,33,34,35,36,37,38,38,39];
  const moveTrend= [3,5,4,6,5,7,6,8,7,9,8,7];
  const lateTrend= [12,11,10,9,8,9,10,11,9,8,7,5];

  // counts by state
  const counts = useMemo(() => {
    const c = { vacant: 0, occupied: 0, reserved: 0, delinq: 0, locked: 0, alarm: 0, open: 0 };
    UNITS.forEach(u => c[u.state]++);
    return c;
  }, []);
  const total = UNITS.length;
  const occPct = Math.round(((counts.occupied + counts.delinq + counts.locked + counts.alarm) / total) * 100);

  return (
    <div data-screen-label="Dashboard" style={{ display: "flex", flexDirection: "column", gap: "var(--gutter)" }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Good morning, Ellie</h1>
          <div className="page-sub">
            Tuesday, May 6 · Auckland Central · <span className="tnum">{counts.occupied}</span> occupied of <span className="tnum">{total}</span> · <span style={{ color: "#fbbf24" }}>3 active alerts</span>
          </div>
        </div>
        <div className="head-actions">
          <button className="btn"><Icon name="calendar" size={14} /> Today</button>
          <button className="btn ghost"><Icon name="external" size={14} /> Reports</button>
          <button className="btn primary"><Icon name="plus" size={14} /> New booking</button>
        </div>
      </div>

      {/* KPI strip */}
      <div className="kpi-row">
        <KPI label="Occupancy"        val={`${occPct}`} unit="%" delta="+1.8 vs LM" deltaTone="up"   trend={occTrend} trendColor="#10b981" tag="MTD" />
        <KPI label="RevPAM"           val="38.4"  unit="NZD/m²" delta="+4.2%"      deltaTone="up"   trend={revTrend} trendColor="#22d3ee" tag="MTD" />
        <KPI label="Move-ins today"   val="5"     unit=""        delta="+2 vs avg"  deltaTone="up"   trend={moveTrend} trendColor="var(--accent-400)" />
        <KPI label="Late accounts"    val="14"    unit=""        delta="-3 wk/wk"   deltaTone="up"   trend={lateTrend} trendColor="#fbbf24" />
        <KPI label="Gate activity"    val="187"   unit="today"   delta="+12%"       deltaTone="up"   trend={gateData} trendColor="var(--accent-400)" />
        <KPI label="Projected MRR"    val="48.2"  unit="K NZD"   delta="+$2.1K"     deltaTone="up"   trend={[40,41,42,43,44,45,46,46,47,47,48,48]} trendColor="#10b981" tag="May" />
      </div>

      {/* Main grid */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: "var(--gutter)" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--gutter)" }}>

          {/* Facility snapshot */}
          <div className="card">
            <div className="card-h">
              <div className="card-t">Facility snapshot</div>
              <div className="card-actions">
                <button className="btn sm ghost" onClick={() => onGoTo("map")}>Open map <Icon name="right" size={12} /></button>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 24, alignItems: "center" }}>
              <Donut pct={occPct} size={120} color="var(--accent-500)" sub="occupied" />
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
                {[
                  { lbl: "Occupied",  n: counts.occupied,        cls: "u-occupied"  },
                  { lbl: "Vacant",    n: counts.vacant,          cls: "u-vacant"    },
                  { lbl: "Reserved",  n: counts.reserved,        cls: "u-reserved"  },
                  { lbl: "Delinquent",n: counts.delinq,          cls: "u-delinq"    },
                  { lbl: "Smart Locked", n: counts.locked,       cls: "u-locked"    },
                  { lbl: "Alarms",    n: counts.alarm + counts.open, cls: "u-alarm" },
                ].map((s, i) => (
                  <div key={i} style={{
                    padding: "10px 12px", borderRadius: 8,
                    background: "var(--bg-2)", border: "1px solid var(--line-1)",
                  }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                      <span className={s.cls} style={{ width: 10, height: 10, borderRadius: 3, border: "1px solid", display: "inline-block" }}></span>
                      <span style={{ fontSize: 11.5, color: "var(--tx-2)" }}>{s.lbl}</span>
                    </div>
                    <div style={{ fontSize: 20, fontWeight: 600, marginTop: 4 }} className="tnum">{s.n}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Today's bookings + Gate activity */}
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: "var(--gutter)" }}>
            <div className="card">
              <div className="card-h">
                <div className="card-t">Today's schedule</div>
                <div className="card-actions">
                  <button className="btn sm ghost" onClick={() => onGoTo("bookings")}>All</button>
                </div>
              </div>
              <table className="table">
                <thead>
                  <tr>
                    <th style={{ width: 56 }}>Time</th>
                    <th>Tenant</th>
                    <th style={{ width: 80 }}>Unit</th>
                    <th>Type</th>
                    <th>Stage</th>
                  </tr>
                </thead>
                <tbody>
                  {BOOKINGS.map((b, i) => (
                    <tr key={i}>
                      <td className="mono" style={{ color: "var(--tx-2)" }}>{b.time}</td>
                      <td>{b.name}</td>
                      <td className="mono"><a onClick={() => onSelectUnit(b.unit)} style={{ color: "var(--tx-1)", cursor: "pointer" }}>{b.unit}</a></td>
                      <td>
                        <span className={`chip ${b.type === "Move-in" ? "ok" : b.type === "Move-out" ? "info" : ""}`}>{b.type}</span>
                      </td>
                      <td style={{ color: "var(--tx-2)" }}>{b.stage}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="card">
              <div className="card-h">
                <div className="card-t">Gate activity · 24h</div>
                <div className="card-actions">
                  <span className="chip">187 events</span>
                </div>
              </div>
              <GateBars data={gateData} height={80} />
              <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, fontSize: 10.5, color: "var(--tx-3)" }} className="mono">
                <span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>now</span>
              </div>
              <div className="divider" style={{ margin: "12px 0" }}/>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                <div>
                  <div style={{ fontSize: 10.5, color: "var(--tx-3)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Peak hour</div>
                  <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>09:00–10:00</div>
                  <div style={{ fontSize: 11, color: "var(--tx-2)" }}>18 entries · 14 exits</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: "var(--tx-3)", textTransform: "uppercase", letterSpacing: "0.06em" }}>Avg dwell</div>
                  <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>23 min</div>
                  <div style={{ fontSize: 11, color: "var(--tx-2)" }}>vs 26 min last wk</div>
                </div>
              </div>
            </div>
          </div>

          {/* Delinquents */}
          <div className="card">
            <div className="card-h">
              <div className="card-t">Late accounts</div>
              <div className="card-actions">
                <span className="chip warn"><span className="d" /> 14 total · $2,840 NZD</span>
                <button className="btn sm ghost" onClick={() => onGoTo("billing")}>Manage</button>
              </div>
            </div>
            <table className="table">
              <thead>
                <tr>
                  <th>Tenant</th>
                  <th>Unit</th>
                  <th style={{ textAlign: "right" }}>Days late</th>
                  <th style={{ textAlign: "right" }}>Balance</th>
                  <th>Last contact</th>
                  <th>Risk</th>
                  <th style={{ width: 100 }}></th>
                </tr>
              </thead>
              <tbody>
                {DELINQUENTS.map((d, i) => (
                  <tr key={i}>
                    <td>{d.name}</td>
                    <td className="mono"><a onClick={() => onSelectUnit(d.unit)} style={{ color: "var(--tx-1)", cursor: "pointer" }}>{d.unit}</a></td>
                    <td style={{ textAlign: "right" }}>
                      <span className={`chip ${d.days > 30 ? "bad" : "warn"}`}>{d.days}d</span>
                    </td>
                    <td style={{ textAlign: "right", fontWeight: 500 }} className="tnum">${d.amount}</td>
                    <td className="mono" style={{ color: "var(--tx-2)" }}>{d.last}</td>
                    <td>
                      <span className={`chip ${d.risk === "high" ? "bad" : d.risk === "medium" ? "warn" : ""}`}>{d.risk}</span>
                    </td>
                    <td>
                      <div style={{ display: "flex", gap: 4, justifyContent: "flex-end" }}>
                        <button className="iconbtn" title="Call" style={{ width: 24, height: 24 }}><Icon name="phone" size={12} /></button>
                        <button className="iconbtn" title="Email" style={{ width: 24, height: 24 }}><Icon name="mail" size={12} /></button>
                        <button className="iconbtn" title="More" style={{ width: 24, height: 24 }}><Icon name="more" size={12} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* Right column */}
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--gutter)" }}>
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <div className="card-h" style={{ padding: "var(--card-pad)", marginBottom: 0 }}>
              <div className="card-t">Live activity</div>
              <div className="card-actions">
                <span className="live-indicator"><span className="pulse" /> Streaming</span>
              </div>
            </div>
            <div style={{ padding: "0 var(--card-pad) 12px", maxHeight: 460, overflow: "auto" }}>
              <ActivityFeed items={ACTIVITY} onSelectUnit={onSelectUnit} />
            </div>
          </div>

          <div className="card">
            <div className="card-h">
              <div className="card-t" style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ color: "var(--violet)" }}><Icon name="ai" size={13} /></span>
                AI Suggestions
              </div>
              <div className="card-actions">
                <span className="chip violet">{AI_NUDGES.length} new</span>
              </div>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {AI_NUDGES.slice(0, 3).map((n, i) => <AINudge key={i} nudge={n} />)}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.Dashboard = Dashboard;
window.SharedUI = { Sparkline, KPI, Donut, ActivityFeed, AINudge, GateBars };
