// Cost-vs-days chart, comparison table, and resort coverage map.

function CostChart({ ranked, inputs, selectedIds }) {
  const W = 720, H = 320, P = { t: 24, r: 24, b: 36, l: 52 };
  const innerW = W - P.l - P.r;
  const innerH = H - P.t - P.b;
  const maxDays = 40;
  const maxY = 260;

  const visible = ranked.filter(m => selectedIds.includes(m.pass.id));

  const xScale = d => P.l + (d / maxDays) * innerW;
  const yScale = v => P.t + innerH - (Math.min(v, maxY) / maxY) * innerH;

  const passLine = (m) => {
    const points = [];
    for (let d = 1; d <= maxDays; d++) {
      const cpd = computePassMetrics(m.pass, { ...inputs, days: d }, []).costPerDay;
      points.push([xScale(d), yScale(Math.min(cpd, maxY))]);
    }
    return points.map((p, i) => `${i === 0 ? "M" : "L"} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ");
  };

  // Find break-even for current top pass (where its cpd dips under avg window)
  const top = visible[0];

  return (
    <div className="chart">
      <div className="panel-head">
        <div>
          <div className="panel-eyebrow">Cost dynamics</div>
          <div className="panel-title">Effective $/day across days skied</div>
        </div>
        <div className="chart-legend">
          {visible.map(m => (
            <div key={m.pass.id} className="legend-item">
              <span className="legend-swatch" style={{ background: m.pass.color }} />
              <span>{m.pass.name}</span>
            </div>
          ))}
        </div>
      </div>

      <svg viewBox={`0 0 ${W} ${H}`} className="chart-svg">
        {/* Y grid */}
        {[0, 65, 130, 195, 260].map(v => (
          <g key={v}>
            <line x1={P.l} x2={W - P.r} y1={yScale(v)} y2={yScale(v)} stroke="#1c262015" strokeDasharray={v === 0 ? "" : "2 4"} />
            <text x={P.l - 8} y={yScale(v) + 4} fontSize="10" textAnchor="end" fill="#6b6b60" fontFamily="JetBrains Mono, monospace">${v}</text>
          </g>
        ))}
        {/* X grid */}
        {[1, 10, 20, 30, 40].map(d => (
          <g key={d}>
            <line x1={xScale(d)} x2={xScale(d)} y1={P.t} y2={H - P.b} stroke="#1c262010" />
            <text x={xScale(d)} y={H - P.b + 16} fontSize="10" textAnchor="middle" fill="#6b6b60" fontFamily="JetBrains Mono, monospace">{d}d</text>
          </g>
        ))}
        {/* Current days marker */}
        <line x1={xScale(inputs.days)} x2={xScale(inputs.days)} y1={P.t} y2={H - P.b} stroke="#1c2620" strokeWidth="1" strokeDasharray="3 3" opacity="0.5" />
        <text x={xScale(inputs.days)} y={P.t - 8} fontSize="10" textAnchor="middle" fill="#1c2620" fontFamily="JetBrains Mono, monospace">{inputs.days}d ↓</text>

        {/* Curves */}
        {visible.map(m => (
          <g key={m.pass.id}>
            <path d={passLine(m)} fill="none" stroke={m.pass.color} strokeWidth={m === top ? 2.5 : 1.5} opacity={m === top ? 1 : 0.7} />
            {/* Marker at current days */}
            <circle cx={xScale(inputs.days)} cy={yScale(Math.min(m.costPerDay, maxY))} r="4" fill={m.pass.color} stroke="#f4efe6" strokeWidth="2" />
          </g>
        ))}

        {/* Axes */}
        <line x1={P.l} x2={W - P.r} y1={H - P.b} y2={H - P.b} stroke="#1c2620" strokeWidth="1" />
        <line x1={P.l} x2={P.l} y1={P.t} y2={H - P.b} stroke="#1c2620" strokeWidth="1" />

        <text x={W - P.r} y={H - 6} fontSize="10" textAnchor="end" fill="#6b6b60" fontFamily="JetBrains Mono, monospace">DAYS SKIED →</text>
        <text x={P.l + 4} y={P.t - 8} fontSize="10" fill="#6b6b60" fontFamily="JetBrains Mono, monospace">$/DAY</text>
      </svg>

      <div className="chart-callout">
        {visible.slice(0, 3).map(m => (
          <div key={m.pass.id} className="callout-row">
            <span className="callout-swatch" style={{ background: m.pass.color }} />
            <span className="callout-name">{m.pass.name}</span>
            <span className="callout-mid">becomes cheaper than window after</span>
            <span className="callout-v">{m.breakEven} days</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function ComparisonTable({ ranked, inputs }) {
  return (
    <div className="table-wrap">
      <div className="panel-head">
        <div>
          <div className="panel-eyebrow">Side by side</div>
          <div className="panel-title">All passes at {inputs.days} days</div>
        </div>
      </div>
      <table className="cmp">
        <thead>
          <tr>
            <th>Pass</th>
            <th className="num">Price</th>
            <th className="num">$/day</th>
            <th className="num">Break-even</th>
            <th className="num">Resorts</th>
            <th>Blackouts</th>
            <th>Best for</th>
          </tr>
        </thead>
        <tbody>
          {ranked.map((m, i) => (
            <tr key={m.pass.id} className={i === 0 ? "is-top" : ""}>
              <td>
                <div className="cmp-name">
                  <span className="cmp-swatch" style={{ background: m.pass.color }} />
                  <div>
                    <div>{m.pass.name}</div>
                    <div className="cmp-op">{m.pass.operator}</div>
                  </div>
                </div>
              </td>
              <td className="num">${m.pass.price.toLocaleString()}</td>
              <td className="num accent">${Math.round(m.costPerDay)}</td>
              <td className="num">{m.breakEven}d</td>
              <td className="num">{m.pass.resortCount}</td>
              <td>{m.pass.blackouts === 0 ? "None" : `${m.pass.blackouts} dates`}</td>
              <td className="muted">
                {m.pass.travelFriendly && m.pass.localFriendly ? "Local + travel"
                  : m.pass.travelFriendly ? "Trip skiers"
                  : "Local skiers"}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function ResortMap({ resorts, ranked, selectedIds, regionFilter, setRegionFilter }) {
  const passById = Object.fromEntries(PASSES.map(p => [p.id, p]));
  const filtered = resorts.filter(r => {
    if (regionFilter !== "All" && r.region !== regionFilter) return false;
    return r.passes.some(pid => selectedIds.includes(pid));
  });

  const regions = ["All", ...Array.from(new Set(resorts.map(r => r.region)))];

  return (
    <div className="map-wrap">
      <div className="panel-head">
        <div>
          <div className="panel-eyebrow">Coverage</div>
          <div className="panel-title">Resorts on selected passes</div>
        </div>
        <div className="map-filter">
          {regions.slice(0, 8).map(r => (
            <button
              key={r}
              className={`mini-chip ${regionFilter === r ? "is-active" : ""}`}
              onClick={() => setRegionFilter(r)}
            >{r}</button>
          ))}
        </div>
      </div>

      <div className="map-grid">
        <div className="map-canvas">
          <svg viewBox="0 0 1000 500" preserveAspectRatio="xMidYMid meet">
            {/* Stylized continent silhouette */}
            <path d="M 80 90 Q 120 60 200 80 L 320 70 Q 420 60 520 90 L 680 100 Q 780 95 860 130 L 920 200 Q 940 280 880 360 L 780 410 Q 680 430 580 420 L 420 415 Q 320 410 240 380 L 140 320 Q 90 260 70 200 Z"
              fill="#e8e0d2" stroke="#1c262025" strokeWidth="1" />
            {/* Latitude lines */}
            {[0.25, 0.5, 0.75].map(y => (
              <line key={y} x1="80" x2="920" y1={y * 500} y2={y * 500} stroke="#1c262010" strokeDasharray="2 6" />
            ))}
            {/* Resorts */}
            {filtered.map(r => {
              const cx = r.x * 1000;
              const cy = r.y * 500;
              const onTopPass = ranked[0] && r.passes.includes(ranked[0].pass.id);
              const passColor = passById[r.passes.find(p => selectedIds.includes(p))]?.color || "#1c2620";
              return (
                <g key={r.id}>
                  {onTopPass && <circle cx={cx} cy={cy} r="14" fill={passColor} opacity="0.12" />}
                  <circle cx={cx} cy={cy} r={onTopPass ? 5 : 3.5} fill={passColor} stroke="#f4efe6" strokeWidth="1.5" />
                  <text x={cx + 8} y={cy + 3} fontSize="9" fill="#1c2620" fontFamily="JetBrains Mono, monospace">{r.name}</text>
                </g>
              );
            })}
          </svg>
        </div>
        <div className="map-list">
          <div className="map-list-head">
            <span>{filtered.length} resorts</span>
            <span className="muted">{regionFilter}</span>
          </div>
          <div className="map-list-body">
            {filtered.map(r => (
              <div key={r.id} className="map-list-row">
                <div>
                  <div className="mlr-name">{r.name}</div>
                  <div className="mlr-region">{r.region}</div>
                </div>
                <div className="mlr-passes">
                  {r.passes.filter(pid => selectedIds.includes(pid)).map(pid => (
                    <span key={pid} className="mlr-pass" style={{ background: passById[pid].color }}>
                      {passById[pid].name.split(" ")[0]}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.CostChart = CostChart;
window.ComparisonTable = ComparisonTable;
window.ResortMap = ResortMap;
