/* view_trends.jsx — week-over-week trends */

function TrendsView() {
  const { sessionHistory } = useQA();
  const [metric, setMetric] = React.useState("health");
  const H = sessionHistory;
  const cur = H[H.length - 1];
  const prev = H[H.length - 2] || cur;

  const metricDef = {
    health:   { label: "Health score", get: h => h.health,   unit: "", goodUp: true,  color: "var(--accent)" },
    passRate: { label: "Pass rate",    get: h => h.passRate, unit: "%", goodUp: true, color: "var(--grade-good)" },
    clips:    { label: "Clips",        get: h => h.clips,    unit: "", goodUp: false, color: "var(--c-clip)" },
    issues:   { label: "Issues",       get: h => h.issues,   unit: "", goodUp: false, color: "var(--c-treble)" },
  };
  const m = metricDef[metric];
  const max = Math.max(...H.map(m.get), 1) * 1.15 || 1;

  const compareRows = [
    { label: "Health score",    c: cur.health,   p: prev.health,   goodUp: true,  unit: "" },
    { label: "Pass rate",       c: cur.passRate, p: prev.passRate, goodUp: true,  unit: "%" },
    { label: "Clips detected",  c: cur.clips,    p: prev.clips,    goodUp: false, unit: "" },
    { label: "Issues flagged",  c: cur.issues,   p: prev.issues,   goodUp: false, unit: "" },
    { label: "Session length",  c: cur.duration, p: prev.duration, text: true },
  ];

  function Delta({ c, p, goodUp }) {
    const d = c - p;
    if (d === 0) return <span className="delta flat">±0</span>;
    const improved = goodUp ? d > 0 : d < 0;
    return <span className={"delta " + (improved ? "up" : "down")}>{d > 0 ? "+" : ""}{d}</span>;
  }

  const recurring = H.length > 1
    ? [
      { name: "Review issues by person", weeks: H.length, trend: "watch", note: "Each Sunday now keeps separate results for every operator." },
      { name: "Build trend history", weeks: H.length, trend: "new", note: "Add a new Sunday after each service to keep this chart growing." },
    ]
    : [
      { name: "First Sunday started", weeks: 1, trend: "new", note: "Run tests to create the first trend point." },
    ];
  const trendTag = { improving: ["good", "Improving"], watch: ["warn", "Watch"], new: ["high", "New"] };

  return (
    <div className="page fade-up">
      <div className="page-head">
        <div>
          <div className="eyebrow">Week over week</div>
          <h2>Trends</h2>
          <p>How the audio system has performed across the last {H.length} Sundays.</p>
        </div>
        <select className="select" value={metric} onChange={e => setMetric(e.target.value)}>
          <option value="health">Health score</option>
          <option value="passRate">Pass rate</option>
          <option value="clips">Clips detected</option>
          <option value="issues">Issues flagged</option>
        </select>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1.5fr 1fr", marginBottom: 16 }}>
        <Panel title={m.label + " · trend"} icon="trend">
          <div className="weekbars">
            {H.map(h => {
              const v = m.get(h);
              return (
                <div className={"weekbar" + (h.current ? " cur" : "")} key={h.date}>
                  <span className="wb-val" style={{ color: h.current ? m.color : "var(--fg-2)" }}>{v}{m.unit}</span>
                  <div className="wb-fill" style={{
                    height: `${(v / max) * 100}%`,
                    background: h.current ? m.color : "var(--bg-3)",
                    border: h.current ? "none" : "1px solid var(--line-2)",
                    boxShadow: h.current ? "0 0 20px " + m.color + "55" : "none",
                  }} />
                  <span className="wb-lab">{h.label}</span>
                </div>
              );
            })}
          </div>
        </Panel>

        <Panel title="This Sunday vs Last Sunday" icon="layers">
          <div className="row between" style={{ marginBottom: 14 }}>
            <div>
              <div className="rm-label">{prev.label}</div>
              <div className="dim" style={{ fontSize: 12 }}>{prev.operator}</div>
            </div>
            <Icon name="arrow" size={18} color="var(--fg-3)" />
            <div style={{ textAlign: "right" }}>
              <div className="rm-label" style={{ color: "var(--accent)" }}>{cur.label} · this Sunday</div>
              <div className="dim" style={{ fontSize: 12 }}>{cur.operator}</div>
            </div>
          </div>
          <table className="trend-table">
            <tbody>
              {compareRows.map(r => (
                <tr key={r.label}>
                  <td className="dim">{r.label}</td>
                  <td className="mono">{r.p}{r.unit || ""}</td>
                  <td className="mono" style={{ fontWeight: 700 }}>{r.c}{r.unit || ""}</td>
                  <td style={{ textAlign: "right" }}>{r.text ? <span className="delta flat">—</span> : <Delta c={r.c} p={r.p} goodUp={r.goodUp} />}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </Panel>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", marginBottom: 16 }}>
        <Panel title="Recurring Issues" icon="alert">
          <div>
            {recurring.map((r, i) => {
              const [grade, lab] = trendTag[r.trend];
              return (
                <div className="issue-row" key={i}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="issue-name">{r.name}</div>
                    <div className="issue-sub">{r.note}</div>
                  </div>
                  <span className="dim mono" style={{ fontSize: 12 }}>{r.weeks} wks</span>
                  <span className={"chip " + grade}><span className="dot" />{lab}</span>
                </div>
              );
            })}
          </div>
        </Panel>

        <Panel title="Pass rate by group · this Sunday" icon="filter">
          {[["Output Playback", 94], ["Instruments", 88], ["Mic Testing", 90], ["Hall / Room", 86]].map(([g, v]) => (
            <div key={g} style={{ marginBottom: 16 }}>
              <div className="row between" style={{ marginBottom: 6 }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>{g}</span>
                <span className="mono" style={{ color: v >= 90 ? "var(--grade-good)" : "var(--grade-warn)", fontWeight: 600 }}>{v}%</span>
              </div>
              <div className="progress"><i style={{ width: `${v}%`, background: v >= 90 ? "var(--grade-good)" : "var(--grade-warn)" }} /></div>
            </div>
          ))}
        </Panel>
      </div>

      <Panel title="Session History" icon="clock">
        <table className="trend-table">
          <thead>
            <tr>
              <th>Date</th><th>Operator</th><th>Health</th>
              <th>Pass rate</th><th>Clips</th><th>Issues</th>
              <th>Duration</th><th></th>
            </tr>
          </thead>
          <tbody>
            {[...H].reverse().map(h => (
              <tr key={h.date} style={h.current ? { background: "rgba(79,124,255,0.06)" } : null}>
                <td style={{ fontWeight: h.current ? 700 : 500 }}>
                  {window.fmtDate(h.date, { month: "short", day: "numeric", year: "numeric" })}
                  {h.current && <span className="tag info" style={{ marginLeft: 8 }}>CURRENT</span>}
                </td>
                <td className="dim">{h.operator}</td>
                <td className="mono">
                  <span style={{ color: h.health >= 85 ? "var(--grade-good)" : h.health >= 75 ? "var(--grade-warn)" : "var(--grade-high)" }}>{h.health}</span>
                </td>
                <td className="mono">{h.passRate}%</td>
                <td className="mono">{h.clips}</td>
                <td className="mono">{h.issues}</td>
                <td className="mono dim">{h.duration}</td>
                <td style={{ width: 130 }}>
                  <Sparkline points={H.map(x => x.health)} color="var(--accent)" width={120} height={28} fill={false} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Panel>
    </div>
  );
}

Object.assign(window, { TrendsView });
