// Secondary views: Customers, Billing, Automation, Access, Portfolio, Analytics, etc.
const { ACTIVITY: V_ACT, DELINQUENTS: V_DELINQ, BOOKINGS: V_BOOK, SITES: V_SITES, AI_NUDGES: V_AI, UNITS: V_UNITS } = window.VAULT_DATA;

// =============================================================
// Unit detail panel — slides in from right when a unit is picked
// =============================================================
const UnitPanel = ({ unit, onClose }) => {
  if (!unit) return null;
  const stateChip = {
    vacant: "", occupied: "info", reserved: "warn", delinq: "bad",
    locked: "cyan", alarm: "bad", open: "bad",
  }[unit.state];
  const stateLabel = {
    vacant: "Vacant", occupied: "Occupied", reserved: "Reserved",
    delinq: "Delinquent", locked: "Smart Locked", alarm: "Alarm",
    open: "Door Open",
  }[unit.state];

  // Mock ledger rows
  const ledger = [
    { d: "May 1",  desc: "Monthly rent",        amt: 320, st: "paid" },
    { d: "Apr 1",  desc: "Monthly rent",        amt: 320, st: "paid" },
    { d: "Mar 22", desc: "Late fee waiver",     amt: -25, st: "credit" },
    { d: "Mar 1",  desc: "Monthly rent",        amt: 320, st: "paid" },
    { d: "Feb 1",  desc: "Monthly rent",        amt: 320, st: "paid" },
    { d: "Jan 5",  desc: "Move-in fee",         amt: 75,  st: "paid" },
  ];
  const events = [
    { t: "08:42", d: "Today",  e: "Gate entry · keypad" },
    { t: "08:31", d: "Today",  e: "Payment received · $320" },
    { t: "17:14", d: "May 5",  e: "Smart lock cycled" },
    { t: "10:02", d: "May 4",  e: "Gate entry · mobile" },
    { t: "16:48", d: "May 1",  e: "Gate exit" },
  ];

  return (
    <div className="panel">
      <div style={{ padding: "16px 18px", borderBottom: "1px solid var(--line-1)", display: "flex", alignItems: "center", gap: 10 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span className="mono" style={{ fontSize: 16, fontWeight: 600 }}>{unit.id}</span>
            <span className={`chip ${stateChip}`}>{stateLabel}</span>
          </div>
          <div style={{ fontSize: 12, color: "var(--tx-2)", marginTop: 4 }}>
            Zone {unit.zone} · {unit.widthM}×{unit.lengthM}m · {unit.sqm}m² {unit.climate ? "· Climate" : ""}
          </div>
        </div>
        <button className="iconbtn" onClick={onClose}><Icon name="close" size={14} /></button>
      </div>

      <div style={{ flex: 1, overflow: "auto" }}>
        {/* Tenant card */}
        {unit.tenant ? (
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line-1)" }}>
            <div style={{ fontSize: 10.5, color: "var(--tx-3)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>Tenant</div>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <div className="avatar" style={{
                background: "linear-gradient(140deg, var(--accent-500), var(--accent-700))",
                width: 36, height: 36, fontSize: 13
              }}>
                {unit.tenant.split(" ").map(p => p[0]).slice(0,2).join("")}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500 }}>{unit.tenant}</div>
                <div style={{ fontSize: 11.5, color: "var(--tx-2)" }}>Customer since Jan 2024</div>
              </div>
              <button className="iconbtn"><Icon name="phone" size={13} /></button>
              <button className="iconbtn"><Icon name="mail" size={13} /></button>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 14 }}>
              <div style={{ padding: 10, background: "var(--bg-2)", borderRadius: 7, border: "1px solid var(--line-1)" }}>
                <div style={{ fontSize: 10.5, color: "var(--tx-3)" }}>Rate</div>
                <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }} className="tnum">${unit.price}</div>
              </div>
              <div style={{ padding: 10, background: "var(--bg-2)", borderRadius: 7, border: "1px solid var(--line-1)" }}>
                <div style={{ fontSize: 10.5, color: "var(--tx-3)" }}>Lease</div>
                <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>Monthly</div>
              </div>
              <div style={{ padding: 10, background: "var(--bg-2)", borderRadius: 7, border: "1px solid var(--line-1)" }}>
                <div style={{ fontSize: 10.5, color: "var(--tx-3)" }}>Auto-pay</div>
                <div style={{ fontSize: 14, fontWeight: 600, marginTop: 2, color: "#6ee7b7" }}>On</div>
              </div>
            </div>
          </div>
        ) : (
          <div style={{ padding: "18px", borderBottom: "1px solid var(--line-1)", textAlign: "center" }}>
            <div style={{ fontSize: 13, color: "var(--tx-2)", marginBottom: 10 }}>This unit is available for rent.</div>
            <button className="btn primary"><Icon name="plus" size={13} /> Reserve unit</button>
            <div style={{ fontSize: 11.5, color: "var(--tx-3)", marginTop: 10 }}>
              Suggested rate <span className="tnum" style={{ color: "var(--tx-1)" }}>${unit.price}</span> · AI-priced
            </div>
          </div>
        )}

        {/* Smart lock */}
        <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line-1)" }}>
          <div style={{ fontSize: 10.5, color: "var(--tx-3)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>Smart lock</div>
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <span className={`chip ${unit.state === "open" ? "bad" : unit.state === "locked" ? "cyan" : ""}`}>
              <Icon name={unit.state === "open" ? "unlock" : "lock"} size={11} />
              {unit.state === "open" ? "Open" : "Locked"}
            </span>
            <span className="chip"><Icon name="wifi" size={11} /> Online</span>
            <span className="chip"><Icon name="battery" size={11} /> 87%</span>
            <div style={{ marginLeft: "auto" }}>
              <button className="btn sm">Override</button>
            </div>
          </div>
        </div>

        {/* Recent events */}
        {unit.tenant && (
          <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--line-1)" }}>
            <div style={{ fontSize: 10.5, color: "var(--tx-3)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>Recent activity</div>
            {events.map((e, i) => (
              <div key={i} style={{
                display: "flex", gap: 10, padding: "6px 0",
                borderBottom: i < events.length - 1 ? "1px solid var(--line-1)" : "none",
              }}>
                <div className="mono" style={{ fontSize: 11, color: "var(--tx-3)", width: 64, flexShrink: 0 }}>
                  {e.d} {e.t}
                </div>
                <div style={{ fontSize: 12, flex: 1 }}>{e.e}</div>
              </div>
            ))}
          </div>
        )}

        {/* Ledger */}
        {unit.tenant && (
          <div style={{ padding: "14px 18px" }}>
            <div style={{ fontSize: 10.5, color: "var(--tx-3)", textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 8 }}>Ledger</div>
            <table className="table" style={{ fontSize: 12 }}>
              <tbody>
                {ledger.map((l, i) => (
                  <tr key={i}>
                    <td className="mono" style={{ color: "var(--tx-3)", padding: "6px 0" }}>{l.d}</td>
                    <td style={{ padding: "6px 0" }}>{l.desc}</td>
                    <td style={{ padding: "6px 0", textAlign: "right" }} className="tnum">
                      <span style={{ color: l.amt < 0 ? "#fbbf24" : "var(--tx-1)" }}>
                        {l.amt < 0 ? "-" : ""}${Math.abs(l.amt)}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div style={{
        padding: 12, borderTop: "1px solid var(--line-1)",
        display: "flex", gap: 6,
      }}>
        <button className="btn" style={{ flex: 1 }}><Icon name="edit" size={13} /> Edit</button>
        <button className="btn" style={{ flex: 1 }}><Icon name="lock" size={13} /> Lock</button>
        <button className="btn primary" style={{ flex: 1 }}>Open ledger</button>
      </div>
    </div>
  );
};

// =============================================================
// Customers list
// =============================================================
const Customers = ({ onPickUnit }) => {
  const customers = useMemo(() => {
    const arr = [];
    const seen = new Set();
    V_UNITS.filter(u => u.tenant).forEach(u => {
      if (seen.has(u.tenant)) return;
      seen.add(u.tenant);
      arr.push({
        name: u.tenant,
        units: V_UNITS.filter(x => x.tenant === u.tenant).map(x => x.id),
        primary: u,
        since: ["Mar 2023","Jul 2023","Nov 2023","Jan 2024","Feb 2024","Apr 2024","Aug 2024","Dec 2024","Feb 2025","Mar 2025"][arr.length % 10],
      });
    });
    return arr.slice(0, 18);
  }, []);

  return (
    <div data-screen-label="Customers" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Customers</h1>
          <div className="page-sub">{customers.length}+ active tenants · 8 new this month</div>
        </div>
        <div className="head-actions">
          <button className="btn"><Icon name="filter" size={14} /> Filter</button>
          <button className="btn ghost"><Icon name="external" size={14} /> Export CSV</button>
          <button className="btn primary"><Icon name="plus" size={14} /> Add customer</button>
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Units</th>
              <th>Customer since</th>
              <th>Auto-pay</th>
              <th>Status</th>
              <th style={{ textAlign: "right" }}>MRR</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {customers.map((c, i) => {
              const status = c.primary.state;
              const statusChip = status === "delinq" ? "bad" : status === "alarm" ? "bad" : "ok";
              const statusLabel = status === "delinq" ? "Late" : "Active";
              return (
                <tr key={i}>
                  <td>
                    <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                      <div className="avatar" style={{ width: 24, height: 24, fontSize: 10, background: `hsl(${i*47 % 360}deg 50% 45%)` }}>
                        {c.name.split(" ").map(p => p[0]).slice(0,2).join("")}
                      </div>
                      <span style={{ fontWeight: 500 }}>{c.name}</span>
                    </div>
                  </td>
                  <td>
                    {c.units.map(uid => (
                      <a key={uid} onClick={() => onPickUnit(uid)} className="mono" style={{
                        cursor: "pointer", padding: "1px 6px", marginRight: 4,
                        background: "var(--bg-3)", borderRadius: 4, fontSize: 11,
                      }}>{uid}</a>
                    ))}
                  </td>
                  <td className="mono" style={{ color: "var(--tx-2)" }}>{c.since}</td>
                  <td><span className={`chip ${i % 4 === 0 ? "" : "ok"}`}>{i % 4 === 0 ? "Off" : "On"}</span></td>
                  <td><span className={`chip ${statusChip}`}>{statusLabel}</span></td>
                  <td style={{ textAlign: "right", fontWeight: 500 }} className="tnum">${c.primary.price}</td>
                  <td style={{ textAlign: "right" }}><Icon name="more" size={14} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// =============================================================
// Billing
// =============================================================
const Billing = ({ onPickUnit }) => {
  const recentPayments = [
    { d: "08:31", who: "Aroha Whetu",   unit: "A-104", method: "Direct Debit", amt: 320, st: "paid" },
    { d: "06:40", who: "Anika Rao",     unit: "B-122", method: "Apple Pay",    amt: 185, st: "paid" },
    { d: "Yest.", who: "Henry Robinson",unit: "B-119", method: "Card · Visa",  amt: 240, st: "paid" },
    { d: "Yest.", who: "Sienna Wright", unit: "B-117", method: "Direct Debit", amt: 280, st: "paid" },
    { d: "May 4", who: "Jack Murphy",   unit: "C-204", method: "Card · MC",    amt: 410, st: "failed" },
    { d: "May 4", who: "Ruby Williams", unit: "E-407", method: "Direct Debit", amt:  95, st: "paid" },
    { d: "May 3", who: "Ari Karaka",    unit: "C-201", method: "Card · Visa",  amt: 180, st: "failed" },
  ];

  return (
    <div data-screen-label="Billing" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Billing</h1>
          <div className="page-sub">$48,234 NZD billed in May · 96.4% on-time payment rate</div>
        </div>
        <div className="head-actions">
          <button className="btn"><Icon name="calendar" size={14} /> May 2026</button>
          <button className="btn ghost">Run batch</button>
          <button className="btn primary"><Icon name="plus" size={14} /> New invoice</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        {[
          { l: "Billed this month",       v: "$48.2K",   d: "+5.4%",  dt: "up",   t: [40,41,42,43,44,45,46,47,48], c: "#10b981" },
          { l: "Outstanding",             v: "$2,840",   d: "-12%",   dt: "up",   t: [4,4,3.5,3.2,3,2.9,2.85,2.84,2.84], c: "#fbbf24" },
          { l: "Auto-pay coverage",       v: "78%",      d: "+2pp",   dt: "up",   t: [70,72,73,74,75,76,77,77,78], c: "var(--accent-400)" },
          { l: "Failed payments",         v: "4",        d: "-2",     dt: "up",   t: [9,8,7,6,5,5,4,4,4],          c: "#ef4444" },
        ].map((k, i) => <window.SharedUI.KPI key={i} label={k.l} val={k.v} delta={k.d} deltaTone={k.dt} trend={k.t} trendColor={k.c} />)}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-h"><div className="card-t">Recent payments</div></div>
          <table className="table">
            <thead>
              <tr><th>When</th><th>Tenant</th><th>Unit</th><th>Method</th><th style={{textAlign:"right"}}>Amt</th><th>Status</th></tr>
            </thead>
            <tbody>
              {recentPayments.map((p, i) => (
                <tr key={i}>
                  <td className="mono" style={{color:"var(--tx-3)"}}>{p.d}</td>
                  <td>{p.who}</td>
                  <td className="mono"><a onClick={() => onPickUnit(p.unit)} style={{cursor:"pointer"}}>{p.unit}</a></td>
                  <td style={{color:"var(--tx-2)"}}>{p.method}</td>
                  <td style={{textAlign:"right"}} className="tnum">${p.amt}</td>
                  <td><span className={`chip ${p.st === "paid" ? "ok" : "bad"}`}>{p.st}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card">
          <div className="card-h"><div className="card-t">Aging summary</div></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {[
              { label: "Current",     n: 128, amt: "$45,394", color: "#10b981", pct: 92 },
              { label: "1–14 days",   n:   8, amt:    "$960", color: "var(--accent-400)", pct: 24 },
              { label: "15–30 days",  n:   3, amt:    "$540", color: "#fbbf24", pct: 16 },
              { label: "31–60 days",  n:   2, amt:    "$620", color: "#f59e0b", pct: 12 },
              { label: "60+ days",    n:   1, amt:    "$720", color: "#ef4444", pct:  8 },
            ].map((b, i) => (
              <div key={i}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}>
                  <span style={{ color: "var(--tx-2)" }}>{b.label} <span className="tnum dim">· {b.n}</span></span>
                  <span className="tnum" style={{ fontWeight: 500 }}>{b.amt}</span>
                </div>
                <div className="bar" style={{ height: 6 }}>
                  <span style={{ width: `${b.pct}%`, background: b.color }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-h">
          <div className="card-t">Late accounts · escalation queue</div>
          <div className="card-actions">
            <button className="btn sm ghost">Send reminder batch</button>
          </div>
        </div>
        <table className="table">
          <thead>
            <tr><th>Tenant</th><th>Unit</th><th>Days late</th><th>Balance</th><th>Last contact</th><th>Risk</th><th>Auto-action</th><th></th></tr>
          </thead>
          <tbody>
            {V_DELINQ.map((d, i) => (
              <tr key={i}>
                <td>{d.name}</td>
                <td className="mono"><a onClick={() => onPickUnit(d.unit)} style={{cursor:"pointer"}}>{d.unit}</a></td>
                <td><span className={`chip ${d.days > 30 ? "bad" : "warn"}`}>{d.days}d</span></td>
                <td className="tnum">${d.amount}</td>
                <td className="mono" style={{color:"var(--tx-2)"}}>{d.last}</td>
                <td><span className={`chip ${d.risk === "high" ? "bad" : "warn"}`}>{d.risk}</span></td>
                <td style={{ color: "var(--tx-2)", fontSize: 12 }}>
                  {d.days > 60 ? "Auction notice in 6 days" : d.days > 30 ? "Gate access suspended" : "Reminder scheduled"}
                </td>
                <td><Icon name="more" size={14} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

// =============================================================
// Automation builder
// =============================================================
const AutomationNode = ({ kind, title, body, color = "var(--accent-400)" }) => (
  <div style={{
    background: "var(--bg-2)", border: "1px solid var(--line-2)", borderRadius: 8,
    padding: 12, position: "relative",
    borderLeft: `2px solid ${color}`,
  }}>
    <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em", color, marginBottom: 4 }}>{kind}</div>
    <div style={{ fontSize: 13, fontWeight: 500 }}>{title}</div>
    {body && <div style={{ fontSize: 11.5, color: "var(--tx-2)", marginTop: 4 }}>{body}</div>}
  </div>
);

const FlowConnector = () => (
  <div style={{ display: "flex", justifyContent: "center", padding: "4px 0" }}>
    <div style={{ width: 1, height: 20, background: "var(--line-2)" }} />
  </div>
);

const Automation = () => {
  const flows = [
    {
      name: "Late payment escalation", runs: 142, last: "12 min ago", on: true,
      steps: [
        { kind: "TRIGGER", title: "Payment fails", body: "When a scheduled payment is declined", color: "var(--accent-400)" },
        { kind: "CONDITION", title: "Failed twice in 7 days AND balance > $300", color: "var(--warn)" },
        { kind: "ACTION", title: "Suspend gate access", body: "Smart lock + perimeter gates", color: "var(--bad)" },
        { kind: "ACTION", title: "Notify manager + send SMS to tenant", color: "var(--info)" },
      ],
    },
    {
      name: "Move-in welcome", runs: 38, last: "2 hours ago", on: true,
      steps: [
        { kind: "TRIGGER", title: "New lease signed", color: "var(--accent-400)" },
        { kind: "ACTION", title: "Provision smart lock + gate code", color: "var(--info)" },
        { kind: "ACTION", title: "Send welcome SMS + email with PDF lease", color: "var(--info)" },
        { kind: "DELAY", title: "Wait 7 days", color: "var(--violet)" },
        { kind: "ACTION", title: "Survey: how was the move-in?", color: "var(--info)" },
      ],
    },
  ];

  const templates = [
    { name: "Auto-pricing weekly", icon: "trend-up", color: "var(--violet)" },
    { name: "Reservation expires in 24h", icon: "calendar", color: "var(--warn)" },
    { name: "Gate alarm → security", icon: "alert", color: "var(--bad)" },
    { name: "Auction notice (60d)", icon: "auctions", color: "var(--bad)" },
    { name: "Birthday discount", icon: "ai", color: "var(--accent-400)" },
    { name: "Climate sensor alert", icon: "snowflake", color: "var(--info)" },
  ];

  return (
    <div data-screen-label="Automation" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Automation</h1>
          <div className="page-sub">14 active flows · 1,284 runs this month · 99.2% success</div>
        </div>
        <div className="head-actions">
          <button className="btn ghost">Templates</button>
          <button className="btn primary"><Icon name="plus" size={14} /> New automation</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 280px", gap: 14 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {flows.map((f, i) => (
            <div key={i} className="card">
              <div className="card-h">
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <div className="card-t" style={{ marginBottom: 0 }}>{f.name}</div>
                  <span className="chip ok"><span className="d" /> Active</span>
                </div>
                <div className="card-actions">
                  <span style={{ fontSize: 11.5, color: "var(--tx-3)" }}>
                    <span className="tnum">{f.runs}</span> runs · last {f.last}
                  </span>
                  <button className="iconbtn" style={{width:24,height:24}}><Icon name="edit" size={12} /></button>
                  <button className="iconbtn" style={{width:24,height:24}}><Icon name="more" size={12} /></button>
                </div>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, alignItems: "start" }}>
                {/* Visual flow column */}
                <div>
                  {f.steps.map((s, j) => (
                    <Fragment key={j}>
                      {j > 0 && <FlowConnector />}
                      <AutomationNode {...s} />
                    </Fragment>
                  ))}
                </div>
                {/* Pseudocode column */}
                <div style={{
                  background: "var(--bg-0)", borderRadius: 8,
                  border: "1px solid var(--line-1)",
                  padding: 14, fontSize: 12, fontFamily: "var(--font-mono)",
                  color: "var(--tx-2)", lineHeight: 1.7,
                }}>
                  {f.steps.map((s, j) => {
                    const prefix = j === 0 ? "WHEN " : s.kind === "CONDITION" ? "  IF  " : s.kind === "DELAY" ? "  WAIT" : "  THEN";
                    const color = s.color;
                    return (
                      <div key={j}>
                        <span style={{ color }}>{prefix}</span>{" "}
                        <span style={{ color: "var(--tx-1)" }}>{s.title}</span>
                        {s.body && <div style={{ paddingLeft: 38, color: "var(--tx-3)", fontSize: 11 }}>// {s.body}</div>}
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <div className="card">
            <div className="card-h"><div className="card-t">Templates</div></div>
            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              {templates.map((t, i) => (
                <div key={i} style={{
                  display: "flex", alignItems: "center", gap: 10,
                  padding: "8px 10px", borderRadius: 7,
                  background: "var(--bg-2)", border: "1px solid var(--line-1)",
                  cursor: "pointer",
                }}>
                  <span style={{ color: t.color }}><Icon name={t.icon} size={14} /></span>
                  <span style={{ fontSize: 12.5, flex: 1 }}>{t.name}</span>
                  <Icon name="plus" size={12} style={{ color: "var(--tx-3)" }} />
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <div className="card-h"><div className="card-t">Recent runs</div></div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, fontSize: 12 }}>
              {[
                { f: "Late payment escalation", t: "12m", st: "ok" },
                { f: "Move-in welcome",         t: "2h",  st: "ok" },
                { f: "Reservation expires",     t: "3h",  st: "ok" },
                { f: "Auto-pricing",            t: "5h",  st: "ok" },
                { f: "Auction notice",          t: "1d",  st: "warn" },
              ].map((r, i) => (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span className={`chip ${r.st === "ok" ? "ok" : "warn"}`} style={{padding:"1px 5px"}}>
                    <Icon name={r.st === "ok" ? "check" : "alert"} size={10} stroke={2} />
                  </span>
                  <span style={{ flex: 1, color: "var(--tx-2)" }}>{r.f}</span>
                  <span className="mono" style={{ color: "var(--tx-3)", fontSize: 11 }}>{r.t}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// =============================================================
// Access Control — security console
// =============================================================
const Access = () => {
  const liveEvents = [
    { t: "08:42:14", g: "Gate 1", e: "Entry · keypad",     u: "B-118", who: "Hemi Tane",       st: "ok"   },
    { t: "08:39:02", g: "Gate 2", e: "Exit · LPR · BLM921", u: "D-301", who: "Maeve Smith",     st: "ok"   },
    { t: "08:24:51", g: "C-208",  e: "Door open · unscheduled", u: "C-208", who: "—",          st: "bad"  },
    { t: "08:11:33", g: "Gate 1", e: "Entry · mobile",     u: "E-403", who: "Olivia Brown",    st: "ok"   },
    { t: "07:58:20", g: "Gate 1", e: "Denied · suspended", u: "D-302", who: "Liam Walker",     st: "warn" },
    { t: "07:42:08", g: "Gate 2", e: "Exit · mobile",      u: "B-115", who: "Mei Chen",        st: "ok"   },
    { t: "07:30:55", g: "A-102",  e: "Lock cycle · battery low", u: "A-102", who: "—",         st: "warn" },
    { t: "06:22:12", g: "Gate 2", e: "Entry · LPR · TNK443",u: "D-308", who: "Connor O'Connor",st: "ok"   },
  ];

  const cameras = [
    { id: "CAM-01", label: "Gate 1 entry",    online: true,  motion: false },
    { id: "CAM-02", label: "Gate 2 entry",    online: true,  motion: true  },
    { id: "CAM-03", label: "Zone A corridor", online: true,  motion: false },
    { id: "CAM-04", label: "Zone B corridor", online: true,  motion: false },
    { id: "CAM-05", label: "Zone C corridor", online: false, motion: false },
    { id: "CAM-06", label: "Drive lane",      online: true,  motion: true  },
  ];

  return (
    <div data-screen-label="Access Control" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Access Control</h1>
          <div className="page-sub">2 gates · 6 cameras · 522 smart locks · <span style={{color:"#fca5a5"}}>1 active alert</span></div>
        </div>
        <div className="head-actions">
          <button className="btn"><Icon name="filter" size={14} /> All zones</button>
          <button className="btn ghost"><Icon name="settings" size={14} /></button>
          <button className="btn primary"><Icon name="alert" size={14} /> Lockdown</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 14 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>

          {/* Active alert banner */}
          <div className="card" style={{
            borderColor: "color-mix(in oklab, var(--bad) 50%, var(--line-1))",
            background: "color-mix(in oklab, var(--bad) 8%, var(--bg-1))",
            display: "flex", alignItems: "center", gap: 14, padding: 14,
          }}>
            <div className="alarm-pulse" style={{
              width: 40, height: 40, borderRadius: "50%",
              background: "color-mix(in oklab, var(--bad) 20%, transparent)",
              color: "#fca5a5", display: "grid", placeItems: "center",
              border: "1px solid var(--bad)",
            }}>
              <Icon name="alert" size={18} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: "#fecaca" }}>C-208 · Door open without scheduled access</div>
              <div style={{ fontSize: 12, color: "var(--tx-2)", marginTop: 2 }}>
                Tenant: Yuki Ito · Last access 4 days ago · Sensor triggered at 08:24
              </div>
            </div>
            <button className="btn ghost">Acknowledge</button>
            <button className="btn">View camera</button>
            <button className="btn primary">Dispatch</button>
          </div>

          {/* Cameras */}
          <div className="card">
            <div className="card-h">
              <div className="card-t">Cameras</div>
              <div className="card-actions">
                <span className="chip ok"><span className="d" /> 5 online</span>
                <span className="chip bad"><span className="d" /> 1 offline</span>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 10 }}>
              {cameras.map(c => (
                <div key={c.id} style={{
                  background: "var(--bg-0)", borderRadius: 8,
                  border: "1px solid var(--line-1)", overflow: "hidden",
                  position: "relative", aspectRatio: "16 / 10",
                }}>
                  {/* Fake camera image */}
                  <div style={{
                    position: "absolute", inset: 0,
                    background: c.online
                      ? "radial-gradient(ellipse at 50% 60%, rgba(80,90,140,0.3), rgba(20,22,30,1) 70%)"
                      : "var(--bg-2)",
                  }}>
                    {c.online && (
                      <>
                        <div style={{
                          position: "absolute", left: 0, right: 0, bottom: "20%",
                          height: 1, background: "rgba(255,255,255,0.05)"
                        }} />
                        <div style={{
                          position: "absolute", left: "30%", top: "30%",
                          width: 30, height: 50, background: "rgba(120,130,180,0.15)",
                          borderRadius: 4,
                        }} />
                      </>
                    )}
                    {!c.online && (
                      <div style={{
                        position: "absolute", inset: 0, display: "grid", placeItems: "center",
                        color: "var(--tx-3)", fontSize: 11,
                      }}>
                        <div style={{ textAlign: "center" }}>
                          <Icon name="alert" size={18} />
                          <div style={{ marginTop: 4 }}>Offline</div>
                        </div>
                      </div>
                    )}
                  </div>
                  <div style={{
                    position: "absolute", top: 6, left: 6, right: 6,
                    display: "flex", justifyContent: "space-between", alignItems: "center",
                    fontSize: 10, fontFamily: "var(--font-mono)",
                  }}>
                    <span style={{ color: "rgba(255,255,255,0.7)" }}>{c.id}</span>
                    {c.online && (
                      <span style={{ color: "#fca5a5", display: "flex", alignItems: "center", gap: 4 }}>
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#ef4444" }}
                              className="alarm-pulse" /> REC
                      </span>
                    )}
                  </div>
                  <div style={{
                    position: "absolute", bottom: 6, left: 6,
                    fontSize: 11, color: "white",
                    background: "rgba(0,0,0,0.4)", padding: "2px 6px", borderRadius: 4,
                  }}>{c.label}</div>
                  {c.motion && (
                    <div style={{
                      position: "absolute", bottom: 6, right: 6,
                      fontSize: 10, color: "#fbbf24",
                      background: "rgba(0,0,0,0.4)", padding: "2px 6px", borderRadius: 4,
                    }}>motion</div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Lock health */}
          <div className="card">
            <div className="card-h">
              <div className="card-t">Smart lock health</div>
              <div className="card-actions">
                <span className="chip">522 locks</span>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10 }}>
              {[
                { l: "Online",        v: "517", c: "#10b981" },
                { l: "Battery low",   v: "8",   c: "#fbbf24" },
                { l: "Offline",       v: "5",   c: "#ef4444" },
                { l: "Predicted fail",v: "3",   c: "var(--violet)" },
              ].map((x, i) => (
                <div key={i} style={{
                  padding: 14, background: "var(--bg-2)", borderRadius: 8,
                  border: "1px solid var(--line-1)",
                }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "var(--tx-2)" }}>
                    <span style={{ width: 8, height: 8, borderRadius: 99, background: x.c }} />
                    {x.l}
                  </div>
                  <div style={{ fontSize: 22, fontWeight: 600, marginTop: 6 }} className="tnum">{x.v}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Realtime event log */}
        <div className="card" style={{ padding: 0, display: "flex", flexDirection: "column" }}>
          <div className="card-h" style={{ padding: 14, marginBottom: 0, borderBottom: "1px solid var(--line-1)" }}>
            <div className="card-t">Live event log</div>
            <span className="live-indicator"><span className="pulse" /> Live</span>
          </div>
          <div style={{ flex: 1, overflow: "auto", padding: "8px 12px" }}>
            {liveEvents.map((e, i) => (
              <div key={i} style={{
                display: "grid", gridTemplateColumns: "70px 1fr",
                gap: 8, padding: "8px 0",
                borderBottom: i < liveEvents.length - 1 ? "1px solid var(--line-1)" : "none",
              }}>
                <div className="mono" style={{ color: "var(--tx-3)", fontSize: 11 }}>{e.t}</div>
                <div>
                  <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
                    <span style={{
                      width: 6, height: 6, borderRadius: 99,
                      background: e.st === "ok" ? "#10b981" : e.st === "bad" ? "#ef4444" : "#fbbf24",
                    }} />
                    <span style={{ fontSize: 12, fontWeight: 500 }}>{e.g}</span>
                    <span className="mono" style={{ fontSize: 10.5, color: "var(--tx-3)", marginLeft: "auto" }}>{e.u}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--tx-2)", marginTop: 2 }}>
                    {e.e}{e.who && e.who !== "—" ? ` · ${e.who}` : ""}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// =============================================================
// Portfolio (multi-site)
// =============================================================
const Portfolio = () => {
  const totalUnits = V_SITES.reduce((s, x) => s + x.units, 0);
  const avgOcc = Math.round(V_SITES.reduce((s, x) => s + x.occ, 0) / V_SITES.length);
  return (
    <div data-screen-label="Portfolio" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Portfolio</h1>
          <div className="page-sub">{V_SITES.length} facilities · {totalUnits} units · {avgOcc}% avg occupancy</div>
        </div>
        <div className="head-actions">
          <button className="btn"><Icon name="filter" size={14} /> All regions</button>
          <button className="btn primary"><Icon name="plus" size={14} /> Add facility</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
        {[
          { l: "Total units",  v: totalUnits, t: [500,510,520,530,540,548,556,564,568] },
          { l: "Avg occupancy",v: `${avgOcc}%`, t: [82,83,84,85,86,86,86,86,87], c: "#10b981" },
          { l: "Portfolio NOI",v: "$284K",  t: [240,250,255,260,265,270,275,280,284], c: "var(--accent-400)" },
          { l: "Open alerts",  v: V_SITES.reduce((s,x) => s + x.alerts, 0), c: "#fbbf24", t: [12,11,10,11,10,9,10,9,10] },
        ].map((k, i) => <window.SharedUI.KPI key={i} label={k.l} val={k.v} trend={k.t} trendColor={k.c} />)}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
        {V_SITES.map(s => (
          <div key={s.id} className="card" style={{ position: "relative", cursor: "pointer" }}>
            <div className="card-h">
              <div>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{s.city}</div>
                <div style={{ fontSize: 11, color: "var(--tx-3)" }}>
                  {s.units} units · {s.climate ? "Climate" : "Standard"}
                </div>
              </div>
              <div className="card-actions">
                {s.alerts > 0 && <span className="chip bad"><span className="d" /> {s.alerts}</span>}
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginTop: 8 }}>
              <div>
                <div style={{ fontSize: 10.5, color: "var(--tx-3)" }}>Occupancy</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 6 }}>
                  <div style={{ fontSize: 22, fontWeight: 600 }} className="tnum">{s.occ}%</div>
                  <span className={`chip ${s.deltaOcc >= 0 ? "ok" : "bad"}`} style={{padding:"1px 5px"}}>
                    {s.deltaOcc >= 0 ? "+" : ""}{s.deltaOcc}
                  </span>
                </div>
                <div className="bar" style={{ marginTop: 8 }}><span style={{ width: `${s.occ}%` }} /></div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: "var(--tx-3)" }}>RevPAM</div>
                <div style={{ fontSize: 22, fontWeight: 600 }} className="tnum">${s.revPam}</div>
                <div style={{ marginTop: 4 }}>
                  <window.SharedUI.Sparkline data={s.trend} color="var(--accent-400)" w={120} h={28}/>
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// =============================================================
// Analytics
// =============================================================
const Analytics = () => {
  const months = ["Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May"];
  return (
    <div data-screen-label="Analytics" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="page-head">
        <div>
          <h1 className="page-title">Analytics</h1>
          <div className="page-sub">Revenue · Churn · Operations · last 12 months</div>
        </div>
        <div className="head-actions">
          <button className="btn"><Icon name="calendar" size={14} /> Last 12 mo</button>
          <button className="btn ghost"><Icon name="external" size={14} /> Export</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-h">
            <div className="card-t">RevPAM · 12 month trend</div>
            <div className="card-actions">
              <span className="chip">All zones</span>
              <span className="chip ok">+12.4% YoY</span>
            </div>
          </div>
          <RevpamChart months={months} />
        </div>

        <div className="card">
          <div className="card-h"><div className="card-t">Forecast · next 90 days</div></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
            {[
              { l: "Projected occupancy", v: "94.2%", d: "+2.1pp", c: "#10b981" },
              { l: "Move-ins (forecast)", v: "62",    d: "+11",    c: "var(--accent-400)" },
              { l: "Move-outs (forecast)", v: "38",   d: "−4",     c: "#fbbf24" },
              { l: "Net unit change",     v: "+24",   d: "",       c: "#10b981" },
              { l: "RevPAM target",       v: "$41.2", d: "+$2.80", c: "var(--violet)" },
            ].map((x, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", justifyContent: "space-between",
                padding: "10px 12px", background: "var(--bg-2)",
                border: "1px solid var(--line-1)", borderRadius: 7,
              }}>
                <div style={{ fontSize: 12, color: "var(--tx-2)" }}>{x.l}</div>
                <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
                  <div style={{ fontSize: 16, fontWeight: 600 }} className="tnum">{x.v}</div>
                  {x.d && <span className="chip ok" style={{padding:"1px 5px"}}>{x.d}</span>}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
        <div className="card">
          <div className="card-h"><div className="card-t">Churn signals</div></div>
          <div style={{ fontSize: 22, fontWeight: 600 }} className="tnum">5.4%</div>
          <div style={{ fontSize: 11, color: "var(--tx-3)", marginBottom: 12 }}>annual churn rate · 0.6pp lower than industry</div>
          {[
            ["Reduced access frequency", 24],
            ["Late payment 1+ time",     31],
            ["Downsized to smaller unit",  9],
            ["Moved out of region",        7],
          ].map(([l, n], i) => (
            <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0", fontSize: 12, borderBottom: i < 3 ? "1px solid var(--line-1)" : "none" }}>
              <span style={{ color: "var(--tx-2)" }}>{l}</span>
              <span className="tnum">{n}</span>
            </div>
          ))}
        </div>
        <div className="card">
          <div className="card-h"><div className="card-t">Competitor pricing</div></div>
          {[
            { name: "Storage King Newmarket", d: "+7%", base: 85, you: 82 },
            { name: "Kennards CBD",            d: "+2%", base: 70, you: 82 },
            { name: "National Storage K Rd",   d: "0%",  base: 60, you: 82 },
            { name: "SmartStor Parnell",       d: "+4%", base: 75, you: 82 },
          ].map((c, i) => (
            <div key={i} style={{ padding: "8px 0", borderBottom: i < 3 ? "1px solid var(--line-1)" : "none" }}>
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}>
                <span>{c.name}</span><span className={`chip ${c.d.startsWith("+") ? "warn" : ""}`}>{c.d}</span>
              </div>
              <div style={{ display: "flex", gap: 4, alignItems: "center", marginTop: 6 }}>
                <div className="bar" style={{ flex: 1, height: 4 }}><span style={{ width: `${c.base}%`, background: "var(--tx-3)" }} /></div>
                <span className="mono" style={{fontSize:10,color:"var(--tx-3)"}}>them</span>
              </div>
              <div style={{ display: "flex", gap: 4, alignItems: "center", marginTop: 4 }}>
                <div className="bar" style={{ flex: 1, height: 4 }}><span style={{ width: `${c.you}%`, background: "var(--accent-500)" }} /></div>
                <span className="mono" style={{fontSize:10,color:"var(--accent-300)"}}>you</span>
              </div>
            </div>
          ))}
        </div>
        <div className="card">
          <div className="card-h"><div className="card-t">Move-in heatmap · day × hour</div></div>
          <MoveInHeatmap />
        </div>
      </div>
    </div>
  );
};

const RevpamChart = ({ months }) => {
  const data = [28.4, 29.1, 29.8, 30.2, 30.9, 31.5, 32.4, 33.8, 34.6, 35.9, 37.1, 38.4];
  const forecast = [38.4, 39.2, 40.1, 41.2];
  const all = [...data, ...forecast.slice(1)];
  const max = Math.max(...all), min = Math.min(...all);
  const W = 600, H = 200, pad = 24;
  const x = (i) => pad + (i / (all.length - 1)) * (W - pad * 2);
  const y = (v) => H - pad - ((v - min) / (max - min)) * (H - pad * 2);
  const path = data.map((v, i) => `${i === 0 ? "M" : "L"}${x(i)} ${y(v)}`).join(" ");
  const fcastPath = forecast.map((v, i) => `${i === 0 ? "M" : "L"}${x(i + data.length - 1)} ${y(v)}`).join(" ");

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", display: "block" }}>
      <defs>
        <linearGradient id="rg" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="var(--accent-500)" stopOpacity="0.4" />
          <stop offset="1" stopColor="var(--accent-500)" stopOpacity="0" />
        </linearGradient>
      </defs>
      {/* gridlines */}
      {[0,0.25,0.5,0.75,1].map((g, i) => (
        <g key={i}>
          <line x1={pad} x2={W-pad} y1={pad + g*(H-pad*2)} y2={pad + g*(H-pad*2)} stroke="var(--line-1)" strokeDasharray="2 4"/>
        </g>
      ))}
      <path d={`${path} L${x(data.length-1)} ${H-pad} L${x(0)} ${H-pad} Z`} fill="url(#rg)" />
      <path d={path} fill="none" stroke="var(--accent-500)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      <path d={fcastPath} fill="none" stroke="var(--violet)" strokeWidth="2" strokeDasharray="4 4" />
      {data.map((v, i) => (
        <circle key={i} cx={x(i)} cy={y(v)} r={2.5} fill="var(--bg-1)" stroke="var(--accent-500)" strokeWidth="1.5" />
      ))}
      {months.map((m, i) => (
        <text key={i} x={x(i)} y={H - 6} fontSize="9" fill="var(--tx-3)" textAnchor="middle">{m}</text>
      ))}
      <text x={W-pad} y={pad - 6} fontSize="10" fill="var(--violet)" textAnchor="end">forecast →</text>
    </svg>
  );
};

const MoveInHeatmap = () => {
  const days = ["M","T","W","T","F","S","S"];
  const hours = ["8","10","12","14","16","18"];
  const seedH = (a,b) => ((a*7+b*13+3)%17)/17;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "20px repeat(6, 1fr)", gap: 4 }}>
      <div></div>
      {hours.map((h,i) => <div key={i} style={{fontSize:10,color:"var(--tx-3)",textAlign:"center"}}>{h}</div>)}
      {days.map((d, di) => (
        <Fragment key={di}>
          <div style={{fontSize:10,color:"var(--tx-3)",alignSelf:"center"}}>{d}</div>
          {hours.map((_, hi) => {
            const v = seedH(di, hi) + (di === 5 ? 0.4 : 0) + (hi === 2 || hi === 4 ? 0.2 : 0);
            return (
              <div key={hi} style={{
                aspectRatio: "1",
                background: `color-mix(in oklab, var(--accent-500) ${Math.min(v*100, 80)}%, var(--bg-2))`,
                borderRadius: 3,
              }} />
            );
          })}
        </Fragment>
      ))}
    </div>
  );
};

// =============================================================
// Generic placeholder for other nav targets
// =============================================================
const Placeholder = ({ name, icon }) => (
  <div data-screen-label={name} style={{ display: "flex", flexDirection: "column", gap: 14 }}>
    <div className="page-head">
      <div>
        <h1 className="page-title">{name}</h1>
        <div className="page-sub">This surface lives here in the IA — design pending.</div>
      </div>
    </div>
    <div className="card" style={{ padding: 80, textAlign: "center", color: "var(--tx-3)" }}>
      <div style={{ display: "inline-flex", padding: 18, borderRadius: 14, background: "var(--bg-2)", marginBottom: 14 }}>
        <Icon name={icon} size={28} />
      </div>
      <div style={{ fontSize: 14, color: "var(--tx-2)", marginBottom: 4 }}>{name} workspace</div>
      <div style={{ fontSize: 12 }}>Designs will be built here in the next iteration. Try Dashboard, Map, Customers, Billing, Automation, or Access for now.</div>
    </div>
  </div>
);

window.Views = { UnitPanel, Customers, Billing, Automation, Access, Portfolio, Analytics, Placeholder };
