// Workflow builder, Visitors table, other misc pages

function WorkflowBuilder() {
  const [selected, setSelected] = useState("n2");
  const nodes = [
    { id: "n1", type: "trigger",  title: "Invitation sent",  desc: "Host creates invite",              x: 40,  y: 60,  dot: "var(--accent)" },
    { id: "n2", type: "form",     title: "Visitor form",     desc: "Pre-registration · NDA + ID",       x: 260, y: 60,  dot: "oklch(65% 0.13 260)" },
    { id: "n3", type: "approval", title: "Host confirms",    desc: "Auto-approve if internal",          x: 480, y: 60,  dot: "var(--amber)" },
    { id: "n4", type: "branch",   title: "Risk check",       desc: "Watchlist + country of origin",     x: 700, y: 60,  dot: "var(--violet)" },
    { id: "n5", type: "approval", title: "Security review",  desc: "SLA: 30 minutes",                   x: 700, y: 200, dot: "var(--amber)" },
    { id: "n6", type: "approval", title: "Legal NDA",        desc: "Only if docs flagged",              x: 480, y: 200, dot: "var(--amber)" },
    { id: "n7", type: "action",   title: "Send QR pass",     desc: "Email + SMS + Wallet pass",         x: 260, y: 200, dot: "var(--green)" },
    { id: "n8", type: "check",    title: "Guard check-in",   desc: "QR or manual · 5s SLA",             x: 40,  y: 200, dot: "var(--green)" },
    { id: "n9", type: "action",   title: "Notify signage",   desc: "Lobby + floor TVs",                 x: 40,  y: 340, dot: "oklch(65% 0.13 185)" },
    { id: "n10", type: "end",     title: "On site",          desc: "Visitor record live",               x: 260, y: 340, dot: "var(--ink-3)" },
  ];
  const edges = [
    ["n1","n2"], ["n2","n3"], ["n3","n4"], ["n4","n5"], ["n5","n6"], ["n6","n7"], ["n7","n8"], ["n8","n9"], ["n9","n10"],
  ];
  const sel = nodes.find(n => n.id === selected);

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Workflow Engine</h1>
          <div className="page-subtitle">Standard visitor flow · AXS Holdings HQ · v12 · Draft</div>
        </div>
        <div className="hstack">
          <button className="btn ghost">Version history</button>
          <button className="btn">Test run</button>
          <button className="btn primary"><I.Check size={14}/> Publish</button>
        </div>
      </div>

      <div className="tabs">
        <div className="tab active">Standard</div>
        <div className="tab">Secure</div>
        <div className="tab">VIP Fast-Track</div>
        <div className="tab">Contractor (multi-day)</div>
        <div className="tab">+ New workflow</div>
      </div>

      <div style={{display: "grid", gridTemplateColumns: "1fr 320px", gap: 16}}>
        <div className="flow-canvas">
          <svg style={{position: "absolute", inset: 0, pointerEvents: "none"}} width="100%" height="100%">
            {edges.map(([a, b], i) => {
              const na = nodes.find(n => n.id === a);
              const nb = nodes.find(n => n.id === b);
              const x1 = na.x + 180, y1 = na.y + 26;
              const x2 = nb.x, y2 = nb.y + 26;
              const mx = (x1 + x2) / 2;
              const path = y1 === y2
                ? `M ${x1} ${y1} L ${x2} ${y2}`
                : `M ${x1} ${y1} C ${mx} ${y1}, ${mx} ${y2}, ${x2} ${y2}`;
              return <path key={i} d={path} stroke="oklch(78% 0.02 240)" strokeWidth="1.5" fill="none" strokeDasharray={na.type === "branch" ? "4 3" : ""} />;
            })}
          </svg>
          {nodes.map(n => (
            <div key={n.id}
                 className={"flow-node" + (selected === n.id ? " selected" : "")}
                 onClick={() => setSelected(n.id)}
                 style={{top: n.y, left: n.x}}>
              <div className="title"><span className="type-dot" style={{background: n.dot}}/> {n.title}</div>
              <div className="desc">{n.desc}</div>
              <div style={{fontSize: 10.5, color: "var(--ink-4)", marginTop: 6, fontFamily: "var(--font-mono)", textTransform: "uppercase", letterSpacing: "0.05em"}}>{n.type}</div>
            </div>
          ))}
          <div style={{position: "absolute", top: 12, right: 12, display: "flex", gap: 6}}>
            <div className="btn sm"><I.Plus size={13}/> Add step</div>
            <div className="btn sm ghost">Fit</div>
          </div>
        </div>

        <div className="card" style={{alignSelf: "start"}}>
          <div className="card-header">
            <div>
              <div className="card-title">{sel.title}</div>
              <div className="card-sub mono" style={{textTransform: "uppercase", letterSpacing: "0.05em", fontSize: 10.5}}>{sel.type} · {sel.id}</div>
            </div>
          </div>
          <div className="card-body stack-md">
            <div className="field">
              <label>Step name</label>
              <input className="input" defaultValue={sel.title}/>
            </div>
            <div className="field">
              <label>Approver</label>
              <select className="select"><option>Visitor's host</option><option>Security Admin</option><option>Legal team</option><option>Reception (guard)</option></select>
            </div>
            <div className="field">
              <label>SLA</label>
              <div className="hstack">
                <input className="input" defaultValue="30" style={{width: 80}}/>
                <select className="select" style={{width: 120}}><option>minutes</option><option>hours</option></select>
                <span className="muted" style={{fontSize: 12}}>before escalation</span>
              </div>
            </div>
            <div className="field">
              <label>Fallback on timeout</label>
              <select className="select"><option>Escalate to Security Admin</option><option>Auto-deny</option><option>Auto-approve</option></select>
            </div>
            <div className="field">
              <label>Required fields</label>
              <div className="hstack" style={{flexWrap: "wrap", gap: 6}}>
                {["Full name", "Email", "Company", "ID upload", "NDA"].map(f => (
                  <span key={f} className="pill scheduled">{f} <I.X size={10}/></span>
                ))}
                <button className="btn sm ghost"><I.Plus size={12}/> Add</button>
              </div>
            </div>
            <div className="divider"/>
            <div className="muted" style={{fontSize: 11.5}}>Last edited by Noor Khalfan · 2h ago</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Visitors({ onOpen }) {
  const [tab, setTab] = useState("all");
  const rows = VISITORS.filter(v => tab === "all" ? true : v.status === tab);
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Visitors</h1>
          <div className="page-subtitle">{VISITORS.length} total this week · 38 on site now</div>
        </div>
        <div className="hstack">
          <button className="btn ghost"><I.Filter size={14}/> Advanced filters</button>
          <button className="btn"><I.ArrowDown size={14}/> Export CSV</button>
          <button className="btn primary"><I.Plus size={14}/> New invitation</button>
        </div>
      </div>

      <div className="hstack" style={{marginBottom: 14, gap: 12}}>
        <div className="seg">
          {[
            ["all", "All"],
            ["onsite", "On site"],
            ["pending", "Pending"],
            ["approved", "Approved"],
            ["denied", "Denied"],
            ["checkedout", "Checked out"],
          ].map(([k, l]) => (
            <button key={k} className={tab === k ? "active" : ""} onClick={() => setTab(k)}>{l}</button>
          ))}
        </div>
        <div className="search" style={{flex: "0 0 280px"}}>
          <I.Search size={14}/>
          <input placeholder="Search by name, company, ID…"/>
        </div>
      </div>

      <div className="card" style={{padding: 0}}>
        <table className="table">
          <thead>
            <tr>
              <th style={{width: 24}}><input type="checkbox"/></th>
              <th>Visitor</th><th>Host</th><th>Purpose</th><th>Sched.</th><th>Destination</th><th>Status</th><th>Badge</th><th></th>
            </tr>
          </thead>
          <tbody>
            {rows.map(v => (
              <tr key={v.id} onClick={() => onOpen?.(v)} style={{cursor: "pointer"}}>
                <td onClick={e => e.stopPropagation()}><input type="checkbox"/></td>
                <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: 6, fontSize: 10}}>VIP</span>}</div>
                      <div className="muted" style={{fontSize: 12}}>{v.company} · {v.id}</div>
                    </div>
                  </div>
                </td>
                <td>{v.host}<div className="muted" style={{fontSize: 12}}>{v.hostTeam}</div></td>
                <td className="muted">{v.purpose}</td>
                <td className="tnum">{v.scheduled}<div className="muted tnum" style={{fontSize: 12}}>Arr {v.arrival}</div></td>
                <td className="muted" style={{fontSize: 12.5}}>{v.dest}</td>
                <td>
                  <span className={"pill " + v.status}><span className="dot"/>{v.status === "checkedout" ? "Checked out" : v.status[0].toUpperCase() + v.status.slice(1)}</span>
                </td>
                <td className="mono" style={{fontSize: 12, color: "var(--ink-3)"}}>{v.badge}</td>
                <td><button className="icon-btn"><I.More/></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Integrations() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Integration Hub</h1>
          <div className="page-subtitle">API-first · 8 connected · 2.1k events / min peak</div>
        </div>
        <button className="btn primary"><I.Plus size={14}/> Add integration</button>
      </div>

      <div className="kpi-grid" style={{gridTemplateColumns: "repeat(3, 1fr)"}}>
        <KPI label="Events (24h)" value="184,210" delta="Healthy" deltaDir="up"/>
        <KPI label="Failed events" value="23" delta="ServiceNow rate-limit" deltaDir="down"/>
        <KPI label="Avg latency" value="142ms" delta="−12ms" deltaDir="up"/>
      </div>

      <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12}}>
        {INTEGRATIONS.map(x => (
          <div key={x.name} className="card">
            <div style={{padding: 16, display: "grid", gridTemplateColumns: "44px 1fr auto", gap: 14, alignItems: "center"}}>
              <div style={{
                width: 44, height: 44, borderRadius: 10,
                background: "var(--surface-3)", border: "1px solid var(--border)",
                display: "grid", placeItems: "center", fontWeight: 600, color: "var(--ink-2)"
              }}>
                {x.name.split(" ").map(w => w[0]).slice(0, 2).join("")}
              </div>
              <div>
                <div style={{fontWeight: 500, fontSize: 14}}>{x.name}</div>
                <div className="muted" style={{fontSize: 12}}>{x.category} · {x.events}</div>
              </div>
              <div className="stack-sm" style={{alignItems: "flex-end"}}>
                <span className={"pill " + (x.status === "connected" ? "approved" : x.status === "warning" ? "pending" : "checkedout")}>
                  <span className="dot"/>{x.status}
                </span>
                <div className="muted" style={{fontSize: 11}}>last {x.last}</div>
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="card" style={{marginTop: 16}}>
        <div className="card-header">
          <div><div className="card-title">Event stream</div><div className="card-sub mono" style={{fontSize: 11.5}}>POST /webhook/v2/events · live</div></div>
          <button className="btn sm ghost">Pause</button>
        </div>
        <div className="mono" style={{padding: 14, fontSize: 12, background: "var(--surface-2)", color: "var(--ink-2)", maxHeight: 220, overflowY: "auto"}}>
          {[
            `09:47:02  visitor.checkin      V-10491  ➜  Lenel OnGuard     200 · 118ms`,
            `09:47:02  visitor.checkin      V-10491  ➜  Appspace          200 · 94ms`,
            `09:47:02  visitor.checkin      V-10491  ➜  Slack #lobby      200 · 163ms`,
            `09:46:58  approval.requested   A-881    ➜  Microsoft 365     200 · 82ms`,
            `09:46:44  visitor.invited      V-10513  ➜  Salto KS          200 · 210ms`,
            `09:46:22  visitor.checkout     V-10487  ➜  Lenel OnGuard     200 · 124ms`,
            `09:45:11  approval.granted     A-874    ➜  ServiceNow        429 · retry in 32s`,
            `09:44:50  visitor.checkin      V-10495  ➜  Lenel OnGuard     200 · 134ms`,
            `09:44:50  visitor.checkin      V-10495  ➜  Appspace          200 · 87ms`,
          ].map((l, i) => <div key={i}>{l}</div>)}
        </div>
      </div>
    </div>
  );
}

function Tenants() {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Tenants</h1>
          <div className="page-subtitle">White-label deployments · 4 active tenants · Capability flags per tenant</div>
        </div>
        <button className="btn primary"><I.Plus size={14}/> New tenant</button>
      </div>

      <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 14}}>
        {TENANTS_SUMMARY.map(t => (
          <div key={t.name} className="card">
            <div className="card-header">
              <div className="hstack">
                <div style={{width: 36, height: 36, borderRadius: 8, background: "var(--accent)", display: "grid", placeItems: "center", color: "#fff", fontWeight: 600}}>{t.name[0]}</div>
                <div>
                  <div style={{fontWeight: 600}}>{t.name}</div>
                  <div className="muted" style={{fontSize: 12}}>{t.sites} site{t.sites > 1 ? "s" : ""} · {t.visitorsToday} visits today</div>
                </div>
              </div>
              <span className={"pill " + (t.status === "healthy" ? "approved" : "pending")}>{t.status}</span>
            </div>
            <div className="card-body">
              <div className="muted" style={{fontSize: 11.5, marginBottom: 6}}>Capability flags</div>
              <div className="hstack" style={{flexWrap: "wrap", gap: 6}}>
                {["Forms", "Approvals", "QR check-in", "VIP", "Signage", "Lenel", "Slack", "Analytics"].map((f, i) => (
                  <span key={f} className={"pill " + (i < 6 ? "scheduled" : "checkedout")}>{i < 6 ? <I.Check size={10} sw={2.4}/> : <I.X size={10} sw={2.4}/>} {f}</span>
                ))}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Placeholder({ title, subtitle, icon: IconC }) {
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">{title}</h1>
          <div className="page-subtitle">{subtitle}</div>
        </div>
      </div>
      <div className="card">
        <div className="card-body" style={{padding: 60, textAlign: "center"}}>
          <div style={{display: "inline-flex", width: 56, height: 56, borderRadius: 14, background: "var(--surface-3)", color: "var(--ink-3)", placeItems: "center", marginBottom: 14}}>
            <IconC size={24}/>
          </div>
          <div style={{fontWeight: 600, fontSize: 16, letterSpacing: "-0.01em"}}>This section is part of the full vision</div>
          <div className="muted" style={{fontSize: 13, marginTop: 6, maxWidth: 420, marginInline: "auto"}}>
            Other sections in this prototype are fully built. Click another item in the sidebar to explore.
          </div>
        </div>
      </div>
    </div>
  );
}

function VisitorDrawer({ v, onClose }) {
  if (!v) return null;
  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <aside className="drawer">
        <div className="drawer-header">
          <div className="hstack">
            <Avatar name={v.name} size="lg"/>
            <div>
              <div style={{fontWeight: 600, fontSize: 16}}>{v.name} {v.type === "vip" && <span className="pill vip" style={{marginLeft: 6, fontSize: 10}}>VIP</span>}</div>
              <div className="muted" style={{fontSize: 12.5}}>{v.company} · {v.id}</div>
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><I.X/></button>
        </div>
        <div className="drawer-body stack-lg">
          <div className="hstack" style={{gap: 8}}>
            <span className={"pill " + v.status}><span className="dot"/>{v.status === "checkedout" ? "Checked out" : v.status[0].toUpperCase() + v.status.slice(1)}</span>
            {v.badge !== "—" && <span className="pill mono">Badge {v.badge}</span>}
          </div>
          <div style={{display: "grid", gridTemplateColumns: "140px 1fr", gap: 10, fontSize: 13}}>
            <div className="muted">Host</div><div>{v.host} · <span className="muted">{v.hostTeam}</span></div>
            <div className="muted">Purpose</div><div>{v.purpose}</div>
            <div className="muted">Destination</div><div>{v.dest}</div>
            <div className="muted">Scheduled</div><div className="tnum">Apr 21 · {v.scheduled}</div>
            <div className="muted">Arrival</div><div className="tnum">{v.arrival}</div>
            <div className="muted">Checkout</div><div className="tnum">{v.checkout}</div>
          </div>

          <div>
            <div className="muted" style={{fontSize: 11.5, marginBottom: 8}}>Timeline</div>
            <div className="stack-sm">
              {[
                ["09:12", "Checked in — QR scan at Lobby A · Tower 1", "done"],
                ["09:14", "Badge printed · Access granted to L14", "done"],
                ["09:15", "Signage greeted guest on Floor 14", "done"],
                ["09:18", "Host notified on Slack", "done"],
                ["—", "Auto-checkout at 18:00 if not manual", "pending"],
              ].map((r, i) => (
                <div key={i} style={{display: "grid", gridTemplateColumns: "56px 1fr", gap: 10, fontSize: 13}}>
                  <div className="mono tnum muted" style={{fontSize: 11.5}}>{r[0]}</div>
                  <div>{r[1]}</div>
                </div>
              ))}
            </div>
          </div>

          <div>
            <div className="muted" style={{fontSize: 11.5, marginBottom: 8}}>QR pass</div>
            <div style={{padding: 18, border: "1px solid var(--border)", borderRadius: 10, display: "grid", gridTemplateColumns: "90px 1fr", gap: 16, alignItems: "center"}}>
              <div style={{width: 90, height: 90, background: "repeating-conic-gradient(var(--ink) 0% 25%, #fff 0% 50%) 50% / 10px 10px", borderRadius: 6, border: "1px solid var(--border)"}}/>
              <div>
                <div className="mono" style={{fontSize: 12, color: "var(--ink-2)"}}>DARA-{v.id}-0421</div>
                <div className="muted" style={{fontSize: 12, marginTop: 4}}>Valid: 08:00 – 18:00 · Single check-in</div>
                <div className="hstack" style={{marginTop: 10}}>
                  <button className="btn sm"><I.Copy size={12}/> Copy link</button>
                  <button className="btn sm"><I.Mail size={12}/> Resend email</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div className="drawer-footer">
          <button className="btn danger"><I.Logout size={13}/> Check out</button>
          <button className="btn">Reprint badge</button>
          <button className="btn primary">Message host</button>
        </div>
      </aside>
    </>
  );
}

function CmdK({ open, onClose, nav }) {
  if (!open) return null;
  const options = [
    { label: "Invite a visitor", hint: "⌘I", action: "invite", icon: I.Plus },
    { label: "Go to Live Dashboard", action: "dashboard", icon: I.Dashboard },
    { label: "Approvals · 6 pending", action: "approvals", icon: I.Approvals },
    { label: "Open VIP Fast-Track", action: "vip", icon: I.VIP },
    { label: "Workflow builder", action: "workflows", icon: I.Workflow },
    { label: "Integration hub", action: "integrations", icon: I.Integrations },
    { label: "Tenants", action: "tenants", icon: I.Tenants },
  ];
  return (
    <>
      <div className="scrim" onClick={onClose}/>
      <div className="cmdk">
        <div className="hstack" style={{padding: "14px 16px", borderBottom: "1px solid var(--border)", gap: 10}}>
          <I.Search/>
          <input autoFocus style={{flex: 1, border: 0, outline: 0, fontSize: 14, background: "transparent"}} placeholder="Search DARA…"/>
          <kbd className="pill mono" style={{fontSize: 11}}>ESC</kbd>
        </div>
        <div style={{maxHeight: 360, overflowY: "auto", padding: 6}}>
          {options.map((o, i) => (
            <div key={i} className="nav-item" style={{margin: 0}} onClick={() => { nav(o.action); onClose(); }}>
              <o.icon/>
              <span>{o.label}</span>
              {o.hint && <span className="muted mono" style={{marginLeft: "auto", fontSize: 11}}>{o.hint}</span>}
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { WorkflowBuilder, Visitors, Integrations, Tenants, Placeholder, VisitorDrawer, CmdK });
