// Data & Integrations — the Datalake surface. Shows every source NuCo reasons over,
// plus the flow into the modules. Responds to the "one platform vs 10–15 products" UVP.

function DataSources() {
  const { state, dispatch } = useApp();

  const okCount   = state.dataSources.filter(d => d.health === "ok").length;
  const warnCount = state.dataSources.filter(d => d.health === "warn").length;
  const regulatory = state.dataSources.filter(d => d.type === "Regulatory").length;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow">Datalake · live sources</div>
          <h1 className="page-title" style={{ marginTop: 4 }}>Data & Integrations</h1>
          <div className="page-sub">{state.dataSources.length} sources in sync · {okCount} healthy · {warnCount} attention · one platform, not 10–15 point products.</div>
        </div>
        <div className="hstack">
          <button className="btn" onClick={() => dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: "Data map exported · Mermaid + PDF" } })}><Icon name="download" size={13} /> Data map</button>
          <button className="btn primary" onClick={() => dispatch({ type: "PUSH_TOAST", toast: { tone: "ai", text: "Source wizard opening · coming soon" } })}><Icon name="plus" size={13} /> Add source</button>
        </div>
      </div>

      {/* KPIs */}
      <div className="grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))", gap: 16, marginBottom: 20 }}>
        <div className="kpi">
          <div className="kpi-label">Sources live</div>
          <div className="kpi-value">{state.dataSources.length}</div>
          <div className="kpi-delta"><span className="tone-up">▲ {okCount} healthy</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Regulatory feeds</div>
          <div className="kpi-value" style={{ fontSize: 28 }}>{regulatory}</div>
          <div className="kpi-delta">AHPRA · VEVO · ATO · SCHADS · AusCheck · NDIS</div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Avg sync latency</div>
          <div className="kpi-value" style={{ fontSize: 28 }}>4<span className="unit">min</span></div>
          <div className="kpi-delta"><span className="tone-up">▼ well under SLA</span></div>
        </div>
        <div className="kpi">
          <div className="kpi-label">Fallback to manual</div>
          <div className="kpi-value" style={{ fontSize: 28 }}>0<span className="unit">events</span></div>
          <div className="kpi-delta">Last 30 days</div>
        </div>
      </div>

      {/* Data flow visual — CSS grid, fully responsive. */}
      <div className="card" style={{ marginBottom: 20 }}>
        <div className="card-head">
          <div>
            <div className="card-title">How data flows</div>
            <div className="card-sub">External sources → NuCo Datalake → every module, in real time</div>
          </div>
          <Badge tone="ai" dot>live</Badge>
        </div>
        <div className="card-body">
          <div className="dataflow">
            <div className="dataflow-col">
              <div className="dataflow-label">Sources</div>
              {state.dataSources.slice(0, 6).map(d => (
                <div key={d.id} className="dataflow-node">
                  <Icon name="link" size={11} />
                  <span>{d.name.split(" · ")[0]}</span>
                </div>
              ))}
            </div>
            <div className="dataflow-edge"><Icon name="arrowRight" size={14} /></div>
            <div className="dataflow-col center">
              <div className="dataflow-label">Datalake</div>
              <div className="dataflow-hub">
                <Icon name="sparkle" size={18} />
                <div style={{ fontWeight: 600, fontSize: 13, marginTop: 6 }}>NuCo core</div>
                <div className="sub" style={{ fontSize: 11 }}>rules · events · state</div>
              </div>
            </div>
            <div className="dataflow-edge"><Icon name="arrowRight" size={14} /></div>
            <div className="dataflow-col">
              <div className="dataflow-label">Modules</div>
              {["Roster", "Payroll", "People", "Compliance", "Agents", "Reports"].map(m => (
                <div key={m} className="dataflow-node" onClick={() => dispatch({ type: "SET_PAGE", page: m.toLowerCase() === "people" ? "people" : m.toLowerCase() })} style={{ cursor: "pointer" }}>
                  <Icon name="arrowRight" size={10} />
                  <span>{m}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Sources table */}
      <div className="card scroll">
        <div className="card-head">
          <div>
            <div className="card-title">Live sources</div>
            <div className="card-sub">Each source is monitored continuously · health + freshness + record counts</div>
          </div>
        </div>
        <div className="table-scroll" style={{ maxHeight: "none" }}>
          <table className="table">
            <thead>
              <tr><th>Source</th><th>Type</th><th>Mode</th><th>Records</th><th>Freshness</th><th>Health</th><th></th></tr>
            </thead>
            <tbody>
              {state.dataSources.map(d => (
                <tr key={d.id}>
                  <td>
                    <div style={{ fontWeight: 500, fontSize: 12.5 }}>{d.name}</div>
                    <div className="sub" style={{ fontSize: 11 }}>{d.note}</div>
                  </td>
                  <td><Badge tone={d.type === "Regulatory" ? "warn" : d.type === "Finance" ? "ink" : d.type === "Clinical" ? "ai" : undefined}>{d.type}</Badge></td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{d.mode}</td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{d.records}</td>
                  <td className="mono" style={{ fontSize: 11.5 }}>{d.freshness}</td>
                  <td><Badge tone={d.health} dot>{d.health === "ok" ? "healthy" : d.health === "warn" ? "delayed" : "down"}</Badge></td>
                  <td>
                    <div className="hstack" style={{ gap: 4 }}>
                      <button className="btn" style={{ padding: "3px 8px", fontSize: 11 }} onClick={() => { dispatch({ type: "SYNC_DATA_SOURCE", id: d.id }); dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: `Synced · ${d.name}` } }); }}>Sync now</button>
                      <button className="btn ghost" style={{ padding: "3px 8px", fontSize: 11 }} onClick={() => dispatch({ type: "PUSH_TOAST", toast: { tone: "ok", text: `Test connection · ${d.name} · 200 OK` } })}>Test</button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Outbound — webhooks & exports */}
      <div className="card" style={{ marginTop: 20 }}>
        <div className="card-head">
          <div>
            <div className="card-title">Outbound · webhooks & exports</div>
            <div className="card-sub">Where NuCo pushes data</div>
          </div>
        </div>
        <div className="card-body grid" style={{ gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 }}>
          {[
            { name: "ATO · Single Touch Payroll", every: "Every pay run",    next: "Today 17:00", tone: "ok" },
            { name: "HESTA · super contributions", every: "Monthly 28th",     next: "28 Apr",      tone: "ok" },
            { name: "Board pack · Slack + email",  every: "Monthly 5th",      next: "05 May",      tone: "ok" },
            { name: "Xero · journal entries",      every: "Daily 23:00",      next: "Tonight",     tone: "ok" },
            { name: "Slack · exceptions feed",     every: "Real-time",        next: "live",        tone: "ok" },
          ].map(w => (
            <div key={w.name} className="vstack" style={{ gap: 4, padding: 10, background: "var(--bone)", borderRadius: 6, border: "1px solid var(--line)" }}>
              <div style={{ fontSize: 12.5, fontWeight: 500 }}>{w.name}</div>
              <div className="sub mono" style={{ fontSize: 10.5 }}>{w.every} · next {w.next}</div>
              <Badge tone={w.tone} dot style={{ alignSelf: "flex-start" }}>healthy</Badge>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DataSources });
