// Compliance Dashboard — three-column layout

// Score color thresholds: green ≥ 80, orange 50–79, red < 50.
const scoreColor = (n) =>
  n >= 80 ? "var(--success-mint)"
  : n >= 50 ? "#F4811F"
  : "var(--red-deep)";

const Sparkline = ({ data, w = 320, h = 80, color = "var(--midnight)" }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * (h - 8) - 4;
    return [x, y];
  });
  const d = pts.map((p, i) => `${i === 0 ? "M" : "L"} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ");
  const fill = `${d} L ${w} ${h} L 0 ${h} Z`;
  return (
    <svg width={w} height={h} style={{ display: "block" }}>
      <defs>
        <linearGradient id="spark-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#0A1628" stopOpacity="0.12"/>
          <stop offset="100%" stopColor="#0A1628" stopOpacity="0"/>
        </linearGradient>
      </defs>
      <path d={fill} fill="url(#spark-fill)"/>
      <path d={d} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round"/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="3.5" fill={color}/>
      <circle cx={pts[pts.length-1][0]} cy={pts[pts.length-1][1]} r="6" fill={color} opacity="0.18"/>
    </svg>
  );
};

const TopBar = ({ active = "Compliance" }) => {
  const connected = (typeof useConnected === "function") ? useConnected() : null;
  const NAV = [
    { label: "Compliance", to: "/dashboard" },
    { label: "Inbox",      to: "/inbox" },
    { label: "Compose",    to: "/compose" },
    { label: "Settings",   to: "/settings" },
  ];

  return (
    <div style={{
      height: 64, flexShrink: 0,
      display: "flex", alignItems: "center",
      padding: "0 32px", borderBottom: "1px solid var(--gray-whisper)",
      background: "rgba(253,253,252,0.85)", backdropFilter: "blur(12px)",
    }}>
      <a href="/landing" data-link style={{
        display: "flex", alignItems: "center", gap: 11, width: 260,
        textDecoration: "none", color: "inherit", flexShrink: 0,
      }}>
        <span style={{
          width: 12, height: 12, borderRadius: 999, background: "var(--red-core)",
          boxShadow: "0 0 0 5px rgba(230,57,70,0.18)",
        }}/>
        <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em" }}>RedGone</span>
        {!connected && (
          <span className="mono" style={{
            fontSize: 9.5, letterSpacing: "0.08em", color: "var(--midnight-soft)",
            background: "var(--white-soft)", padding: "3px 6px", borderRadius: 999,
            marginLeft: 4,
          }}>DEMO</span>
        )}
      </a>

      <div style={{ flex: 1, display: "flex", justifyContent: "center", gap: 10 }}>
        {NAV.map(t => {
          const on = t.label === active;
          return (
            <a key={t.label} href={t.to} data-link
               className={`neu-tab ${on ? "on" : ""}`}
               style={{
                 textDecoration: "none",
                 padding: "8px 16px",
                 fontSize: 13,
                 color: on ? "var(--midnight)" : "var(--midnight-soft)",
               }}>
              {t.label}
            </a>
          );
        })}
      </div>

      <div style={{ width: 260, display: "flex", justifyContent: "flex-end", gap: 10, alignItems: "center", flexShrink: 0 }}>
        {connected ? (
          <a href="/settings" data-link style={{
            display: "inline-flex", alignItems: "center", gap: 10,
            padding: "6px 14px 6px 6px",
            borderRadius: 999,
            background: "var(--white-pure)",
            boxShadow: "var(--neu-out-sm)",
            textDecoration: "none", color: "inherit",
          }}
          title="Open settings">
            <span style={{
              width: 28, height: 28, borderRadius: 999,
              background: "var(--midnight)",
              display: "flex", alignItems: "center", justifyContent: "center",
              color: "#fff",
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" aria-hidden>
                <circle cx="12" cy="8.5" r="3.6" fill="#fff"/>
                <path d="M4.5 20.5c0-3.6 3.4-6.4 7.5-6.4s7.5 2.8 7.5 6.4" fill="#fff"/>
              </svg>
            </span>
            <span style={{ fontSize: 13, fontWeight: 600, color: "var(--midnight)" }}>
              {connected.name.split(" ")[0]}
            </span>
          </a>
        ) : (
          <a href="/connect" data-link className="neu-btn-redglow neu-btn-redglow-sm">
            <span>Connect Email</span>
            <span style={{ opacity: 0.85 }}>→</span>
          </a>
        )}
      </div>
    </div>
  );
};

const Dashboard = ({ width = 1440, height = 900 }) => {
  const connected = (typeof useConnected === "function") ? useConnected() : null;

  // First-time-user (connected) data: low baseline, no improvement yet, more risks.
  // Demo (unconnected) data: post-improvement steady state.
  const data = connected ? {
    score: 41,
    delta: null,           // no trend yet — just connected
    deltaLabel: "Just connected",
    sparkData: [38, 39, 36, 41, 40, 38, 42, 39, 40, 41, 38, 36, 40, 41, 39, 42, 40, 38, 41, 39, 40, 42, 38, 39, 41, 40, 38, 41, 42, 41],
    weeklySpark: [44, 42, 40, 39, 41, 40, 39, 41],
    risksLastWeek: 47,
    modes: [
      { k: "FCA", on: true,  s: "41" },
      { k: "SEC", on: false, s: "38" },
      { k: "Internal", on: false, s: "—" },
    ],
    recentRisks: [
      { sev: "high", color: "#E63946", excerpt: "this investment is", risk: "safe and should return 10%", to: "Quarterly client letter — Acme Pension", time: "14:32", mode: "SEC" },
      { sev: "high", color: "#E63946", excerpt: "no fees, no risk —", risk: "guaranteed access", to: "Promo: Premium tier rollout", time: "11:45", mode: "FCA" },
      { sev: "high", color: "#E63946", excerpt: "you'll definitely see", risk: "double-digit returns", to: "Follow-up: Mr. Castelli", time: "11:08", mode: "SEC" },
      { sev: "mid",  color: "#F4811F", excerpt: "we expect strong outperformance over the", risk: "next twelve months", to: "Re: Q1 strategy update", time: "10:50", mode: "FCA" },
      { sev: "high", color: "#E63946", excerpt: "this is a", risk: "risk-free opportunity", to: "Cold outreach — Hartford", time: "10:14", mode: "SEC" },
      { sev: "mid",  color: "#F4811F", excerpt: "the fund is", risk: "low-volatility and stable", to: "RFP — Northwind Capital", time: "Yesterday", mode: "SEC" },
      { sev: "high", color: "#E63946", excerpt: "you can expect", risk: "consistent monthly gains", to: "Pitch deck — pension trust", time: "Yesterday", mode: "FCA" },
      { sev: "low",  color: "#F4C430", excerpt: "performance has been", risk: "exceptional this cycle", to: "Internal: Desk wrap-up", time: "Yesterday", mode: "Internal" },
    ],
    patterns: [
      { name: "Unhedged performance claims", count: 24, weight: 1.00 },
      { name: "Implied guarantees",          count: 18, weight: 0.86 },
      { name: "Missing risk disclaimers",    count: 14, weight: 0.72 },
      { name: "Superlatives without basis",  count: 11, weight: 0.58 },
    ],
  } : {
    score: 92,
    delta: 4,
    deltaLabel: "this week",
    sparkData: [78, 79, 80, 79, 81, 82, 81, 83, 84, 83, 85, 86, 85, 87, 86, 88, 87, 89, 90, 89, 90, 91, 90, 92, 91, 92, 91, 92, 91, 92],
    weeklySpark: [72, 75, 78, 80, 82, 85, 88, 92],
    risksLastWeek: 23,
    modes: [
      { k: "FCA", on: true,  s: "92" },
      { k: "SEC", on: false, s: "87" },
      { k: "Internal", on: false, s: "94" },
    ],
    recentRisks: [
      { sev: "high", color: "#E63946", excerpt: "this investment is", risk: "safe and should return 10%", to: "Quarterly client letter — Acme Pension", time: "14:32", mode: "SEC" },
      { sev: "mid",  color: "#F4811F", excerpt: "we expect strong outperformance over the", risk: "next twelve months", to: "Re: Q1 strategy update", time: "13:08", mode: "FCA" },
      { sev: "high", color: "#E63946", excerpt: "no fees, no risk —", risk: "guaranteed access", to: "Promo: Premium tier rollout", time: "11:45", mode: "FCA" },
      { sev: "low",  color: "#F4C430", excerpt: "performance has been", risk: "exceptional this cycle", to: "Internal: Desk wrap-up", time: "10:22", mode: "Internal" },
      { sev: "mid",  color: "#F4811F", excerpt: "the fund is", risk: "low-volatility and stable", to: "RFP — Northwind Capital", time: "Yesterday", mode: "SEC" },
      { sev: "high", color: "#E63946", excerpt: "you'll definitely see", risk: "double-digit returns", to: "Follow-up: Mr. Castelli", time: "Yesterday", mode: "SEC" },
    ],
    patterns: [
      { name: "Unhedged performance claims", count: 12, weight: 0.95 },
      { name: "Implied guarantees", count: 8, weight: 0.7 },
      { name: "Missing risk disclaimers", count: 6, weight: 0.55 },
      { name: "Superlatives without basis", count: 4, weight: 0.35 },
    ],
  };

  const { score, delta, deltaLabel, sparkData, weeklySpark, risksLastWeek, modes, recentRisks, patterns } = data;

  return (
    <div style={{ width, height, background: "var(--white-pure)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
      <TopBar active="Compliance"/>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(0, 35fr) minmax(0, 35fr) minmax(0, 30fr)", gap: 24, padding: 32, minHeight: 0, overflow: "hidden" }}>
        {/* Left — score */}
        <div className="pillow hero float-in" style={{ padding: 36, display: "flex", flexDirection: "column" }}>
          <div className="micro">
            {connected ? `${connected.name.split(" ")[0]}'s baseline · FCA mode` : "FCA mode · active"}
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 8, marginTop: 12 }}>
            <div className="serif" style={{
              fontSize: 144, lineHeight: 0.9, letterSpacing: "-0.04em",
              color: scoreColor(score),
            }}>{score}</div>
            <div className="serif" style={{ fontSize: 36, color: "var(--midnight-soft)", lineHeight: 1.3, paddingBottom: 14 }}>/100</div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 10 }}>
            {delta !== null ? (
              <>
                <span className="mono" style={{
                  fontSize: 12,
                  color: delta > 0 ? "var(--success-mint)" : "var(--red-deep)",
                  fontWeight: 600,
                }}>{delta > 0 ? "↑" : "↓"} {Math.abs(delta)}</span>
                <span className="small" style={{ color: "var(--midnight-soft)" }}>{deltaLabel}</span>
              </>
            ) : (
              <span className="small" style={{ color: "var(--midnight-soft)" }}>{deltaLabel}</span>
            )}
          </div>
          <div style={{ marginTop: 24 }}>
            <div className="micro" style={{ marginBottom: 10 }}>30-day score history</div>
            <Sparkline data={sparkData} w={420} h={80}/>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
              <span className="mono" style={{ fontSize: 10, color: "var(--midnight-soft)" }}>APR 01</span>
              <span className="mono" style={{ fontSize: 10, color: "var(--midnight-soft)" }}>APR 30</span>
            </div>
          </div>

          <div style={{ flex: 1 }}/>

          {/* Mode switcher (neu) */}
          <div style={{ display: "flex", gap: 12, marginTop: 24 }}>
            {modes.map(m => (
              <div key={m.k} style={{
                flex: 1, padding: "14px 16px", borderRadius: 14,
                background: "var(--white-pure)",
                boxShadow: m.on ? "var(--neu-in)" : "var(--neu-out-sm)",
                textAlign: "center",
              }}>
                <div className="micro" style={{ color: m.on ? "var(--midnight)" : "var(--midnight-soft)" }}>{m.k}</div>
                <div className="small" style={{ color: "var(--midnight-soft)", marginTop: 4 }}>{m.s}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Center — recent risks */}
        <div className="pillow float-in" style={{ padding: 28, display: "flex", flexDirection: "column", minWidth: 0, minHeight: 0 }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
            <div className="h3">Recent risks detected</div>
            <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>LAST 7 DAYS · {risksLastWeek}</span>
          </div>
          <div className="scroll" style={{
            display: "flex", flexDirection: "column", gap: 10,
            overflow: "auto",
            padding: "8px 16px 16px 16px",
            margin: "8px -16px -16px -16px",
            minHeight: 0, flex: 1,
          }}>
            {recentRisks.map((r, i) => (
              <div key={i} className="pillow" style={{ padding: 16, display: "flex", gap: 14, alignItems: "flex-start", borderRadius: 14 }}>
                <span style={{
                  width: 8, height: 8, borderRadius: 999, marginTop: 8, flexShrink: 0,
                  background: r.color, boxShadow: `0 0 0 4px ${r.color}22`,
                }}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, lineHeight: 1.45, color: "var(--midnight)" }}>
                    <span style={{ color: "var(--midnight-soft)" }}>"…{r.excerpt} </span>
                    <span style={{ background: "var(--red-ghost)", padding: "1px 4px", borderRadius: 3, textDecoration: "underline wavy rgba(230,57,70,0.6)", textDecorationThickness: 2, textUnderlineOffset: 3 }}>{r.risk}</span>
                    <span style={{ color: "var(--midnight-soft)" }}>"</span>
                  </div>
                  <div style={{ display: "flex", gap: 12, marginTop: 6, alignItems: "center" }}>
                    <span className="small" style={{ color: "var(--midnight-soft)" }}>{r.to}</span>
                    <span style={{ width: 3, height: 3, borderRadius: 999, background: "var(--gray-whisper)" }}/>
                    <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>{r.time} · {r.mode}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Right — improvement & patterns */}
        <div style={{ display: "flex", flexDirection: "column", gap: 24, minWidth: 0 }}>
          <div className="pillow float-in" style={{ padding: 28 }}>
            <div className="h3">Improvement</div>
            <div className="micro" style={{ marginTop: 4, color: "var(--midnight-soft)" }}>Weekly score evolution</div>
            <div style={{ marginTop: 16 }}>
              <Sparkline data={weeklySpark} w={360} h={120}/>
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", marginTop: 8 }}>
              <span className="mono" style={{ fontSize: 10, color: "var(--midnight-soft)" }}>W-8</span>
              <span className="mono" style={{ fontSize: 10, color: "var(--midnight-soft)" }}>NOW</span>
            </div>
          </div>

          <div className="pillow float-in" style={{ padding: 28, flex: 1 }}>
            <div className="h3">Top issue patterns</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 16 }}>
              {patterns.map(p => (
                <div key={p.name}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 6 }}>
                    <span style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</span>
                    <span className="mono" style={{ fontSize: 11, color: "var(--midnight-soft)" }}>{p.count}</span>
                  </div>
                  <div style={{ height: 6, background: "var(--white-soft)", borderRadius: 999, overflow: "hidden" }}>
                    <div style={{
                      width: `${p.weight*100}%`, height: "100%",
                      background: "linear-gradient(90deg, #B91C2C, #E63946 60%, #F4811F)",
                      opacity: 0.85,
                    }}/>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.Dashboard = Dashboard;
window.TopBar = TopBar;
