/* =====================================================================
   pathway.jsx — the Freedom Filled pathway visual, 3 variations
   A) circular wheel   B) simplified strip   C) layered map
   Highlights primary + secondary business pins and the F.R.E.S.H baseline.
   ===================================================================== */

/* themed colors (set by app2 on window.__ffp2Theme) */
function pAccent() { return (window.__ffp2Theme && window.__ffp2Theme.accent) || "#6e8e77"; }
function pDark()   { return (window.__ffp2Theme && window.__ffp2Theme.dark)   || "#1e3735"; }
function hex2rgb(h){ h=h.replace('#',''); if(h.length===3)h=h.split('').map(c=>c+c).join(''); return [parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)]; }
function mix(a,b,t){ const A=hex2rgb(a),B=hex2rgb(b); const c=A.map((v,i)=>Math.round(v+(B[i]-v)*t)); return 'rgb('+c.join(',')+')'; }
const OAT = "#f6f4f1";

/* FFB monogram (inline so it themes via currentColor) */
function FFBMark({ size = 46, color }) {
  return (
    <svg viewBox="0 0 237.9 270.78" width={size} height={size * 270.78 / 237.9} style={{ display: "block", fill: color || "currentColor" }}>
      <path d="M206.76,170.83c.44-3.05.65-5.88.65-8.93,0-33.53-21.99-71.64-58.58-71.64h-30.05c12.63,6.53,11.32,17.42,11.32,29.4l.06,11.12c-23.43-7.1-40.35-29.26-40.35-54.67v-23.3h45.51c19.82,0,33.75,1.52,42.03,21.77l-1.31-25.69H59.78c12.41,6.53,11.32,16.98,11.32,29.4v3.81c-23.79-6.86-41.05-29.21-41.05-54.87V3.92h45.51c19.82,0,33.75,1.52,42.03,21.77l-1.31-25.69H0c12.41,6.53,11.32,16.98,11.32,29.4v121.94c0,11.1.44,23.52-10.89,29.18h40.72c-12.41-6.1-11.1-16.55-11.1-29.18V48.56c6.81,18.55,22.4,31.52,41.05,36.92v114.75c0,11.11.44,23.52-10.89,29.18h40.72c-12.41-6.1-11.1-16.55-11.1-29.18v-102.78c6.72,18.32,22.02,31.19,40.36,36.71l.58,107.88c0,10.23-1.09,23.74-11.11,28.74h29.18c33.1,0,89.06-18.29,89.06-58.79,0-19.82-10.89-37.24-31.14-41.15h0ZM148.84,94.18c35.71,1.96,39.85,39.85,39.85,67.72s-4.14,65.76-39.85,67.5V94.18ZM148.84,267.29v-33.97c31.14-1.52,52.48-28.96,57.49-57.7,11.32,8.93,13.28,22.43,13.28,36.36,0,36.8-38.32,55.09-70.77,55.31Z" />
    </svg>
  );
}

/* which areas are pinned, and how */
function pinMap(result) {
  const m = {};
  const pm = result.pathwayMap;
  m[pm.primaryPin.area] = "primary";
  pm.secondaryPins.forEach(p => { m[p.area] = "secondary"; });
  return m;
}

/* ============ Variation A: circular wheel ============ */
function CircularPathway({ result, size = 460 }) {
  const pins = pinMap(result);
  const accent = pAccent(), dark = pDark();
  const reduceMotion = typeof window !== "undefined" && window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const half = size / 2;
  // viewBox padding so outer labels never clip
  const PAD = Math.round(size * 0.2);
  const VB = size + PAD * 2;
  const cx = half + PAD, cy = half + PAD;
  // proportional radii (scale with size)
  const centerR = half * 0.355;
  const innerIn = half * 0.40;
  const innerOut = half * 0.625;
  const bandIn = half * 0.66;
  const bandOut = half * 0.90;
  const dotR = (bandIn + bandOut) / 2;
  const labelR = bandOut + half * 0.085;
  // font scale
  const fStage = Math.max(10, size * 0.038);
  const fArea = Math.max(7.5, size * 0.023);
  const fMono = Math.round(half * 0.26);
  const fFresh = Math.max(6, size * 0.018);

  const STAGES = window.FFP2.STAGES;
  // area angles: 9 evenly spaced, 40deg apart, starting offer at -130
  const areaAngles = { Offer:-130, Message:-90, Model:-50, Attract:-10, Convert:30, Optimise:70, "Client Experience":110, Facilitate:150, Leadership:190 };
  const areaShort = { "Client Experience": "Client Exp." };
  const stageCenter = { BUILD:-90, SELL:30, LEAD:150 };
  const rad = (d) => (d * Math.PI) / 180;
  const P = (ang, r) => [cx + Math.cos(rad(ang)) * r, cy + Math.sin(rad(ang)) * r];
  function annular(a0, a1, r0, r1) {
    const [x0, y0] = P(a0, r1), [x1, y1] = P(a1, r1), [x2, y2] = P(a1, r0), [x3, y3] = P(a0, r0);
    const large = (a1 - a0) > 180 ? 1 : 0;
    return `M${x0},${y0} A${r1},${r1} 0 ${large} 1 ${x1},${y1} L${x2},${y2} A${r0},${r0} 0 ${large} 0 ${x3},${y3} Z`;
  }
  const sectors = [
    { key: "build", a0: -148, a1: -32, name: "BUILD", innerFill: mix(accent, OAT, 0.18), bandFill: mix(accent, OAT, 0.86), word: dark },
    { key: "sell",  a0: -28,  a1: 88,  name: "SELL",  innerFill: mix(accent, OAT, 0.62), bandFill: mix(accent, OAT, 0.90), word: dark },
    { key: "lead",  a0: 92,   a1: 208, name: "LEAD",  innerFill: dark,                  bandFill: mix(dark, OAT, 0.90),  word: OAT },
  ];

  return (
    <svg viewBox={`0 0 ${VB} ${VB}`} width="100%" style={{ maxWidth: VB }} role="img" aria-label="Freedom Filled pathway wheel">
      {/* outer pale sector bands */}
      {sectors.map(s => <path key={s.key + "b"} d={annular(s.a0, s.a1, bandIn, bandOut)} fill={s.bandFill} />)}
      {/* inner stage ring */}
      {sectors.map(s => <path key={s.key + "i"} d={annular(s.a0, s.a1, innerIn, innerOut)} fill={s.innerFill} />)}
      {/* stage words (tangential) */}
      {sectors.map(s => {
        const ang = stageCenter[s.name];
        const [lx, ly] = P(ang, (innerIn + innerOut) / 2);
        let rot = ang + 90; if (Math.sin(rad(ang)) > 0.02) rot += 180;
        return <text key={s.key + "w"} x={lx} y={ly} transform={`rotate(${rot} ${lx} ${ly})`} textAnchor="middle" dominantBaseline="central"
          fontFamily="Poppins, sans-serif" fontSize={fStage} fontWeight="600" letterSpacing="0.22em" fill={s.word}>{s.name}</text>;
      })}
      {/* thin dotted ring */}
      <circle cx={cx} cy={cy} r={dotR} fill="none" stroke={mix(dark, OAT, 0.7)} strokeWidth="1" />
      {/* area dots + labels */}
      {STAGES.flatMap(st => st.areas).map(a => {
        const ang = areaAngles[a.area];
        const [dx, dy] = P(ang, dotR);
        const pin = pins[a.area];
        const r = pin === "primary" ? half * 0.024 : pin === "secondary" ? half * 0.017 : half * 0.012;
        const fill = pin === "primary" ? dark : pin === "secondary" ? accent : mix(accent, OAT, 0.5);
        const [lx, ly] = P(ang, labelR);
        let rot = ang + 90; if (Math.sin(rad(ang)) > 0.02) rot += 180;
        return (
          <g key={a.key}>
            {pin === "primary" && <circle cx={dx} cy={dy} r={half * 0.04} fill="none" stroke={dark} strokeWidth="1.5" opacity="0.45" />}
            {pin === "primary" && !reduceMotion && (
              <circle cx={dx} cy={dy} fill="none" stroke={dark} strokeWidth="2">
                <animate attributeName="r" values={`${half * 0.028};${half * 0.11}`} dur="1.9s" repeatCount="indefinite" calcMode="spline" keySplines="0.22 1 0.36 1" keyTimes="0;1" />
                <animate attributeName="opacity" values="0.55;0" dur="1.9s" repeatCount="indefinite" keyTimes="0;1" />
              </circle>
            )}
            <circle cx={dx} cy={dy} r={r} fill={fill} stroke={OAT} strokeWidth="1.5">
              {pin === "primary" && !reduceMotion && (
                <animate attributeName="r" values={`${r};${r * 1.32};${r}`} dur="1.9s" repeatCount="indefinite" calcMode="spline" keySplines="0.4 0 0.2 1;0.4 0 0.2 1" keyTimes="0;0.5;1" />
              )}
            </circle>
            <text x={lx} y={ly} transform={`rotate(${rot} ${lx} ${ly})`} textAnchor="middle" dominantBaseline="central"
              fontFamily="Poppins, sans-serif" fontSize={fArea} fontWeight={pin ? 600 : 500} letterSpacing="0.12em"
              fill={pin === "primary" ? dark : mix(dark, OAT, 0.25)} style={{ textTransform: "uppercase" }}>{areaShort[a.area] || a.area}</text>
          </g>
        );
      })}
      {/* center disc + monogram + FRESH baseline */}
      <circle cx={cx} cy={cy} r={centerR} fill={OAT} />
      <g transform={`translate(${cx - fMono / 2} ${cy - centerR * 0.62})`}><FFBMark size={fMono} color={dark} /></g>
      <g>
        {window.FFP2.FRESH.map((f, i) => (
          <circle key={f.key} cx={cx - (centerR * 0.5) + i * (centerR * 0.25)} cy={cy + centerR * 0.42} r={half * 0.0095} fill={f.color} />
        ))}
        <text x={cx} y={cy + centerR * 0.66} textAnchor="middle" fontFamily="Poppins, sans-serif" fontSize={fFresh} letterSpacing="0.22em" fill={mix(dark, OAT, 0.4)}>F.R.E.S.H</text>
      </g>
    </svg>
  );
}

/* ============ Variation B: simplified strip ============ */
function PathwayStrip({ result }) {
  const pins = pinMap(result);
  const STAGES = window.FFP2.STAGES;
  return (
    <div className="pw-strip">
      <div className="pw-strip__stages">
        {STAGES.map((st, si) => (
          <React.Fragment key={st.key}>
            <div className="pw-stage">
              <div className="pw-stage__name">{st.name}</div>
              <div className="pw-stage__areas">
                {st.areas.map(a => {
                  const pin = pins[a.area];
                  return (
                    <div key={a.key} className={"pw-chip" + (pin ? " pw-chip--" + pin : "")}>
                      <span className="pw-chip__dot"></span>{a.area}
                      {pin === "primary" && <span className="pw-chip__tag">Start here</span>}
                    </div>
                  );
                })}
              </div>
            </div>
            {si < STAGES.length - 1 && <div className="pw-strip__arrow"><Icon name="arrow" size={18} /></div>}
          </React.Fragment>
        ))}
      </div>
      <div className="pw-foundation">
        <span className="pw-foundation__label">F.R.E.S.H foundation</span>
        <div className="pw-foundation__dots">
          {window.FFP2.FRESH.map(f => {
            const on = result.implementationSupportSignal.freshAreas.includes(f.name);
            return <span key={f.key} className="pw-foundation__pill" style={{ background: on ? f.color : "transparent", borderColor: f.color, color: on ? "#fff" : f.color }}>{f.letter}</span>;
          })}
        </div>
        <span className="pw-foundation__cap">The human operating layer beneath the business pathway</span>
      </div>
    </div>
  );
}

/* ============ Variation C: layered map (recommended) ============ */
function LayeredMap({ result }) {
  const pins = pinMap(result);
  const STAGES = window.FFP2.STAGES;
  const signal = result.implementationSupportSignal;
  return (
    <div className="pw-layer">
      <div className="pw-layer__business">
        {STAGES.map(st => (
          <div className="pw-col" key={st.key}>
            <div className="pw-col__head"><span className="pw-col__name">{st.name}</span></div>
            <div className="pw-col__areas">
              {st.areas.map(a => {
                const pin = pins[a.area];
                return (
                  <div key={a.key} className={"pw-area" + (pin ? " pw-area--" + pin : "")}>
                    <span className="pw-area__dot"></span>
                    <span className="pw-area__name">{a.area}</span>
                    {pin === "primary" && <span className="pw-area__flag">Primary focus</span>}
                    {pin === "secondary" && <span className="pw-area__flag pw-area__flag--q">Supporting</span>}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      <div className="pw-layer__foundation">
        <div className="pw-layer__found-label">
          <span className="pw-found-eyebrow">Foundation</span>
          <span className="pw-found-title">F.R.E.S.H</span>
        </div>
        <div className="pw-layer__found-track">
          {window.FFP2.FRESH.map(f => {
            const on = signal.freshAreas.includes(f.name);
            return (
              <div key={f.key} className={"pw-found-cell" + (on ? " on" : "")}>
                <span className="pw-found-dot" style={{ background: f.color, opacity: on ? 1 : 0.32 }}></span>
                <span className="pw-found-name">{f.name.split(",")[0]}</span>
              </div>
            );
          })}
        </div>
        <span className="pw-layer__found-cap">{signal.publicTitle}</span>
      </div>
    </div>
  );
}

const PATHWAY_VARIANTS = [
  { key: "layered",  label: "Layered map", render: (r) => <LayeredMap result={r} /> },
  { key: "circular", label: "Circular", render: (r) => <div style={{ display: "grid", placeItems: "center" }}><CircularPathway result={r} /></div> },
  { key: "strip",    label: "Strip", render: (r) => <PathwayStrip result={r} /> },
];

Object.assign(window, { FFBMark, CircularPathway, PathwayStrip, LayeredMap, PATHWAY_VARIANTS, pinMap });
