/* global React, M, CoastGroup */

const G = window.CoastGroup;

// ====================================================================
// A4 — Cross-pollination mobile full-bleed
// ====================================================================
function CrossPollMobile() {
  const { MScreen, MTopBar, Eyebrow, Glyph, Perf } = window.M;
  const [range, setRange] = React.useState("90D");
  const [ind, setInd] = React.useState("All");

  // Compute node positions (radial)
  const cx = 170, cy = 175, r = 130;
  const positions = G.members.map((m, i) => {
    const a = (i / G.members.length) * Math.PI * 2 - Math.PI / 2;
    return { ...m, x: cx + Math.cos(a) * r, y: cy + Math.sin(a) * r, angle: a };
  });

  // industry buckets for perimeter labels
  const labels = [
    { txt: "LEGAL", angle: -Math.PI/2 - 0.05 },
    { txt: "FINANCE", angle: -Math.PI/4 + 0.1 },
    { txt: "PROPERTY", angle: 0.5 },
    { txt: "CREATIVE", angle: Math.PI/2 + 0.4 },
    { txt: "TECH", angle: Math.PI - 0.4 },
    { txt: "ADVISORY", angle: -Math.PI + 0.4 },
  ];

  return (
    <MScreen>
      <MTopBar
        right={
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <button style={{ width: 36, height: 36, borderRadius: 18, background: "transparent", border: "none", color: "var(--text-2)", cursor: "pointer" }}><Glyph.Share/></button>
            <span className="mono" style={{ padding: "6px 11px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent)", fontSize: 10, letterSpacing: "0.1em" }}>{range}</span>
          </div>
        }
      />

      {/* Header */}
      <div style={{ padding: "0 24px 24px" }}>
        <Eyebrow>Group health · Coast Referral Collective</Eyebrow>
        <h1 className="serif" style={{ fontSize: 38, lineHeight: 1.05, letterSpacing: "-0.02em", margin: "12px 0 0" }}>
          Cross-pollination.
        </h1>
        <p style={{ fontSize: 14, lineHeight: 1.6, color: "var(--text-2)", marginTop: 16, textWrap: "pretty" }}>
          Connections members have made for one another over the selected period — attributed by the receiving party, not self-claimed.
        </p>
      </div>

      {/* Time range pills */}
      <div style={{ display: "flex", gap: 6, padding: "0 24px 20px" }}>
        {["30D","90D","1Y","ALL TIME"].map((p, i) => {
          const on = range === p;
          return (
            <button key={i} onClick={() => setRange(p)} style={{
              flex: 1, padding: "9px 10px", borderRadius: 999, fontSize: 11.5,
              border: "1px solid " + (on ? "transparent" : "var(--border)"),
              background: on ? "var(--accent)" : "var(--surface-2)",
              color: on ? "#0E0D0B" : "var(--text-2)",
              fontWeight: on ? 600 : 400, fontFamily: "var(--mono)", letterSpacing: "0.1em", cursor: "pointer",
            }}>{p}</button>
          );
        })}
      </div>

      {/* Viz */}
      <div style={{ padding: "0 12px 12px" }}>
        <svg viewBox="0 0 340 340" style={{ width: "100%", height: 360 }}>
          <defs>
            <radialGradient id="cpg" cx="50%" cy="50%" r="50%">
              <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.08"/>
              <stop offset="100%" stopColor="var(--accent)" stopOpacity="0"/>
            </radialGradient>
          </defs>

          {/* Soft halo */}
          <circle cx={cx} cy={cy} r={r + 12} fill="url(#cpg)"/>

          {/* Ring */}
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--border-soft)" strokeWidth="0.7" strokeDasharray="2 4"/>

          {/* Industry labels around perimeter */}
          {labels.map((l, i) => {
            const lr = r + 22;
            const x = cx + Math.cos(l.angle) * lr;
            const y = cy + Math.sin(l.angle) * lr;
            return <text key={i} x={x} y={y} fontFamily="var(--mono)" fontSize="8" letterSpacing="1.4" fill="var(--text-3)" textAnchor="middle" dominantBaseline="middle">{l.txt}</text>;
          })}

          {/* Edges */}
          {G.edges.map(([a, b], i) => {
            const A = positions[a-1], B = positions[b-1];
            return <line key={"e"+i} x1={A.x} y1={A.y} x2={B.x} y2={B.y} stroke="var(--accent)" strokeWidth="0.6" opacity="0.5"/>;
          })}
          {G.dormantEdges.map(([a, b], i) => {
            const A = positions[a-1], B = positions[b-1];
            return <line key={"d"+i} x1={A.x} y1={A.y} x2={B.x} y2={B.y} stroke="var(--text-3)" strokeWidth="0.5" strokeDasharray="2 3" opacity="0.5"/>;
          })}

          {/* Center label */}
          <text x={cx} y={cy - 4} fontFamily="var(--serif)" fontStyle="italic" fontSize="13" fill="var(--text)" textAnchor="middle">Coast</text>
          <text x={cx} y={cy + 12} fontFamily="var(--serif)" fontStyle="italic" fontSize="13" fill="var(--accent)" textAnchor="middle">Referral</text>

          {/* Nodes */}
          {positions.map(m => (
            <g key={m.id}>
              <circle cx={m.x} cy={m.y} r={m.self ? 7 : 4 + Math.min(m.conn / 3, 4)} fill={m.self ? "var(--accent)" : "var(--text)"} stroke="var(--bg)" strokeWidth="1.4"/>
              <text x={m.x} y={m.y - 12} fontFamily="var(--mono)" fontSize="7.5" letterSpacing="0.6" fill={m.self ? "var(--accent)" : "var(--text-2)"} textAnchor="middle">{m.initials}</text>
            </g>
          ))}
        </svg>
      </div>

      {/* Filter row */}
      <div style={{ padding: "8px 24px 16px" }}>
        <Eyebrow>Filter by industry</Eyebrow>
        <div style={{ display: "flex", gap: 6, overflowX: "auto", padding: "10px 0 4px", scrollbarWidth: "none" }}>
          {["All", "Legal", "Finance", "Property", "Creative", "Technology"].map((c, i) => {
            const on = ind === c;
            return (
              <button key={i} onClick={() => setInd(c)} style={{
                flex: "0 0 auto", padding: "7px 13px", borderRadius: 999, fontSize: 11.5,
                border: "1px solid " + (on ? "transparent" : "var(--border)"),
                background: on ? "var(--accent)" : "var(--surface-2)",
                color: on ? "#0E0D0B" : "var(--text-2)", fontWeight: on ? 600 : 400, cursor: "pointer", whiteSpace: "nowrap",
              }}>{c === "All" ? "All members" : c}</button>
            );
          })}
        </div>
      </div>

      {/* Legend */}
      <div style={{ padding: "8px 24px 0" }}>
        <Eyebrow>Legend</Eyebrow>
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 12 }}>
          <LegendRow icon={<svg width="36" height="6"><line x1="0" y1="3" x2="36" y2="3" stroke="var(--accent)" strokeWidth="1.5"/></svg>} label="Recent intro made"/>
          <LegendRow icon={<svg width="36" height="6"><line x1="0" y1="3" x2="36" y2="3" stroke="var(--text-3)" strokeWidth="1.5" strokeDasharray="3 3"/></svg>} label="Dormant > 90d"/>
          <LegendRow icon={<svg width="36" height="6"><circle cx="18" cy="3" r="3" fill="var(--text)"/></svg>} label="Member · size = degree"/>
        </div>
      </div>

      <Perf margin="28px 24px"/>

      {/* Score strip */}
      <div style={{ padding: "0 24px 32px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", padding: "20px 0", borderTop: "1px solid var(--border-soft)", borderBottom: "1px solid var(--border-soft)" }}>
          {[
            ["0.84", "Cross-poll score", "var(--accent)"],
            ["+0.06", "Vs last period", "var(--text)"],
            ["Top 12%", "Among comparable", "var(--text)"],
          ].map(([n, l, c], i) => (
            <div key={i} style={{ borderLeft: i > 0 ? "1px solid var(--border-soft)" : "none", padding: "0 12px", textAlign: i === 0 ? "left" : "center" }}>
              <div className="mono" style={{ fontSize: 22, fontWeight: 500, color: c, letterSpacing: "-0.02em" }}>{n}</div>
              <div className="mono" style={{ fontSize: 9.5, letterSpacing: "0.12em", color: "var(--text-3)", textTransform: "uppercase", marginTop: 6 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>
    </MScreen>
  );
}

function LegendRow({ icon, label }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
      <span style={{ flex: "0 0 36px", display: "inline-flex", alignItems: "center" }}>{icon}</span>
      <span className="muted" style={{ fontSize: 12 }}>{label}</span>
    </div>
  );
}

// ====================================================================
// A5 — Group health summary mobile · pentagon radar
// ====================================================================
function GroupHealthMobile() {
  const { MScreen, MTopBar, Eyebrow } = window.M;
  // Pentagon radar with 5 axes
  const cx = 175, cy = 195, R = 130;
  const axes = [
    { label: "TOTAL 1TO1S", value: 0.86 },
    { label: "GROUP REACH", value: 0.78 },
    { label: "INDUSTRY BREADTH", value: 0.79 },
    { label: "EXT : INT RATIO", value: 0.71 },
    { label: "CROSS-POLL", value: 0.84 },
  ];

  const points = (mult) => axes.map((a, i) => {
    const angle = (i / axes.length) * Math.PI * 2 - Math.PI / 2;
    const r = R * (mult ?? a.value);
    return [cx + Math.cos(angle) * r, cy + Math.sin(angle) * r];
  });

  const polyPts = (pts) => pts.map(p => p.join(",")).join(" ");

  return (
    <MScreen>
      <MTopBar/>
      <div style={{ padding: "0 24px 24px" }}>
        <Eyebrow>Group health · summary</Eyebrow>
        <h1 className="serif" style={{ fontSize: 32, lineHeight: 1.05, letterSpacing: "-0.02em", margin: "12px 0 0" }}>
          Coast Referral<br/><span className="serif-i" style={{ color: "var(--accent)" }}>Collective.</span>
        </h1>
        <div className="muted" style={{ fontSize: 13, marginTop: 10 }}>14 members · Gold Coast · 90-day window</div>
      </div>

      {/* Radar */}
      <div style={{ padding: "0 12px" }}>
        <svg viewBox="0 0 350 380" style={{ width: "100%" }}>
          {/* Concentric pentagons */}
          {[0.25, 0.5, 0.75, 1].map((m, i) => (
            <polygon key={i} points={polyPts(points(m))} fill="none" stroke="var(--border-soft)" strokeWidth="0.6"/>
          ))}
          {/* Axis spokes */}
          {axes.map((_, i) => {
            const angle = (i / axes.length) * Math.PI * 2 - Math.PI / 2;
            return <line key={i} x1={cx} y1={cy} x2={cx + Math.cos(angle) * R} y2={cy + Math.sin(angle) * R} stroke="var(--border-soft)" strokeWidth="0.5"/>;
          })}
          {/* Filled shape */}
          <polygon points={polyPts(points())} fill="var(--accent)" fillOpacity="0.18" stroke="var(--accent)" strokeWidth="1.4"/>
          {/* Vertices */}
          {points().map((p, i) => (
            <circle key={i} cx={p[0]} cy={p[1]} r="3" fill="var(--accent)"/>
          ))}
          {/* Labels */}
          {axes.map((a, i) => {
            const angle = (i / axes.length) * Math.PI * 2 - Math.PI / 2;
            const lr = R + 28;
            const x = cx + Math.cos(angle) * lr;
            const y = cy + Math.sin(angle) * lr;
            return <text key={i} x={x} y={y} fontFamily="var(--mono)" fontSize="8.5" letterSpacing="1" fill="var(--text-3)" textAnchor="middle" dominantBaseline="middle">{a.label}</text>;
          })}
        </svg>
      </div>

      {/* Metric breakdown */}
      <div style={{ padding: "8px 24px 0" }}>
        {[
          ["Total 1to1s", "312"],
          ["Group reach", "184"],
          ["Industry breadth", "11/14"],
          ["Ext : Int ratio", "0.71"],
          ["Cross-poll", "0.84"],
        ].map(([l, v], i, arr) => (
          <div key={i} style={{ padding: "14px 0", borderBottom: i < arr.length - 1 ? "1px dotted var(--border)" : "none", display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span style={{ fontSize: 13.5 }}>{l}</span>
            <span className="mono" style={{ fontSize: 16, fontWeight: 500 }}>{v}</span>
          </div>
        ))}
      </div>

      {/* Footer */}
      <div style={{ padding: "26px 24px 32px" }}>
        <div className="muted" style={{ fontSize: 11.5, lineHeight: 1.6 }}>
          Updated nightly. Comparisons drawn from groups of similar size and age.
        </div>
      </div>
    </MScreen>
  );
}

window.CrossPollMobile = CrossPollMobile;
window.GroupHealthMobile = GroupHealthMobile;
