// Live Dashboard page — KPIs, live list, floor plan, activity, volume
function KPI({ label, value, delta, deltaDir, spark }) {
  return (
    <div className="kpi">
      <div className="label">{label}</div>
      <div className="value tnum">{value}</div>
      {delta && <div className={"delta " + (deltaDir === "up" ? "up" : deltaDir === "down" ? "down" : "")}>{delta}</div>}
      {spark && (
        <svg className="spark" width="90" height="30" viewBox="0 0 90 30" fill="none">
          <polyline points={spark} stroke="var(--accent)" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      )}
    </div>
  );
}

function VisitorRow({ v, onOpen, compact }) {
  const pillCls = {
    onsite: "onsite", pending: "pending", denied: "denied",
    approved: "approved", checkedout: "checkedout", scheduled: "scheduled"
  }[v.status];
  const pillLabel = {
    onsite: "On site", pending: "Pending", denied: "Denied",
    approved: "Approved", checkedout: "Checked out", scheduled: "Scheduled"
  }[v.status];
  return (
    <tr onClick={() => onOpen?.(v)} style={{cursor: "pointer"}}>
      <td>
        <div className="hstack">
          <Avatar name={v.name} size="sm" />
          <div>
            <div style={{fontWeight: 500}}>
              {v.name}
              {v.type === "vip" && <span className="pill vip" style={{marginLeft: 8, fontSize: 10}}>VIP</span>}
            </div>
            <div className="muted" style={{fontSize: 12}}>{v.company}</div>
          </div>
        </div>
      </td>
      {!compact && <td>{v.host}<div className="muted" style={{fontSize: 12}}>{v.hostTeam}</div></td>}
      {!compact && <td className="muted">{v.purpose}</td>}
      <td className="tnum">{v.scheduled}<div className="muted tnum" style={{fontSize: 12}}>Arr {v.arrival}</div></td>
      {!compact && <td className="muted" style={{fontSize: 12.5}}>{v.dest}</td>}
      <td><span className={"pill " + pillCls}><span className="dot"/>{pillLabel}</span></td>
      {!compact && <td className="mono" style={{fontSize: 12, color: "var(--ink-3)"}}>{v.badge}</td>}
    </tr>
  );
}

function VolumeChart({ data, peak = 26 }) {
  return (
    <div>
      <div className="bar-chart">
        {data.map((v, i) => (
          <div key={i} className="bar" style={{height: "100%"}}>
            <div className="fill" style={{height: `${(v / peak) * 100}%`}} />
          </div>
        ))}
      </div>
      <div className="hstack" style={{justifyContent: "space-between", fontSize: 11, color: "var(--ink-3)", marginTop: 6}}>
        <span>00:00</span><span>06:00</span><span>12:00</span><span>18:00</span><span>24:00</span>
      </div>
    </div>
  );
}

function FloorPlan() {
  // approximate building floor plan with visitor pins
  const rooms = [
    { id: "r1", top: 4, left: 4,  w: 32, h: 38, label: "Lobby A", sub: "T1 · Ground" },
    { id: "r2", top: 4, left: 38, w: 28, h: 28, label: "Boardroom A", sub: "T1 · L14" },
    { id: "r3", top: 4, left: 68, w: 28, h: 28, label: "Executive Lounge", sub: "T1 · L15" },
    { id: "r4", top: 44, left: 4, w: 24, h: 24, label: "Studio 4", sub: "T1 · L2" },
    { id: "r5", top: 44, left: 30, w: 24, h: 24, label: "Meeting 3A", sub: "T1 · L9" },
    { id: "r6", top: 44, left: 56, w: 20, h: 24, label: "Broadcast", sub: "T2 · L1" },
    { id: "r7", top: 44, left: 78, w: 18, h: 24, label: "Huddle 2", sub: "T1 · L6" },
    { id: "r8", top: 72, left: 4, w: 30, h: 24, label: "Innovation Lab", sub: "T2 · L3" },
    { id: "r9", top: 72, left: 36, w: 26, h: 24, label: "Data Studio", sub: "T2 · L5" },
    { id: "r10", top: 72, left: 64, w: 32, h: 24, label: "Reception", sub: "T2 · Ground" },
  ];
  const pins = [
    { name: "Amira Haddad", room: "r2", vip: false },
    { name: "Hassan Al-Sabah", room: "r3", vip: true },
    { name: "Marcus Chen", room: "r8", vip: true },
    { name: "Priya Iyer", room: "r9", vip: false },
    { name: "Tom Whitaker", room: "r6", vip: false },
    { name: "Daniel Park", room: "r5", vip: false },
    { name: "Amira G", room: "r1", vip: false },
    { name: "G2", room: "r1", vip: false },
  ];
  const pinColor = (vip) => vip ? "var(--violet)" : "var(--green)";
  return (
    <div className="floor">
      {rooms.map(r => (
        <div key={r.id} className="room" style={{top: `${r.top}%`, left: `${r.left}%`, width: `${r.w}%`, height: `${r.h}%`}}>
          <div className="rn">{r.label}</div>
          <div style={{fontSize: 10.5, marginTop: 2}}>{r.sub}</div>
        </div>
      ))}
      {pins.map((p, i) => {
        const r = rooms.find(x => x.id === p.room);
        const offsetX = 8 + (i * 11) % (r.w - 20);
        const offsetY = r.h - 14;
        return (
          <div key={i} className="pin"
               style={{
                 top: `calc(${r.top + r.h}% - 28px + ${i * 3}px)`,
                 left: `calc(${r.left}% + ${offsetX}%)`,
                 background: pinColor(p.vip),
               }}>
            {p.name.split(" ").map(x=>x[0]).slice(0,2).join("")}
          </div>
        );
      })}

      <div style={{position: "absolute", left: 12, bottom: 12, display: "flex", gap: 12,
                   background: "var(--surface)", padding: "6px 10px", borderRadius: 8,
                   border: "1px solid var(--border)", fontSize: 11.5}}>
        <div className="hstack"><span className="dot" style={{background: "var(--green)", width: 8, height: 8, borderRadius: "50%", display: "inline-block"}}/> Standard</div>
        <div className="hstack"><span style={{background: "var(--violet)", width: 8, height: 8, borderRadius: "50%", display: "inline-block"}}/> VIP</div>
      </div>
    </div>
  );
}

function ActivityFeed() {
  const typeIcon = { checkin: I.Door, checkout: I.Logout, approval: I.Clock, vip: I.VIP, denied: I.Shield };
  const typeColor = { checkin: "var(--green)", checkout: "var(--ink-3)", approval: "var(--amber)", vip: "var(--violet)", denied: "var(--red)" };
  return (
    <div className="stack-sm" style={{maxHeight: 520, overflowY: "auto"}}>
      {ACTIVITY.map((a, i) => {
        const IconC = typeIcon[a.type];
        return (
          <div key={i} style={{display: "grid", gridTemplateColumns: "42px 1fr", gap: 10, padding: "10px 4px", borderBottom: i < ACTIVITY.length - 1 ? "1px solid var(--border)" : 0}}>
            <div className="tnum" style={{fontSize: 12, color: "var(--ink-3)", fontFamily: "var(--font-mono)"}}>{a.t}</div>
            <div>
              <div style={{fontSize: 13, lineHeight: 1.45}}>
                <span style={{color: typeColor[a.type], display: "inline-flex", verticalAlign: "middle", marginRight: 6}}>
                  <IconC size={13} sw={1.8}/>
                </span>
                <strong style={{fontWeight: 500}}>{a.who}</strong> <span className="muted">{a.what}</span> <span>{a.where}</span>
              </div>
              <div className="muted" style={{fontSize: 11.5, marginTop: 2}}>{a.by}</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function Dashboard({ onOpenVisitor }) {
  const onsite = VISITORS.filter(v => v.status === "onsite");
  const upcoming = VISITORS.filter(v => v.status === "approved" || v.status === "pending");
  const [tab, setTab] = useState("onsite");
  const rows = tab === "onsite" ? onsite : upcoming;

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Live Dashboard</h1>
          <div className="page-subtitle">Tuesday, April 21 · All sites · Auto-refreshing</div>
        </div>
        <div className="hstack">
          <div className="seg">
            <button className="active">Today</button>
            <button>Week</button>
            <button>Month</button>
          </div>
          <button className="btn ghost"><I.Filter size={14}/> All sites</button>
          <button className="btn"><I.ArrowDown size={14}/> Export</button>
        </div>
      </div>

      <div className="kpi-grid">
        <KPI label="On site right now" value="38" delta="+4 vs typical" deltaDir="up" spark="0,22 10,18 20,20 30,14 40,12 50,10 60,12 70,8 80,6 90,4"/>
        <KPI label="Expected today"    value="127" delta="12 awaiting approval" deltaDir="" spark="0,20 10,22 20,18 30,16 40,14 50,14 60,10 70,8 80,10 90,6"/>
        <KPI label="Avg check-in"      value="42s" delta="−8s vs last week" deltaDir="up" spark="0,10 10,14 20,12 30,18 40,16 50,20 60,18 70,22 80,20 90,24"/>
        <KPI label="Approval SLA"      value="96.4%" delta="1 overdue" deltaDir="down" spark="0,6 10,8 20,10 30,8 40,12 50,10 60,14 70,12 80,16 90,14"/>
      </div>

      <div className="col-split-2" style={{marginBottom: 16}}>
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">Visitors today</div>
              <div className="card-sub">Tap a row to open the visitor drawer</div>
            </div>
            <div className="seg">
              <button className={tab === "onsite" ? "active" : ""} onClick={() => setTab("onsite")}>On site · {onsite.length}</button>
              <button className={tab === "upcoming" ? "active" : ""} onClick={() => setTab("upcoming")}>Upcoming · {upcoming.length}</button>
            </div>
          </div>
          <table className="table">
            <thead>
              <tr>
                <th>Visitor</th>
                <th>Host</th>
                <th>Purpose</th>
                <th>Sched.</th>
                <th>Destination</th>
                <th>Status</th>
                <th>Badge</th>
              </tr>
            </thead>
            <tbody>
              {rows.map(v => <VisitorRow key={v.id} v={v} onOpen={onOpenVisitor} />)}
            </tbody>
          </table>
        </div>

        <div className="stack-lg">
          <div className="card">
            <div className="card-header">
              <div>
                <div className="card-title">Where they are</div>
                <div className="card-sub">Live presence · AXS Campus</div>
              </div>
              <button className="btn sm ghost">Fullscreen</button>
            </div>
            <div className="card-body" style={{padding: 14}}>
              <FloorPlan />
            </div>
          </div>

          <div className="card">
            <div className="card-header">
              <div>
                <div className="card-title">Arrivals · 24h</div>
                <div className="card-sub">Peak 11:30 — 26 arrivals</div>
              </div>
            </div>
            <div className="card-body">
              <VolumeChart data={VOLUME_24H} />
            </div>
          </div>
        </div>
      </div>

      <div className="col-split-2">
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">Live activity</div>
              <div className="card-sub">Check-ins, approvals, system events</div>
            </div>
            <button className="btn sm ghost">View all</button>
          </div>
          <div className="card-body" style={{padding: "6px 18px"}}>
            <ActivityFeed />
          </div>
        </div>

        <div className="stack-lg">
          <div className="card">
            <div className="card-header">
              <div>
                <div className="card-title">Approvals waiting</div>
                <div className="card-sub">6 in queue · 1 overdue</div>
              </div>
              <button className="btn sm">Open queue</button>
            </div>
            <div className="stack-sm" style={{padding: "4px 0"}}>
              {APPROVALS.slice(0, 4).map(a => (
                <div key={a.id} style={{display: "grid", gridTemplateColumns: "1fr auto", gap: 12, padding: "10px 18px", borderBottom: "1px solid var(--border)"}}>
                  <div>
                    <div style={{fontWeight: 500}}>{a.visitor} <span className="muted" style={{fontWeight: 400}}>· {a.company}</span></div>
                    <div className="muted" style={{fontSize: 12, marginTop: 2}}>
                      {a.stage} · Level {a.level}
                    </div>
                  </div>
                  <div className="hstack">
                    <span className={"pill " + (a.sla.includes("overdue") ? "denied" : a.risk === "high" ? "denied" : a.risk === "med" ? "pending" : "scheduled")}>
                      {a.sla}
                    </span>
                    <button className="btn sm primary">Review</button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="card-header">
              <div>
                <div className="card-title">Top hosts today</div>
                <div className="card-sub">Visitors scheduled per host</div>
              </div>
            </div>
            <div className="stack-sm" style={{padding: "6px 18px 14px"}}>
              {[
                { name: "Yara Al-Otaibi", team: "Strategy", count: 7, vip: 3 },
                { name: "Omar Rahman", team: "Engineering", count: 5, vip: 1 },
                { name: "Leila Khoury", team: "Brand", count: 4, vip: 0 },
                { name: "Hana Yusuf", team: "Legal", count: 3, vip: 0 },
              ].map((h, i) => (
                <div key={i} style={{display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 10, alignItems: "center", padding: "8px 0", borderBottom: i < 3 ? "1px solid var(--border)" : 0}}>
                  <Avatar name={h.name} size="sm" />
                  <div>
                    <div style={{fontSize: 13, fontWeight: 500}}>{h.name}</div>
                    <div className="muted" style={{fontSize: 11.5}}>{h.team}</div>
                  </div>
                  <div className="hstack">
                    {h.vip > 0 && <span className="pill vip">{h.vip} VIP</span>}
                    <div className="tnum" style={{fontWeight: 600}}>{h.count}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, KPI, VisitorRow, VolumeChart, FloorPlan, ActivityFeed });
