/* ============================================================
   screens-wearables.jsx — Connected Wearables & Platforms.
   Fetches connection statuses from /api/wearables/connections
   and lists all available providers. If Withings scale is connected,
   it pulls and displays dynamic weight & body fat composition charts.
   ============================================================ */
(function () {
  const { useState, useEffect, useCallback } = React;

  // Render a simple SVG line chart for weight/body fat trends.
  function SimpleCompositionChart({ data, type, color, unit, w = 320, h = 130 }) {
    if (!data || data.length === 0) {
      return (
        <div style={{ height: h, display: "grid", placeItems: "center", color: "var(--ink-4)", fontSize: 12 }}>
          No data recorded in this period
        </div>
      );
    }

    const values = data.map(d => d.value);
    const minVal = Math.min(...values);
    const maxVal = Math.max(...values);
    const valRange = maxVal - minVal || 2;
    const lo = minVal - valRange * 0.15;
    const hi = maxVal + valRange * 0.15;

    const padL = 10, padR = 32, padT = 10, padB = 18;
    const x = (i) => padL + (i / Math.max(1, data.length - 1)) * (w - padL - padR);
    const y = (v) => h - padB - ((v - lo) / (hi - lo)) * (h - padT - padB);

    const pts = data.map((d, i) => `${x(i).toFixed(1)},${y(d.value).toFixed(1)}`).join(" ");
    const ticks = [lo, (lo + hi) / 2, hi];

    return (
      <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} style={{ display: "block", overflow: "visible" }}>
        {ticks.map((t, i) => (
          <g key={i}>
            <line x1={padL} x2={w - padR} y1={y(t)} y2={y(t)} stroke="var(--c-grid)" strokeWidth="1" />
            <text x={w - padR + 4} y={y(t) + 3} fontFamily="var(--font-mono)" fontSize="9" fill="var(--c-axis)">
              {t.toFixed(1)}{unit}
            </text>
          </g>
        ))}
        <polyline points={pts} fill="none" stroke={color} strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" />
        {data.map((d, i) => (
          <g key={i}>
            <circle cx={x(i)} cy={y(d.value)} r="3" fill="var(--surface)" stroke={color} strokeWidth="1.5" />
          </g>
        ))}
      </svg>
    );
  }

  function Wearables() {
    const [connections, setConnections] = useState([]);
    const [providers, setProviders] = useState([]);
    const [bodyData, setBodyData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [err, setErr] = useState(null);

    const loadData = useCallback(async () => {
      setLoading(true);
      setErr(null);
      try {
        const [connRes, provRes] = await Promise.all([
          fetch("/api/wearables/connections", { credentials: "same-origin" }),
          fetch("/api/wearables/providers", { credentials: "same-origin" })
        ]);

        if (!connRes.ok || !provRes.ok) {
          throw new Error("Failed to fetch connection statuses.");
        }

        const connList = await connRes.json();
        const provList = await provRes.json();
        setConnections(connList);
        setProviders(provList);

        // Check if Withings scale is connected
        const isWithingsConnected = connList.some(
          c => c.provider === "withings" && c.status === "connected"
        );

        if (isWithingsConnected) {
          const end = new Date().toISOString();
          const start = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();
          const bodyRes = await fetch(
            `/api/wearables/body-composition?start_time=${start}&end_time=${end}`,
            { credentials: "same-origin" }
          );
          if (bodyRes.ok) {
            setBodyData(await bodyRes.json());
          }
        }
      } catch (e) {
        setErr(String(e));
      } finally {
        setLoading(false);
      }
    }, []);

    useEffect(() => {
      loadData();
    }, [loadData]);

    if (loading) {
      return (
        <div>
          <ScreenHead sub="connected health trackers & scales" title="Wearables" />
          <Card pad={16}><div style={{ color: "var(--ink-4)", fontSize: 13 }}>Loading settings & connections…</div></Card>
        </div>
      );
    }

    if (err) {
      return (
        <div>
          <ScreenHead sub="connected health trackers & scales" title="Wearables" />
          <Card pad={16}>
            <div style={{ color: "var(--acute-ink)", fontSize: 13, marginBottom: 8 }}>Couldn't load connection state.</div>
            <button onClick={loadData} className="occ-confirm" style={{ padding: "6px 12px", background: "var(--ink)", color: "var(--bg)", border: "none", borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: "pointer" }}>Retry</button>
          </Card>
        </div>
      );
    }

    // Process Withings Weight & Body Fat timeseries
    let weightSeries = [];
    let fatSeries = [];
    let latestWeight = null;
    let latestFat = null;

    if (bodyData && bodyData.samples) {
      // Sort chronologically
      const sorted = [...bodyData.samples].sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
      weightSeries = sorted
        .filter(s => s.type === "weight")
        .map(s => ({ value: s.value, date: new Date(s.timestamp) }));
      fatSeries = sorted
        .filter(s => s.type === "body_fat_percentage")
        .map(s => ({ value: s.value, date: new Date(s.timestamp) }));

      if (weightSeries.length > 0) latestWeight = weightSeries[weightSeries.length - 1].value;
      if (fatSeries.length > 0) latestFat = fatSeries[fatSeries.length - 1].value;
    }

    return (
      <div>
        <ScreenHead sub="connected health trackers & scales" title="Wearables" />

        {/* Dynamic Scale Metrics: weight, fat percentage */}
        {weightSeries.length > 0 && (
          <div style={{ marginBottom: 12 }}>
            <SubLabel right={latestWeight ? `${latestWeight.toFixed(1)} kg` : ""}>Withings Smart Scale: Weight</SubLabel>
            <Card pad={16}>
              <SimpleCompositionChart data={weightSeries} type="weight" color="var(--good)" unit="kg" />
            </Card>
          </div>
        )}

        {fatSeries.length > 0 && (
          <div style={{ marginBottom: 12 }}>
            <SubLabel right={latestFat ? `${latestFat.toFixed(1)} %` : ""}>Withings Smart Scale: Body Fat</SubLabel>
            <Card pad={16}>
              <SimpleCompositionChart data={fatSeries} type="body_fat" color="var(--attn)" unit="%" />
            </Card>
          </div>
        )}

        {/* Status list of active platforms */}
        <SubLabel>Connected Services</SubLabel>
        <Card pad={16} style={{ paddingTop: 6, paddingBottom: 6 }}>
          {providers.map((p) => {
            const conn = connections.find((c) => c.provider === p.id);
            const isConnected = conn && conn.status === "connected";
            const tone = isConnected ? "var(--good)" : "var(--ink-4)";
            const statusLabel = isConnected ? "CONNECTED" : "NOT CONNECTED";

            return (
              <div key={p.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 2px", borderBottom: "1px solid var(--line)" }}>
                <div>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "var(--ink)", display: "flex", alignItems: "center", gap: 6 }}>
                    {p.name}
                    <span style={{ fontSize: 9, fontWeight: 600, color: tone, border: `1px solid ${tone}`, borderRadius: 999, padding: "1px 5px" }}>
                      {statusLabel}
                    </span>
                  </div>
                  <div style={{ fontSize: 11, color: "var(--ink-4)", marginTop: 2 }}>
                    {isConnected && conn.last_sync_at 
                      ? `Last synced: ${new Date(conn.last_sync_at).toLocaleString()}`
                      : p.description}
                  </div>
                </div>
                <button
                  onClick={() => { window.location.href = `/api/switch/wearables?next=/connections`; }}
                  className="occ-tap"
                  style={{
                    padding: "6px 12px",
                    borderRadius: 999,
                    border: "1px solid var(--line)",
                    background: "var(--surface)",
                    color: "var(--ink)",
                    fontSize: 11,
                    fontWeight: 600,
                    cursor: "pointer"
                  }}
                >
                  {isConnected ? "Manage" : "Connect"}
                </button>
              </div>
            );
          })}
        </Card>

        {/* Informative connection footer */}
        <div style={{ padding: "14px 4px 28px", color: "var(--ink-4)", fontSize: 11, lineHeight: 1.45, textAlign: "center" }}>
          Connections are synced and managed through the secure <b>Open Wearables</b> core service.
        </div>
      </div>
    );
  }

  Object.assign(window, { Wearables });
})();
