// Price history chart — SVG, vanilla feel
// uPlot would go here per DESIGN.md §3.5 — using SVG so it ships in one file

function PriceHistoryChart({ series, statistics, merchants }) {
  const ZOOMS = [
    { id: 30, label: '30 G' },
    { id: 90, label: '90 G' },
    { id: 180, label: '180 G' },
  ];
  const [zoom, setZoom] = React.useState(90);
  const [hover, setHover] = React.useState(null);

  if (!series || series.length < 3) {
    return <div style={{ padding: 24, textAlign: 'center', color: 'var(--km-ink-500)', fontSize: 14 }}>
      Fiyat geçmişi henüz yeterli değil.
    </div>;
  }

  const cutoff = Date.now() - zoom * 86400000;
  const data = series.filter(d => d.t >= cutoff);
  const W = 800, H = 280, PAD_L = 56, PAD_R = 24, PAD_T = 16, PAD_B = 28;
  const xs = data.map(d => d.t);
  const ys = data.map(d => d.p);
  const xMin = Math.min(...xs), xMax = Math.max(...xs);
  const yMin = Math.min(...ys) * 0.98, yMax = Math.max(...ys) * 1.02;
  const xScale = (t) => PAD_L + ((t - xMin) / (xMax - xMin || 1)) * (W - PAD_L - PAD_R);
  const yScale = (p) => H - PAD_B - ((p - yMin) / (yMax - yMin || 1)) * (H - PAD_T - PAD_B);

  // Smooth area path
  const linePath = data.map((d, i) => `${i === 0 ? 'M' : 'L'} ${xScale(d.t)} ${yScale(d.p)}`).join(' ');
  const areaPath = `${linePath} L ${xScale(xMax)} ${H - PAD_B} L ${xScale(xMin)} ${H - PAD_B} Z`;

  // Y ticks (4)
  const yTicks = [yMin, yMin + (yMax - yMin) * 0.33, yMin + (yMax - yMin) * 0.66, yMax].map(v => Math.round(v / 50) * 50);

  // X ticks: 4 labels in tr
  const months = ['Oca','Şub','Mar','Nis','May','Haz','Tem','Ağu','Eyl','Eki','Kas','Ara'];
  const xTickT = [0, 0.33, 0.66, 1].map(f => xMin + f * (xMax - xMin));

  // current vs avg badge
  const current = data[data.length - 1].p;
  const first = data[0].p;
  const change = current - first;
  const changePct = (change / first) * 100;

  const onMove = (e) => {
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * W;
    if (x < PAD_L || x > W - PAD_R) { setHover(null); return; }
    const t = xMin + ((x - PAD_L) / (W - PAD_L - PAD_R)) * (xMax - xMin);
    let nearest = data[0], dist = Infinity;
    for (const d of data) { const dd = Math.abs(d.t - t); if (dd < dist) { nearest = d; dist = dd; } }
    setHover(nearest);
  };

  return (
    <div className="card chart-card">
      <div className="chart-legend">
        <div className="chart-legend__stat">
          <strong className="tabular">{formatPrice(current)}</strong>
          <span>şu an</span>
        </div>
        <div className="chart-legend__stat">
          <span>30 gün ort. </span>
          <strong className="tabular" style={{ fontSize: 14 }}>{formatPrice(statistics.avg30)}</strong>
        </div>
        <div className="chart-legend__stat">
          <span>En düşük </span>
          <strong className="tabular" style={{ fontSize: 14, color: 'var(--km-good)' }}>{formatPrice(statistics.lowestEver)}</strong>
        </div>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12,
          color: change <= 0 ? 'var(--km-good)' : 'var(--km-bad)', fontWeight: 600,
          padding: '2px 8px', borderRadius: 999,
          background: change <= 0 ? 'var(--km-good-soft)' : 'var(--km-bad-soft)' }}>
          {change <= 0 ? '↓' : '↑'} {Math.abs(changePct).toFixed(1)}% son {zoom} gün
        </span>
        <div className="chart-zoom" role="tablist">
          {ZOOMS.map(z => (
            <button key={z.id} className={zoom === z.id ? 'on' : ''} onClick={() => setZoom(z.id)}>{z.label}</button>
          ))}
        </div>
      </div>

      <div style={{ position: 'relative', aspectRatio: '800 / 280' }}>
        <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%"
             onMouseMove={onMove} onMouseLeave={() => setHover(null)}
             style={{ display: 'block' }}>
          <defs>
            <linearGradient id="areaG" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="var(--km-deep-2)" stopOpacity="0.22"/>
              <stop offset="100%" stopColor="var(--km-deep-2)" stopOpacity="0"/>
            </linearGradient>
          </defs>
          {/* Y grid */}
          {yTicks.map((y, i) => (
            <g key={i}>
              <line x1={PAD_L} x2={W - PAD_R} y1={yScale(y)} y2={yScale(y)} stroke="var(--km-line)" strokeDasharray="2 4"/>
              <text x={PAD_L - 8} y={yScale(y) + 4} textAnchor="end" fontSize="11" fill="var(--km-ink-400)" fontFamily="var(--font-mono)">
                {formatPrice(y).replace('₺', '₺')}
              </text>
            </g>
          ))}
          {/* lowest-ever band */}
          <line x1={PAD_L} x2={W - PAD_R} y1={yScale(statistics.lowestEver)} y2={yScale(statistics.lowestEver)} stroke="var(--km-good)" strokeDasharray="4 4" strokeWidth="1"/>
          <text x={W - PAD_R - 4} y={yScale(statistics.lowestEver) - 4} fontSize="10" fill="var(--km-good)" textAnchor="end" fontWeight="600">EN DÜŞÜK</text>

          {/* area + line */}
          <path d={areaPath} fill="url(#areaG)"/>
          <path d={linePath} fill="none" stroke="var(--km-deep-2)" strokeWidth="2"/>

          {/* X labels */}
          {xTickT.map((t, i) => {
            const d = new Date(t);
            return <text key={i} x={xScale(t)} y={H - 8} fontSize="11" fill="var(--km-ink-400)" textAnchor="middle">
              {d.getDate()} {months[d.getMonth()]}
            </text>;
          })}

          {/* hover */}
          {hover && (
            <g>
              <line x1={xScale(hover.t)} x2={xScale(hover.t)} y1={PAD_T} y2={H - PAD_B} stroke="var(--km-ink-700)" strokeDasharray="2 3" opacity="0.5"/>
              <circle cx={xScale(hover.t)} cy={yScale(hover.p)} r="5" fill="var(--km-deep)" stroke="white" strokeWidth="2"/>
            </g>
          )}
        </svg>
        {hover && (() => {
          const d = new Date(hover.t);
          const xpc = (xScale(hover.t) / W) * 100;
          const flipLeft = xpc > 70;
          return (
            <div style={{
              position: 'absolute',
              left: `${xpc}%`,
              top: '20%',
              transform: flipLeft ? 'translate(-100%, 0)' : 'translate(8px, 0)',
              background: 'var(--km-ink-900)',
              color: 'white',
              padding: '8px 12px',
              borderRadius: 8,
              fontSize: 12,
              pointerEvents: 'none',
              whiteSpace: 'nowrap',
              boxShadow: 'var(--shadow-3)',
            }}>
              <div style={{ opacity: 0.7, fontSize: 11 }}>{d.getDate()} {months[d.getMonth()]}</div>
              <div className="tabular" style={{ fontWeight: 600, fontSize: 14 }}>{formatPrice(hover.p)}</div>
            </div>
          );
        })()}
      </div>

      <p style={{ marginTop: 12, fontSize: 12, color: 'var(--km-ink-400)' }}>
        Mavi çizgi — günlük en düşük teklif. Yeşil kesik çizgi — son {zoom} gündeki en düşük seviye. Veri kaynağı: tüm satıcılardan saatlik snapshot.
      </p>
    </div>
  );
}

Object.assign(window, { PriceHistoryChart });
