/* global React, StudyData, productFamily */

// =========================================================
// Consumer Sentiment view — "Explore the data" tab
// Sentiment score = each product's mean P1 rating (1–5)
// rescaled linearly to 0–100:  (mean − 1) / 4 × 100.
// Bars recompute against the active right-panel filters.
// Tier color + benchmark band are anchored to the FULL panel
// (all respondents) so a filtered segment reads against a
// stable reference, exactly like comparing to a benchmark.
// =========================================================

const CS_PLOT_H = 300;          // px height of the plotting (bar) region
const CS_TICKS = [0, 25, 50, 75, 100];

// 1–5 mean → 0–100 sentiment score
function csScore(mean) {
  return Math.round(((mean - 1) / 4) * 100);
}

function csQuantile(sortedAsc, p) {
  if (sortedAsc.length === 0) return 0;
  const i = (sortedAsc.length - 1) * p;
  const lo = Math.floor(i), hi = Math.ceil(i);
  if (lo === hi) return sortedAsc[lo];
  return sortedAsc[lo] + (sortedAsc[hi] - sortedAsc[lo]) * (i - lo);
}

function ConsumerSentimentView({ filtered, allRespondents }) {
  const [selectedId, setSelectedId] = React.useState(null);
  const [view, setView] = React.useState("bars");

  // ---- Benchmark reference: every product, all respondents ----
  const bench = React.useMemo(() => {
    const all = StudyData.aggregateAllProducts(allRespondents).filter((p) => p.n > 0);
    const scores = all.map((p) => csScore(p.meanRating)).sort((a, b) => a - b);
    const mean = scores.reduce((s, v) => s + v, 0) / (scores.length || 1);
    const sd = Math.sqrt(scores.reduce((s, v) => s + (v - mean) ** 2, 0) / (scores.length || 1));
    const q25 = csQuantile(scores, 0.25);
    const q75 = csQuantile(scores, 0.75);
    const band = Math.min(6, Math.max(2, sd * 0.35));
    return { count: all.length, mean, sd, q25, q75, band };
  }, [allRespondents]);

  // ---- Displayed bars: every product, filtered respondents ----
  const products = React.useMemo(() => {
    return StudyData.aggregateAllProducts(filtered)
      .filter((p) => p.n > 0)
      .map((p) => ({ ...p, score: csScore(p.meanRating) }))
      .sort((a, b) => b.score - a.score || b.n - a.n);
  }, [filtered]);

  function tierOf(score) {
    if (score >= bench.q75) return "top";
    if (score <= bench.q25) return "low";
    return "mid";
  }

  const yFor = (v) => CS_PLOT_H * (1 - v / 100);

  return (
    <div className="cs">
      <article className="cs__card">
        {/* Title */}
        <div className="cs__head">
          <h2 className="cs__title">Consumer sentiment</h2>
          <span
            className="cs__info"
            data-tip="Sentiment score = each product's mean “Would you consider buying this item?” rating (1–5), rescaled to 0–100. Higher means stronger purchase intent."
            tabIndex={0}
          >i</span>
        </div>

        {/* Sub-row: compare label + legend */}
        <div className="cs__subrow">
          <div className="cs__compare">
            As compared to {bench.count} products in this study
            <span
              className="cs__info cs__info--sm"
              data-tip="Each bar is colored against the full-panel distribution. Top 25% of products are green, the lower 25% gold, the middle 50% slate. The dashed line marks the benchmark average."
              tabIndex={0}
            >i</span>
          </div>
          <div className="cs__legend">
            <span className="cs__leg"><i className="cs__dot cs__dot--top"></i>Top 25%</span>
            <span className="cs__leg"><i className="cs__dot cs__dot--mid"></i>Mid</span>
            <span className="cs__leg"><i className="cs__dot cs__dot--low"></i>Lower 25%</span>
          </div>
        </div>

        {/* Chart */}
        {view === "bars" && (
        <div className="cs__chart">
          {/* fixed y-axis */}
          <div className="cs__yaxis" style={{ height: CS_PLOT_H }}>
            {CS_TICKS.map((v) => (
              <span key={v} className="cs__ytick" style={{ top: yFor(v) }}>{v}</span>
            ))}
          </div>

          {/* scrolling plot */}
          <div className="cs__scroll">
            <div className="cs__canvas">
              {/* overlay: gridlines + benchmark band + dashed line */}
              <div className="cs__grid" style={{ height: CS_PLOT_H }}>
                {CS_TICKS.map((v) => (
                  <div key={v} className="cs__gridline" style={{ top: yFor(v) }}></div>
                ))}
                <div
                  className="cs__band"
                  style={{
                    top: yFor(bench.mean + bench.band),
                    height: yFor(bench.mean - bench.band) - yFor(bench.mean + bench.band),
                  }}
                ></div>
                <div className="cs__benchline" style={{ top: yFor(bench.mean) }}>
                  <span className="cs__benchtag">Benchmark avg · {Math.round(bench.mean)}</span>
                </div>
              </div>

              {/* bars */}
              <div className="cs__cols">
                {products.map((p) => {
                  const tier = tierOf(p.score);
                  const isSel = p.id === selectedId;
                  const imgUrl = window.PRODUCT_IMAGES && window.PRODUCT_IMAGES.url(p.id);
                  const fam = productFamily(p.title);
                  return (
                    <button
                      key={p.id}
                      className={"cs__col" + (isSel ? " is-sel" : "")}
                      onClick={() => setSelectedId(isSel ? null : p.id)}
                      title={`${p.title} · score ${p.score} · n=${p.n.toLocaleString()}`}
                    >
                      <div className="cs__barbox" style={{ height: CS_PLOT_H }}>
                        <div
                          className={"cs__bar cs__bar--" + tier}
                          style={{ height: `${Math.max(2, (p.score / 100) * CS_PLOT_H)}px` }}
                        >
                          <span className="cs__val">{p.score}</span>
                        </div>
                      </div>
                      <div className="cs__thumb" style={{ background: fam.bg }}>
                        {imgUrl
                          ? <img src={imgUrl} alt={p.title} loading="lazy" />
                          : <span className="cs__thumb-abbr" style={{ color: fam.fg }}>{fam.abbrev}</span>}
                      </div>
                      <div className="cs__name">{p.title}</div>
                    </button>
                  );
                })}
                {products.length === 0 && (
                  <div className="cs__empty">No products have responses in the current filter set.</div>
                )}
              </div>
            </div>
          </div>
        </div>
        )}

        {/* Tile view */}
        {view === "tiles" && (
          <div className="cs__tiles">
            {products.map((p, i) => {
              const tier = tierOf(p.score);
              const imgUrl = window.PRODUCT_IMAGES && window.PRODUCT_IMAGES.url(p.id);
              const fam = productFamily(p.title);
              const isSel = p.id === selectedId;
              return (
                <button
                  key={p.id}
                  className={"cs-tile" + (isSel ? " is-sel" : "")}
                  onClick={() => setSelectedId(isSel ? null : p.id)}
                  title={`${p.title} · score ${p.score} · n=${p.n.toLocaleString()}`}
                >
                  <div className="cs-tile__rank">#{i + 1}</div>
                  <div className="cs-tile__card">
                    {imgUrl
                      ? <img src={imgUrl} alt={p.title} loading="lazy" />
                      : <span className="cs-tile__abbr" style={{ color: fam.fg }}>{fam.abbrev}</span>}
                    <span className={"cs-tile__badge cs-tile__badge--" + tier}>{p.score}</span>
                  </div>
                  <div className="cs-tile__name">{p.title}</div>
                  <div className="cs-tile__id">{p.id}</div>
                </button>
              );
            })}
            {products.length === 0 && (
              <div className="cs__empty">No products have responses in the current filter set.</div>
            )}
          </div>
        )}

        {/* Footer toolbar */}
        <div className="cs__foot">
          <div className="cs__foot-tools">
            <button className={"cs__tool" + (view === "bars" ? " is-active" : "")} title="Bar chart" aria-label="Bar chart" onClick={() => setView("bars")}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="6" y1="20" x2="6" y2="13"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="18" y1="20" x2="18" y2="9"/></svg>
            </button>
            <button className={"cs__tool" + (view === "tiles" ? " is-active" : "")} title="Product tiles" aria-label="Product tiles" onClick={() => setView("tiles")}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 16 4a4 4 0 0 1-8 0L4 6 6 10l2-1v11h8V9l2 1 2-4Z"/></svg>
            </button>
            <button className="cs__tool" title="Expand" aria-label="Expand" disabled>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
            </button>
          </div>
          <div className="cs__foot-right">
            <button className="cs__foot-btn" title="Options">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round"><line x1="4" y1="6" x2="20" y2="6"/><circle cx="9" cy="6" r="2.4" fill="var(--ms-white)"/><line x1="4" y1="14" x2="20" y2="14"/><circle cx="15" cy="14" r="2.4" fill="var(--ms-white)"/></svg>
              Options
            </button>
            <button className="cs__foot-btn cs__foot-btn--icon" title="Fullscreen" aria-label="Fullscreen">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>
            </button>
          </div>
        </div>
      </article>
    </div>
  );
}

Object.assign(window, { ConsumerSentimentView, csScore });
