/* global React, CoastGroup */
const { useState, useMemo } = React;

// ====================================================================
// Marquee Cross-Pollination viz — full screen, editorial
// ====================================================================
function CrossPollFullscreen({ embedded = false }) {
  const G = window.CoastGroup;
  const [range, setRange] = useState("90d");
  const [filter, setFilter] = useState("all");

  // Group members by industry buckets for filter
  const industryFor = (role) => {
    const r = role.toLowerCase();
    if (r.includes("solicitor") || r.includes("conveyanc")) return "legal";
    if (r.includes("accountant") || r.includes("broker") || r.includes("financial") || r.includes("bookkeeper")) return "finance";
    if (r.includes("agent")) return "property";
    if (r.includes("market") || r.includes("copy") || r.includes("brand")) return "creative";
    if (r.includes("it") || r.includes("web")) return "tech";
    return "other";
  };

  const W = 760, H = 580;
  const cx = W/2, cy = H/2 + 10;

  // Hand-tuned positions: arrange by industry around the ring
  const orderedIds = useMemo(() => {
    const buckets = { legal: [], finance: [], property: [], creative: [], tech: [], other: [] };
    G.members.forEach(m => buckets[industryFor(m.role)].push(m.id));
    return [...buckets.legal, ...buckets.finance, ...buckets.property, ...buckets.creative, ...buckets.tech, ...buckets.other];
  }, []);

  const N = G.members.length;
  const ringR = 220;
  const positions = {};
  orderedIds.forEach((id, i) => {
    const a = (i / N) * Math.PI * 2 - Math.PI/2;
    positions[id] = { x: cx + Math.cos(a) * ringR, y: cy + Math.sin(a) * ringR, a };
  });

  const memberById = (id) => G.members.find(m => m.id === id);

  const isVisible = (m) => filter === "all" || industryFor(m.role) === filter;
  const edgeVisible = (a, b) => isVisible(memberById(a)) && isVisible(memberById(b));

  return (
    <div style={{ width: "100%", height: "100%", background: "var(--bg)", color: "var(--text)", display: "flex", flexDirection: "column", padding: embedded ? 28 : 40, position: "relative", overflow: "hidden" }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", borderBottom: "1px solid var(--border-soft)", paddingBottom: 20 }}>
        <div>
          <div className="eyebrow">Group health · {G.name}</div>
          <h1 className="serif" style={{ fontSize: 44, margin: "10px 0 6px", letterSpacing: "-0.02em", lineHeight: 1 }}>
            Cross-pollination<span className="serif-i" style={{ color: "var(--accent)" }}>.</span>
          </h1>
          <p className="muted" style={{ fontSize: 14, maxWidth: 520, lineHeight: 1.55, margin: 0 }}>
            Connections members have made <em className="serif-i">for</em> one another over the selected period — attributed by the receiving party, not self-claimed.
          </p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          {[["30d","30d"],["90d","90d"],["12m","12m"],["all","All time"]].map(([v,l]) => (
            <button key={v} onClick={() => setRange(v)}
              style={{ padding: "8px 14px", borderRadius: 999, border: "1px solid " + (range===v?"var(--accent)":"var(--border)"), background: range===v?"var(--accent-soft)":"transparent", color: range===v?"var(--accent)":"var(--text-2)", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.06em", cursor: "pointer" }}>
              {l.toUpperCase()}
            </button>
          ))}
        </div>
      </div>

      {/* Body — viz left, side panel right */}
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "1fr 240px", gap: 24, paddingTop: 24, minHeight: 0 }}>
        <div style={{ position: "relative" }}>
          <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="xMidYMid meet" style={{ display: "block" }}>
            <defs>
              <radialGradient id="cp-glow" cx="50%" cy="50%" r="50%">
                <stop offset="0" stopColor="var(--accent)" stopOpacity="0.08"/>
                <stop offset="1" stopColor="var(--accent)" stopOpacity="0"/>
              </radialGradient>
            </defs>

            {/* Background glow + concentric rings */}
            <circle cx={cx} cy={cy} r={ringR + 30} fill="url(#cp-glow)"/>
            {[0.45, 0.7, 1].map((s, i) => (
              <circle key={i} cx={cx} cy={cy} r={ringR * s} fill="none" stroke="var(--border-soft)" strokeDasharray="1 5"/>
            ))}

            {/* Industry sector arcs as faint labels */}
            {[
              { label: "LEGAL",     range: [0, 2/N] },
              { label: "FINANCE",   range: [2/N, 6/N] },
              { label: "PROPERTY",  range: [6/N, 7/N] },
              { label: "CREATIVE",  range: [7/N, 11/N] },
              { label: "TECH",      range: [11/N, 13/N] },
              { label: "ADVISORY",  range: [13/N, 14/N] },
            ].map((s, i) => {
              const mid = (s.range[0] + s.range[1]) / 2;
              const ang = mid * Math.PI * 2 - Math.PI/2;
              const lr = ringR + 36;
              const x = cx + Math.cos(ang) * lr;
              const y = cy + Math.sin(ang) * lr;
              return (
                <text key={i} x={x} y={y} textAnchor="middle" dominantBaseline="middle"
                  style={{ font: "500 9px var(--mono)", fill: filter === "all" ? "var(--text-3)" : "var(--text-3)", letterSpacing: "0.14em" }}>
                  {s.label}
                </text>
              );
            })}

            {/* Dormant edges first (under) */}
            {G.dormantEdges.map(([a, b], i) => {
              const p1 = positions[a], p2 = positions[b];
              if (!p1 || !p2) return null;
              const visible = edgeVisible(a, b);
              return (
                <path key={`d${i}`}
                  d={`M ${p1.x} ${p1.y} Q ${cx} ${cy} ${p2.x} ${p2.y}`}
                  fill="none" stroke="var(--border)" strokeWidth="0.7" strokeDasharray="2 4"
                  opacity={visible ? 0.6 : 0.15}/>
              );
            })}

            {/* Active edges */}
            {G.edges.map(([a, b], i) => {
              const p1 = positions[a], p2 = positions[b];
              if (!p1 || !p2) return null;
              const visible = edgeVisible(a, b);
              const isSelf = a === 1 || b === 1;
              return (
                <path key={`e${i}`}
                  d={`M ${p1.x} ${p1.y} Q ${cx} ${cy} ${p2.x} ${p2.y}`}
                  fill="none"
                  stroke="var(--accent)"
                  strokeWidth={isSelf ? 1.4 : 0.9}
                  strokeOpacity={visible ? (isSelf ? 0.7 : 0.32) : 0.06}/>
              );
            })}

            {/* Nodes */}
            {G.members.map((m) => {
              const p = positions[m.id];
              if (!p) return null;
              const r = 6 + Math.sqrt(m.conn) * 2.2;
              const visible = isVisible(m);
              const dim = !visible ? 0.2 : 1;
              return (
                <g key={m.id} opacity={dim}>
                  <circle cx={p.x} cy={p.y} r={r + 4} fill="var(--bg)"/>
                  <circle cx={p.x} cy={p.y} r={r}
                    fill={m.self ? "var(--accent-soft)" : "var(--surface-2)"}
                    stroke={m.self ? "var(--accent)" : "var(--border)"}
                    strokeWidth="1"/>
                  <text x={p.x} y={p.y + 3} textAnchor="middle"
                    style={{ font: `500 ${m.self ? 10 : 9}px var(--mono)`, fill: m.self ? "var(--accent)" : "var(--text-2)", letterSpacing: "0.04em" }}>
                    {m.initials}
                  </text>
                  {/* role label outside */}
                  {(() => {
                    const lr = ringR + 14;
                    const lx = cx + Math.cos(p.a) * lr;
                    const ly = cy + Math.sin(p.a) * lr;
                    return (
                      <text x={lx} y={ly + 3} textAnchor={Math.cos(p.a) > 0.2 ? "start" : Math.cos(p.a) < -0.2 ? "end" : "middle"}
                        style={{ font: "400 9px var(--mono)", fill: "var(--text-3)", letterSpacing: "0.04em" }}>
                        {m.role.toUpperCase().split(" ")[0]}
                      </text>
                    );
                  })()}
                </g>
              );
            })}

            {/* Center label */}
            <text x={cx} y={cy - 4} textAnchor="middle" style={{ font: "italic 400 18px var(--serif)", fill: "var(--text)" }}>
              Coast Referral
            </text>
            <text x={cx} y={cy + 16} textAnchor="middle" style={{ font: "italic 400 18px var(--serif)", fill: "var(--text)" }}>
              Collective
            </text>
            <text x={cx} y={cy + 36} textAnchor="middle" style={{ font: "500 9px var(--mono)", fill: "var(--text-3)", letterSpacing: "0.14em" }}>
              EST. AUG 2024
            </text>
          </svg>
        </div>

        {/* Legend / filter panel */}
        <div style={{ display: "flex", flexDirection: "column", gap: 24, borderLeft: "1px solid var(--border-soft)", paddingLeft: 24 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Filter by industry</div>
            {[
              ["all","All members",""],
              ["legal","Legal",""],
              ["finance","Finance",""],
              ["property","Property",""],
              ["creative","Creative",""],
              ["tech","Technology",""],
            ].map(([v,l]) => (
              <button key={v} onClick={() => setFilter(v)}
                style={{ display: "block", width: "100%", textAlign: "left", padding: "8px 0", background: "transparent", border: "none", color: filter===v?"var(--accent)":"var(--text-2)", fontSize: 13, cursor: "pointer", fontFamily: "var(--sans)" }}>
                <span style={{ display: "inline-block", width: 6, height: 6, borderRadius: 3, background: filter===v?"var(--accent)":"var(--border)", marginRight: 10, verticalAlign: "middle" }}/>
                {l}
              </button>
            ))}
          </div>

          <div>
            <div className="eyebrow" style={{ marginBottom: 12 }}>Legend</div>
            <Legend swatch={<svg width="32" height="8"><line x1="0" y1="4" x2="32" y2="4" stroke="var(--accent)" strokeWidth="1.4"/></svg>} l="Recent intro made"/>
            <Legend swatch={<svg width="32" height="8"><line x1="0" y1="4" x2="32" y2="4" stroke="var(--border)" strokeWidth="0.7" strokeDasharray="2 4"/></svg>} l="Dormant > 90d"/>
            <Legend swatch={<svg width="14" height="14"><circle cx="7" cy="7" r="6" fill="var(--accent-soft)" stroke="var(--accent)"/></svg>} l="You"/>
            <Legend swatch={<svg width="14" height="14"><circle cx="7" cy="7" r="6" fill="var(--surface-2)" stroke="var(--border)"/></svg>} l="Member · size = degree"/>
          </div>

          <div style={{ marginTop: "auto", paddingTop: 20, borderTop: "1px solid var(--border-soft)" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Score</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}>
              <span className="mono" style={{ fontSize: 38, fontWeight: 500, color: "var(--accent)", letterSpacing: "-0.02em" }}>0.84</span>
              <span className="mono" style={{ fontSize: 11, color: "var(--text-3)", letterSpacing: "0.08em" }}>vs 0.51 avg</span>
            </div>
            <p className="muted" style={{ fontSize: 12, marginTop: 8, lineHeight: 1.5 }}>
              Top decile across all 1to1 groups in SE QLD.
            </p>
          </div>
        </div>
      </div>

      {/* Footnote */}
      <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 20, borderTop: "1px solid var(--border-soft)", marginTop: 16 }}>
        <span className="mono" style={{ fontSize: 10, letterSpacing: "0.12em", color: "var(--text-3)" }}>FIG. 01 — INTRA-GROUP REFERRAL ACTIVITY · {range.toUpperCase()}</span>
        <span className="mono" style={{ fontSize: 10, letterSpacing: "0.12em", color: "var(--text-3)" }}>1TO1 · GROUP HEALTH ANALYTICS</span>
      </div>
    </div>
  );
}
const Legend = ({ swatch, l }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "6px 0" }}>
    {swatch}<span style={{ fontSize: 12, color: "var(--text-2)" }}>{l}</span>
  </div>
);

window.CrossPollFullscreen = CrossPollFullscreen;
