// SidePanels.jsx — Weights, Ranking, Brief, Compare, Saved
const { useState: useStateSP, useMemo: useMemoSP, useEffect: useEffectSP, useRef: useRefSP } = React;

function WeightsPanel({ weights, setWeights, lang, onPersona, activePersona, onReset }) {
  const t = window.I18N[lang];
  return (
    <section className="panel weights">
      <header className="panel-h">
        <span className="numeral">I</span>
        <h2>{t.weights}</h2>
        <button className="link" onClick={onReset}>{t.reset}</button>
      </header>

      <div className="personas">
        <div className="kicker">{t.personas}</div>
        <div className="persona-row">
          {window.PERSONAS.map(p => (
            <button key={p.id}
                    className={`persona ${activePersona === p.id ? "is-active" : ""}`}
                    onClick={() => onPersona(p)}>
              {p[lang]}
            </button>
          ))}
          <button className={`persona ${activePersona === null ? "is-active" : ""}`}
                  onClick={() => onPersona(null)}>{t.custom}</button>
        </div>
      </div>

      <div className="sliders">
        {window.FACTORS.map(f => (
          <div className="slider-row" key={f.key}>
            <label htmlFor={`w-${f.key}`}>{f[lang]}</label>
            <input id={`w-${f.key}`} type="range" min="0" max="100" step="1"
                   value={weights[f.key]}
                   onChange={(e) => setWeights({ ...weights, [f.key]: +e.target.value })} />
            <span className="val">{weights[f.key]}</span>
          </div>
        ))}
      </div>
    </section>
  );
}

function RankingPanel({ ranked, lang, selectedId, onSelect, prevRanksRef }) {
  const t = window.I18N[lang];
  const top = ranked.slice(0, 8);

  // delta: previous index vs current
  const prev = prevRanksRef.current || {};
  const deltas = {};
  top.forEach((c, i) => {
    const before = prev[c.id];
    if (before === undefined) deltas[c.id] = "new";
    else deltas[c.id] = before - i;
  });
  // update ref
  useEffectSP(() => {
    const next = {};
    ranked.forEach((c, i) => { next[c.id] = i; });
    prevRanksRef.current = next;
  }, [ranked]);

  return (
    <section className="panel ranking">
      <header className="panel-h">
        <span className="numeral">III</span>
        <h2>{t.rankN.replace("{n}", "8")}</h2>
      </header>
      <ol className="rank-list">
        {top.map((c, i) => {
          const d = deltas[c.id];
          let dCls = "delta-flat", dTxt = "·";
          if (d === "new") { dCls = "delta-new"; dTxt = "new"; }
          else if (typeof d === "number") {
            if (d > 0) { dCls = "delta-up"; dTxt = `▲ ${d}`; }
            else if (d < 0) { dCls = "delta-down"; dTxt = `▼ ${-d}`; }
          }
          return (
            <li key={c.id}
                className={`rank-row ${selectedId === c.id ? "is-selected" : ""}`}
                onClick={() => onSelect(c.id)}>
              <span className="rank-num">{String(i + 1).padStart(2, "0")}</span>
              <span className="rank-name">
                <span className="rn">{c.name}</span>
                <span className="rc">{c.country}</span>
              </span>
              <span className="fit-bar">
                <span className="fit-fill" style={{ width: `${c.fit}%`, background: window.scoreColor(c.fit) }} />
              </span>
              <span className="fit-num">{Math.round(c.fit)}</span>
              <span className={`delta ${dCls}`}>{dTxt}</span>
            </li>
          );
        })}
      </ol>
    </section>
  );
}

function BriefPanel({ city, lang, weights, onCompare }) {
  const t = window.I18N[lang];
  if (!city) {
    return (
      <section className="panel brief brief-empty">
        <header className="panel-h"><span className="numeral">IV</span><h2>{t.brief}</h2></header>
        <div className="empty-msg">{t.pickFromMap}</div>
      </section>
    );
  }
  const fit = window.scoreCity(city, weights);
  const factors = window.FACTORS.map(f => ({
    ...f, value: city.scores[f.key], weight: weights[f.key]
  })).sort((a,b) => (b.weight * b.value) - (a.weight * a.value));

  const topFactors = factors.slice(0, 3);
  const weakFactors = [...factors].sort((a,b) => (a.weight * (100 - a.value)) - (b.weight * (100 - b.value))).reverse().slice(0, 2);

  return (
    <section className="panel brief">
      <header className="panel-h">
        <span className="numeral">IV</span>
        <h2>{t.brief}</h2>
        <button className="link" onClick={() => onCompare(city.id)}>+ {t.compare}</button>
      </header>
      <div className="brief-body">
        <div className="brief-hero">
          <div className="hero-side">
            <div className="kicker">{city.country.toUpperCase()}</div>
            <h3 className="city-name">{city.name}</h3>
            <div className="brief-meta">
              <span>{t.pop} {city.pop}M</span>
              <span>·</span>
              <span>{city.lonlat[1].toFixed(1)}°N {city.lonlat[0].toFixed(1)}°E</span>
            </div>
          </div>
          <div className="hero-fit">
            <div className="fit-circle" style={{ ["--c"]: window.scoreColor(fit) }}>
              <svg viewBox="0 0 100 100">
                <circle cx="50" cy="50" r="44" className="fc-track" />
                <circle cx="50" cy="50" r="44" className="fc-fill"
                        strokeDasharray={`${fit * 2.764} 276.4`} />
              </svg>
              <div className="fit-num-big">{Math.round(fit)}</div>
              <div className="fit-lbl">{t.overall}</div>
            </div>
          </div>
        </div>

        <div className="brief-pull">
          <span className="quote">“</span>
          <p>
            {city.name} {lang === "en"
              ? `scores strongest on ${topFactors[0][lang].toLowerCase()}, ${topFactors[1][lang].toLowerCase()} and ${topFactors[2][lang].toLowerCase()}. Watch out for ${weakFactors[0][lang].toLowerCase()}.`
              : `punktet vor allem bei ${topFactors[0][lang].toLowerCase()}, ${topFactors[1][lang].toLowerCase()} und ${topFactors[2][lang].toLowerCase()}. Achte auf ${weakFactors[0][lang].toLowerCase()}.`}
          </p>
        </div>

        <div className="brief-factors">
          <div className="kicker">{t.factorBreakdown}</div>
          <ul>
            {window.FACTORS.map(f => {
              const v = city.scores[f.key];
              const w = weights[f.key];
              return (
                <li key={f.key} className={w >= 70 ? "is-heavy" : w <= 25 ? "is-light" : ""}>
                  <span className="bf-label">{f[lang]}</span>
                  <span className="bf-bar"><span className="bf-fill" style={{ width: `${v}%`, background: window.scoreColor(v) }} /></span>
                  <span className="bf-num">{v}</span>
                  <span className="bf-w">×{w}</span>
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    </section>
  );
}

function ComparePanel({ cityA, cityB, lang, weights, onPickA, onPickB, onClear }) {
  const t = window.I18N[lang];
  if (!cityA || !cityB) {
    return (
      <section className="panel compare compare-empty">
        <header className="panel-h"><span className="numeral">V</span><h2>{t.compare}</h2></header>
        <div className="empty-msg">{t.selectTwo}</div>
        <div className="compare-slots">
          <div className="slot">{cityA ? cityA.name : "A —"}</div>
          <div className="slot">{cityB ? cityB.name : "B —"}</div>
        </div>
      </section>
    );
  }
  const fitA = window.scoreCity(cityA, weights);
  const fitB = window.scoreCity(cityB, weights);

  return (
    <section className="panel compare">
      <header className="panel-h">
        <span className="numeral">V</span>
        <h2>{t.compare}</h2>
        <button className="link" onClick={onClear}>{t.reset}</button>
      </header>
      <div className="compare-grid">
        <div className="cmp-col">
          <div className="kicker">A · {cityA.country}</div>
          <h3>{cityA.name}</h3>
          <div className="cmp-fit" style={{ color: window.scoreColor(fitA) }}>{Math.round(fitA)}</div>
        </div>
        <div className="cmp-vs">vs</div>
        <div className="cmp-col">
          <div className="kicker">B · {cityB.country}</div>
          <h3>{cityB.name}</h3>
          <div className="cmp-fit" style={{ color: window.scoreColor(fitB) }}>{Math.round(fitB)}</div>
        </div>
      </div>
      <ul className="cmp-rows">
        {window.FACTORS.map(f => {
          const a = cityA.scores[f.key];
          const b = cityB.scores[f.key];
          return (
            <li key={f.key}>
              <span className="cmp-l" style={{ width: `${a}%`, background: window.scoreColor(a) }} />
              <span className="cmp-an">{a}</span>
              <span className="cmp-lbl">{f[lang]}</span>
              <span className="cmp-bn">{b}</span>
              <span className="cmp-r" style={{ width: `${b}%`, background: window.scoreColor(b) }} />
            </li>
          );
        })}
      </ul>
    </section>
  );
}

function ScenariosPanel({ scenarios, onApply, onSave, onDelete, lang, currentName, setCurrentName }) {
  const t = window.I18N[lang];
  return (
    <section className="panel scenarios">
      <header className="panel-h">
        <span className="numeral">·</span>
        <h2>{t.saved}</h2>
      </header>
      <div className="save-row">
        <input value={currentName} onChange={e => setCurrentName(e.target.value)}
               placeholder={t.name} />
        <button className="btn-primary" onClick={onSave}>{t.save}</button>
      </div>
      {scenarios.length === 0 ? (
        <div className="empty-msg sm">{t.nothing}</div>
      ) : (
        <ul className="scn-list">
          {scenarios.map(s => (
            <li key={s.id}>
              <span className="scn-name">{s.name}</span>
              <span className="scn-meta">{Object.values(s.weights).reduce((a,b)=>a+b,0)}pts</span>
              <button className="link" onClick={() => onApply(s)}>{t.apply}</button>
              <button className="link danger" onClick={() => onDelete(s.id)}>×</button>
            </li>
          ))}
        </ul>
      )}
    </section>
  );
}

window.WeightsPanel = WeightsPanel;
window.RankingPanel = RankingPanel;
window.BriefPanel = BriefPanel;
window.ComparePanel = ComparePanel;
window.ScenariosPanel = ScenariosPanel;
