// urlapi.me — TrackingHealth (visual dashboard, no matrix-of-boxes)
// 「売上を伸ばす前に、まず正しく測れるECへ。」

const { useState: dgUS, useEffect: dgUE, useRef: dgUR } = React;

function TrackingHealth() {
  const [mode, setMode] = dgUS("after"); // "before" | "after"

  // 計測スコア・チャート系列(7d × 5 platform)
  const SERIES_BEFORE = {
    Meta:   [60,55,58,40,42,38,35],
    Google: [80,78,82,72,70,68,72],
    LINE:   [25,28,22,18,20,24,18],
    TikTok: [15,12,10,8,12,10,8],
    GA4:    [88,86,85,82,80,78,75],
  };
  const SERIES_AFTER = {
    Meta:   [62,68,75,84,90,94,98],
    Google: [78,82,88,92,95,97,98],
    LINE:   [30,42,58,72,86,94,99],
    TikTok: [20,38,55,72,86,95,99],
    GA4:    [85,88,92,95,97,98,99],
  };
  const data = mode === "after" ? SERIES_AFTER : SERIES_BEFORE;
  const platforms = ["Meta","Google","LINE","TikTok","GA4"];
  const colors = {
    Meta:   "#1877F2",
    Google: "#EA4335",
    LINE:   "#06C755",
    TikTok: "#FF0050",
    GA4:    "#A88BFF",
  };

  // スコア計算
  const allVals = platforms.flatMap(p => data[p]);
  const score = Math.round(allVals.reduce((a,b)=>a+b,0) / allVals.length);
  const scoreFg = score >= 85 ? "var(--success)" : score >= 60 ? "var(--warn)" : "var(--danger)";

  // ライブイベントフィード
  const events = mode === "after" ? [
    { p: "Meta",   ev: "Purchase",       v: "¥4,980", t: "2s",  ok: true },
    { p: "Google", ev: "BeginCheckout",  v: "—",      t: "5s",  ok: true },
    { p: "LINE",   ev: "AddToCart",      v: "—",      t: "8s",  ok: true },
    { p: "TikTok", ev: "Purchase",       v: "¥2,480", t: "14s", ok: true },
    { p: "GA4",    ev: "view_item",      v: "—",      t: "21s", ok: true },
    { p: "Meta",   ev: "Purchase",       v: "¥8,400", t: "33s", ok: true },
  ] : [
    { p: "Meta",   ev: "Purchase",       v: "FAIL",   t: "2s",  ok: false },
    { p: "Google", ev: "BeginCheckout",  v: "PARTIAL",t: "5s",  ok: "warn" },
    { p: "GA4",    ev: "view_item",      v: "—",      t: "8s",  ok: true },
    { p: "Meta",   ev: "AddToCart",      v: "MISS",   t: "14s", ok: false },
    { p: "LINE",   ev: "—",              v: "—",      t: "21s", ok: "warn" },
    { p: "TikTok", ev: "—",              v: "OFFLINE",t: "33s", ok: false },
  ];

  // パスを SVG ラインに変換
  const chartW = 520, chartH = 180;
  const toPath = (arr) => {
    const max = 100;
    return arr.map((v, i) => {
      const x = (i / (arr.length - 1)) * chartW;
      const y = chartH - (v / max) * chartH;
      return `${i === 0 ? "M" : "L"} ${x.toFixed(1)} ${y.toFixed(1)}`;
    }).join(" ");
  };

  return (
    <section id="tracking-health" style={{ padding: "16px 0 32px", position: "relative" }}>
      {/* Soft purple glow background instead of borders/cards */}
      <div style={{ position: "absolute", inset: 0, pointerEvents: "none",
        background: "radial-gradient(ellipse 1000px 600px at 50% 30%, rgba(124,92,255,0.10), transparent 70%)" }} />

      <div className="wrap" style={{ position: "relative" }}>
        {/* Heading — unified with other About panels */}
        <div style={{ textAlign: "center", maxWidth: 880, marginInline: "auto", marginBottom: 36 }}>
          <div className="mono" style={{ fontSize: 11, color: "var(--accent-2)", letterSpacing: 0.2, marginBottom: 10, textTransform: "uppercase" }}>
            結局、何ができるのか
          </div>
          <h2 className="display" style={{ fontSize: "clamp(26px, 4.2vw, 40px)", fontWeight: 700, margin: 0, letterSpacing: -0.025, lineHeight: 1.2 }}>
            売上を伸ばす前に、<br />まず正しく測れる EC へ。
          </h2>
          <p style={{ fontSize: 14.5, color: "var(--text-mid)", marginTop: 16, lineHeight: 1.7, maxWidth: 640, marginInline: "auto" }}>
            広告費をかけても、CV計測がズレていれば広告AIは正しく学習できません。<br />
            <strong style={{ color: "var(--text)", fontWeight: 600 }}>計測の健全性</strong>を、ひとつのダッシュボードで。
          </p>
        </div>

        {/* The Dashboard — single big visual replacing all the cards */}
        <div className="th-dash" style={{
          marginTop: 48, maxWidth: 1180, marginInline: "auto",
          background: "linear-gradient(180deg, rgba(17,17,24,0.7), rgba(11,11,16,0.9))",
          border: "1px solid var(--border-strong)",
          borderRadius: 20, overflow: "hidden",
          boxShadow: "0 50px 120px -30px rgba(0,0,0,0.7), 0 0 80px -30px var(--accent-glow), inset 0 1px 0 rgba(255,255,255,0.04)",
          position: "relative",
        }}>
          {/* Browser bar */}
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 18px", background: "rgba(0,0,0,0.35)", borderBottom: "1px solid var(--border)" }}>
            <span style={{ width: 11, height: 11, borderRadius: 6, background: "#FF5F57" }} />
            <span style={{ width: 11, height: 11, borderRadius: 6, background: "#FEBC2E" }} />
            <span style={{ width: 11, height: 11, borderRadius: 6, background: "#28C840" }} />
            <div className="mono" style={{ flex: 1, textAlign: "center", fontSize: 11, color: "var(--text-mute)" }}>
              app.urlapi.me / tracking-health
            </div>
            {/* Mode toggle (inline, not a separate card) */}
            <div className="mono" style={{ display: "inline-flex", padding: 3, background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 999 }}>
              {[
                { k: "before", l: "Before" },
                { k: "after",  l: "After" },
              ].map(t => (
                <button key={t.k} onClick={() => setMode(t.k)} className="mono" style={{
                  padding: "4px 12px",
                  background: mode === t.k ? (t.k === "after" ? "linear-gradient(135deg, var(--accent), var(--accent-2))" : "var(--bg-3)") : "transparent",
                  color: mode === t.k ? (t.k === "after" ? "white" : "var(--text)") : "var(--text-mute)",
                  border: "none", borderRadius: 999, fontSize: 10.5, fontWeight: 600, letterSpacing: 0.04, cursor: "pointer",
                  transition: "all .2s",
                }}>{t.l}</button>
              ))}
            </div>
          </div>

          {/* Dashboard body */}
          <div className="th-dashbody" style={{ display: "grid", gridTemplateColumns: "300px 1fr 320px", minHeight: 460 }}>

            {/* ── Left: Score gauge ─────────────────────── */}
            <div className="th-col" style={{ padding: "28px 24px", borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 22 }}>
              <div>
                <div className="mono" style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: 0.16, textTransform: "uppercase" }}>Tracking Health</div>
                <div className="mono" style={{ fontSize: 10, color: "var(--text-dim)", marginTop: 2 }}>last 7 days · 5 platforms</div>
              </div>

              {/* Big gauge */}
              <div style={{ position: "relative", width: "100%", aspectRatio: "1 / 1", maxWidth: 220, marginInline: "auto" }}>
                <svg viewBox="0 0 200 200" width="100%" height="100%" style={{ transform: "rotate(-90deg)" }}>
                  <circle cx="100" cy="100" r="86" fill="none" stroke="var(--bg-3)" strokeWidth="10" />
                  <circle cx="100" cy="100" r="86" fill="none" stroke={scoreFg} strokeWidth="10" strokeLinecap="round"
                    strokeDasharray={`${(score/100) * 540} 540`} strokeDashoffset="0"
                    style={{ transition: "stroke-dasharray 1s cubic-bezier(0.65, 0, 0.35, 1), stroke 0.4s", filter: `drop-shadow(0 0 16px ${scoreFg})` }} />
                </svg>
                <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
                  <div style={{ textAlign: "center" }}>
                    <div className="display" style={{ fontSize: 52, fontWeight: 800, color: scoreFg, fontVariantNumeric: "tabular-nums", lineHeight: 1, transition: "color 0.4s" }}>{score}</div>
                    <div className="mono" style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: 0.14, marginTop: 4 }}>/100</div>
                  </div>
                </div>
              </div>

              {/* Insight under gauge */}
              <div>
                <div style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px", background: mode === "after" ? "rgba(46,230,168,0.10)" : "rgba(255,92,122,0.10)", color: mode === "after" ? "var(--success)" : "var(--danger)", borderRadius: 999, fontSize: 11, fontWeight: 600 }}>
                  {mode === "after" ? "↑ +52pt" : "↓ −41pt"}
                  <span style={{ opacity: 0.7 }}>vs ベンチマーク</span>
                </div>
                <div style={{ fontSize: 13.5, color: "var(--text-mid)", marginTop: 12, lineHeight: 1.65 }}>
                  {mode === "after"
                    ? <>全 6 イベント × 5 媒体が常時連携。<strong style={{ color: "var(--text)" }}>欠損ゼロ</strong>で広告 AI が最大効率で学習できる状態です。</>
                    : <>3 媒体で<strong style={{ color: "var(--danger)" }}>送信欠損</strong>を検出。広告 AI が誤った母集団で学習しています。</>}
                </div>
              </div>
            </div>

            {/* ── Center: chart + summary stats ─────────────── */}
            <div className="th-col th-center" style={{ padding: "24px 28px", display: "flex", flexDirection: "column", gap: 18, minWidth: 0 }}>
              {/* Top stats row */}
              <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 0, borderBottom: "1px solid var(--border)", paddingBottom: 18 }}>
                {[
                  { l: "Click → CV 到達率", v: mode === "after" ? "94.2%" : "61.4%", d: mode === "after" ? "+11.8" : "−9.6", up: mode === "after" },
                  { l: "未送信 CV",          v: mode === "after" ? "0"      : "423",   d: mode === "after" ? "−100%" : "+1820%", up: mode === "after" },
                  { l: "媒体間ズレ",        v: mode === "after" ? "1.4%"   : "24.8%", d: mode === "after" ? "−23pt" : "+18pt",  up: mode === "after" },
                  { l: "AI 学習効率",       v: mode === "after" ? "98%"    : "47%",   d: mode === "after" ? "+51"   : "−18",    up: mode === "after" },
                ].map((s, i) => (
                  <div key={i} style={{ padding: "0 14px", borderLeft: i === 0 ? "none" : "1px solid var(--border-soft)" }}>
                    <div className="mono" style={{ fontSize: 9.5, color: "var(--text-mute)", letterSpacing: 0.1, textTransform: "uppercase" }}>{s.l}</div>
                    <div className="display" style={{ fontSize: 22, fontWeight: 700, marginTop: 6, fontVariantNumeric: "tabular-nums", color: "var(--text)" }}>{s.v}</div>
                    <div className="mono" style={{ fontSize: 10, color: s.up ? "var(--success)" : "var(--danger)", marginTop: 2, letterSpacing: 0.04 }}>{s.d}</div>
                  </div>
                ))}
              </div>

              {/* Chart */}
              <div style={{ flex: 1, position: "relative", minHeight: 220 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                  <div className="mono" style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: 0.12, textTransform: "uppercase" }}>イベント到達率 · 7 日</div>
                  <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
                    {platforms.map(p => {
                      const ent = BRAND[p];
                      const L = ent ? ent.L : null;
                      return (
                        <div key={p} className="mono" style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10, color: "var(--text-mid)" }}>
                          {L ? <L size={12} /> : <span style={{ width: 8, height: 2, background: colors[p], borderRadius: 1 }} />}
                          {p}
                        </div>
                      );
                    })}
                  </div>
                </div>
                <svg viewBox={`0 0 ${chartW} ${chartH}`} width="100%" height="220" preserveAspectRatio="none" style={{ display: "block", overflow: "visible" }}>
                  {/* gridlines */}
                  {[0, 25, 50, 75, 100].map(g => {
                    const y = chartH - (g / 100) * chartH;
                    return (
                      <g key={g}>
                        <line x1="0" y1={y} x2={chartW} y2={y} stroke="var(--border-soft)" strokeWidth="1" strokeDasharray={g === 100 || g === 0 ? "" : "2 4"} />
                        <text x={chartW - 4} y={y - 4} textAnchor="end" fontSize="9" fill="var(--text-dim)" fontFamily="var(--font-mono)">{g}</text>
                      </g>
                    );
                  })}
                  {/* lines */}
                  {platforms.map(p => (
                    <path key={p} d={toPath(data[p])} fill="none" stroke={colors[p]} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transition: "d 0.6s" }} opacity={0.95}/>
                  ))}
                  {/* end-of-line dots */}
                  {platforms.map(p => {
                    const v = data[p][data[p].length - 1];
                    const y = chartH - (v / 100) * chartH;
                    return <circle key={p} cx={chartW} cy={y} r="3.5" fill={colors[p]} stroke="var(--bg-1)" strokeWidth="1.5" />;
                  })}
                </svg>
                <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6 }}>
                  {["7d ago","6d","5d","4d","3d","2d","today"].map((d, i) => (
                    <span key={i} className="mono" style={{ fontSize: 9.5, color: "var(--text-dim)" }}>{d}</span>
                  ))}
                </div>
              </div>
            </div>

            {/* ── Right: live event feed ─────────────────── */}
            <div className="th-col th-right" style={{ padding: "24px", borderLeft: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 14, background: "rgba(0,0,0,0.20)" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <div className="mono" style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: 0.16, textTransform: "uppercase" }}>Live Event Stream</div>
                <div style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10, color: mode === "after" ? "var(--success)" : "var(--danger)" }}>
                  <span style={{ width: 6, height: 6, borderRadius: 3, background: "currentColor", boxShadow: "0 0 6px currentColor", animation: "pulse 1.4s infinite" }} />
                  <span className="mono">{mode === "after" ? "HEALTHY" : "DEGRADED"}</span>
                </div>
              </div>

              <div style={{ display: "flex", flexDirection: "column", gap: 0, flex: 1 }}>
                {events.map((e, i) => {
                  const okFg = e.ok === true ? "var(--success)" : e.ok === "warn" ? "var(--warn)" : "var(--danger)";
                  const okSym = e.ok === true ? "✓" : e.ok === "warn" ? "△" : "✕";
                  const ent = BRAND[e.p];
                  const L = ent ? ent.L : null;
                  return (
                    <div key={i} className="mono" style={{
                      display: "flex", alignItems: "center", gap: 10, padding: "10px 0",
                      borderBottom: i === events.length - 1 ? "none" : "1px dashed var(--border-soft)",
                      fontSize: 11,
                    }}>
                      {L ? <L size={18} /> : <span style={{ width: 4, height: 28, borderRadius: 2, background: colors[e.p] }} />}
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 11.5, color: "var(--text)", fontWeight: 600 }}>{e.p}<span style={{ color: "var(--text-mute)", fontWeight: 400 }}> · {e.ev}</span></div>
                        <div style={{ fontSize: 10, color: "var(--text-mute)", marginTop: 2 }}>{e.v} · {e.t} ago</div>
                      </div>
                      <span style={{ color: okFg, fontWeight: 700, fontSize: 14 }}>{okSym}</span>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Bottom narrative — replaces the 4 IssueRow cards */}
          <div className="th-bottom" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, padding: "18px 28px", background: "rgba(0,0,0,0.30)", borderTop: "1px solid var(--border)", flexWrap: "wrap" }}>
            <div className="mono" style={{ fontSize: 11.5, color: "var(--text-mid)", letterSpacing: 0.04, lineHeight: 1.6 }}>
              {mode === "after" ? (
                <><span style={{ color: "var(--success)" }}>●</span> 6 イベント × 5 媒体 = 30 経路を常時監視。<span style={{ color: "var(--text)" }}>欠損・遅延・重複を AI が自動修復します。</span></>
              ) : (
                <><span style={{ color: "var(--danger)" }}>●</span> Meta CAPI 未送信 423 件 / TikTok 完全オフライン / GA4 部分欠損。<span style={{ color: "var(--text)" }}>広告 AI は誤った母集団で学習中。</span></>
              )}
            </div>
            <a href="#signup" className="mono" style={{
              padding: "8px 16px",
              background: mode === "after" ? "var(--bg-2)" : "linear-gradient(135deg, var(--accent), var(--accent-2))",
              color: mode === "after" ? "var(--text-mid)" : "white",
              border: mode === "after" ? "1px solid var(--border-strong)" : "none",
              borderRadius: 7, fontSize: 12, fontWeight: 600, textDecoration: "none", whiteSpace: "nowrap",
              boxShadow: mode === "after" ? "none" : "0 0 18px var(--accent-glow)",
              letterSpacing: 0.04,
            }}>
              {mode === "after" ? "詳細レポートを見る →" : "計測を整える →"}
            </a>
          </div>
        </div>
      </div>

      <style>{`
        @media (max-width: 1180px) {
          .th-dashbody { grid-template-columns: 1fr !important; }
          .th-col { border-right: none !important; border-left: none !important; border-bottom: 1px solid var(--border); }
          .th-right { border-bottom: none !important; }
        }
        @media (max-width: 640px) {
          .th-bottom { flex-direction: column; align-items: stretch !important; text-align: center; }
        }
      `}</style>
    </section>
  );
}

window.TrackingHealth = TrackingHealth;
