// Interactive goal map — 15 nodes arranged in 6 thematic clusters.
// Center node: "Tekoälyturvallisuus". Click a node to scroll to that suositus in chapter view.

const themeAccentRGB = {
  huoltovarmuus: '#69a3a3',
  turvallisuus:  '#d4a25a',
  talous:        '#d47a5a',
  kv:            '#7a8ad4',
  hallinto:      '#8aa570',
  mielenterveys: '#d47a8a',
};

// Pre-computed cluster centers (percent of stage). Two-line titles where useful.
// labelDx/labelDy: offset from cluster center, AWAY from the map center,
// so labels sit on the outer side of each cluster (not toward the middle).
const clusterCenters = {
  huoltovarmuus: { x: 16, y: 32, label: ['Huolto-', 'varmuus'],            labelDx: 0,  labelDy: -14 },
  turvallisuus:  { x: 50, y: 14, label: ['Turvallisuus &', 'hybridi­vaikuttaminen'], labelDx: 0,  labelDy: -15 },
  talous:        { x: 84, y: 32, label: ['Talous &', 'työllisyys'],         labelDx: 0,  labelDy: -14 },
  kv:            { x: 84, y: 68, label: ['Kansainvälinen', 'yhteistyö'],    labelDx: 0,  labelDy:  16 },
  hallinto:      { x: 50, y: 86, label: ['Tekoäly', 'hallinnossa'],         labelDx: 0,  labelDy:  18 },
  mielenterveys: { x: 16, y: 68, label: ['Mielenterveys &', 'hyvinvointi'], labelDx: 0,  labelDy:  16 },
};

function nodePositions(goals) {
  const byTheme = {};
  goals.forEach(g => { (byTheme[g.theme] = byTheme[g.theme] || []).push(g); });
  const out = [];
  Object.entries(byTheme).forEach(([theme, gs]) => {
    const c = clusterCenters[theme];
    const n = gs.length;
    gs.forEach((g, i) => {
      let x = c.x, y = c.y;
      if (n === 1) { /* center */ }
      else if (n === 2) {
        const dx = (i === 0 ? -7 : 7);
        const dy = (i === 0 ? 4 : -4);
        x += dx; y += dy;
      } else if (n === 3) {
        const angles = [-150, -10, 110];
        x += Math.cos(angles[i] * Math.PI/180) * 9;
        y += Math.sin(angles[i] * Math.PI/180) * 8;
      }
      out.push({ ...g, x, y });
    });
  });
  return out;
}

const GoalMap = ({ activeGoalId, onActiveGoal }) => {
  const data = window.TUTKE_DATA;
  const positioned = React.useMemo(() => nodePositions(data.goals), [data.goals]);
  const active = activeGoalId
    ? positioned.find(g => g.id === activeGoalId)
    : null;

  const edges = React.useMemo(() => {
    const e = [];
    const byTheme = {};
    positioned.forEach(g => { (byTheme[g.theme] = byTheme[g.theme] || []).push(g); });
    Object.values(byTheme).forEach(gs => {
      for (let i = 0; i < gs.length; i++)
        for (let j = i+1; j < gs.length; j++)
          e.push({ a: gs[i], b: gs[j], theme: gs[i].theme });
    });
    // Soft connections: every node → center, so links visibly attach to nodes.
    const center = { x: 50, y: 50 };
    positioned.forEach(g => {
      e.push({ a: g, b: center, theme: g.theme, soft: true });
    });
    return e;
  }, [positioned]);

  const handleShare = (id) => {
    const url = window.location.origin + window.location.pathname + '#suositus-' + id;
    if (navigator.clipboard) {
      navigator.clipboard.writeText(url).then(() => {
        alert('Linkki kopioitu: ' + url);
      });
    }
  };

  const jumpToSuositus = (id) => {
    onActiveGoal(id);
    setTimeout(() => {
      const el = document.getElementById('suositus-' + id);
      if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 50);
  };

  const backToMap = () => {
    const el = document.querySelector('.map');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <section className="map" data-screen-label="04 Tavoitekartta">
      <div className="map-head">
        <div className="eyebrow">§ 03 · Tavoitekartta</div>
        <h2>15 suositusta. Kuusi osa-aluetta.</h2>
        <p>Vie hiiri solmun päälle nähdäksesi otsikon. Klikkaa siirtyäksesi suoraan suositukseen.</p>
      </div>

      <div className="map-mobile-list">
        {data.themes.map(t => {
          const themeGoals = data.goals.filter(g => g.theme === t.id);
          return (
            <div key={t.id} className="map-mobile-theme" style={{ '--accent': themeAccentRGB[t.id] }}>
              <div className="map-mobile-theme-head">
                <span className="map-mobile-theme-num">§ {t.n}</span>
                <h3>{t.title}</h3>
              </div>
              <ol className="map-mobile-goals">
                {themeGoals.map(g => (
                  <li key={g.id}>
                    <button onClick={() => jumpToSuositus(g.id)}>
                      <span className="num">№ {g.id}</span>
                      <span className="title">{g.title}</span>
                    </button>
                  </li>
                ))}
              </ol>
            </div>
          );
        })}
      </div>

      <div className="map-stage">
        <svg className="map-svg" viewBox="0 0 100 100" preserveAspectRatio="none">
          {edges.map((e, i) => (
            <line key={i}
              x1={e.a.x} y1={e.a.y} x2={e.b.x} y2={e.b.y}
              stroke={themeAccentRGB[e.theme]}
              strokeWidth={e.soft ? "0.14" : "0.13"}
              strokeOpacity={e.soft ? 0.4 : 0.42}
              vectorEffect="non-scaling-stroke" />
          ))}
        </svg>

        {/* CENTER NODE — Suomi 2027 */}
        <div className="map-core">
          <div className="map-core-disc">
          <div className="map-core-label">Tekoäly-<br/>turvallisuus</div>
          </div>
        </div>

        {Object.entries(clusterCenters).map(([theme, c]) => (
          <div key={theme}
            className="map-cluster-label"
            style={{ left: (c.x + c.labelDx) + '%', top: (c.y + c.labelDy) + '%', color: themeAccentRGB[theme] }}>
            {c.label.map((l, i) => <div key={i}>{l}</div>)}
          </div>
        ))}

        {positioned.map(g => (
          <div key={g.id}
            className={"map-node" + (active && active.id === g.id ? " active" : "")}
            style={{ left: g.x + '%', top: g.y + '%' }}
            onClick={() => jumpToSuositus(g.id)}
            onMouseEnter={() => onActiveGoal(g.id)}
            onMouseLeave={() => onActiveGoal(null)}>
            <div className="map-node-dot" style={{ '--accent': themeAccentRGB[g.theme] }}></div>
            <div className="map-node-num">{g.id}</div>
            <div className="map-node-label">№ {g.id} · {g.title}</div>
          </div>
        ))}
      </div>

      <div className="map-detail">
        {active ? (
          <React.Fragment>
            <div className="map-detail-card">
              <div className="map-detail-num">Suositus № {active.id} · {data.themes.find(t => t.id === active.theme).title}</div>
              <h3>{active.title}</h3>
              <div className="map-detail-body-single">
                <p>{active.body ? (active.body.split(/\.\s+/).slice(0,2).join('. ') + '.') : ''}</p>
              </div>
              {active.cta && (
                <a className="map-cta-link" href={active.cta.url} target="_blank" rel="noopener">
                  → {active.cta.label} · {active.cta.note}
                </a>
              )}
              <div className="map-detail-foot">
                <div className="ministry-chips">
                  {active.ministries.map(m => (
                    <span key={m} className="ministry-chip">{m}</span>
                  ))}
                </div>
              </div>
            </div>
          </React.Fragment>
        ) : (
          <div className="map-detail-empty">Vie hiiri solmun päälle nähdäksesi otteen suosituksesta.</div>
        )}
      </div>

      <div className="map-prompt">↓ Jatka lukemaan kappale kerrallaan ↓</div>
    </section>
  );
};

window.GoalMap = GoalMap;
window.themeAccentRGB = themeAccentRGB;
