<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="UTF-8">
  <title>株式チャート</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://www.highcharts.com/highslide/highslide.css" rel="stylesheet">
  <script src="https://code.highcharts.com/stock/6/highstock.js"></script>
  <script src="https://code.highcharts.com/6/highcharts-more.js"></script>
  <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">

</head>

<body style="margin:0;padding:0;">
  <!-- ヘッダー -->



  <div id="navbar" class="d-flex align-items-center p-2">
    <h1 class="mb-0 me-2">株式チャート</h1>

    <div class="d-flex align-items-center">
      <div class="dropdown me-1">
        <button class="btn btn-sm btn-secondary btn-no-outline">銘柄選択 ▼</button>
        <div class="dropdown-content">

          {% for s in stocks %}
          <a href="/stock/{{ s.code }}" data-stock="{{ s.code }}"
            class="{% if s.code == stock.code %}active{% endif %}">{{
            s.name }} {{ s.code }}</a>

          {% endfor %}

        </div>
      </div>
      <form id="trendline-form" class="d-flex flex-nowrap align-items-center gap-2">
        <div class="d-flex align-items-center">
          <label for="lookback" class="form-label mb-0 me-1">Lookback:</label>
          <input type="number" id="lookback" class="form-control form-control-sm input-wrapper" style="width: 60px;"
            value="100">
        </div>

        <div class="d-flex align-items-center">
          <label for="min_touches" class="form-label mb-0 me-2">Min:</label>
          <input type="number" id="min_touches" class="form-control form-control-sm input-wrapper" style="width: 44px;"
            value="5">
        </div>

        <div class="d-flex align-items-center">
          <label for="order" class="form-label mb-0 me-1">Order:</label>
          <input type="number" id="order" class="form-control form-control-sm input-wrapper" style="width: 44px;"
            value="5">
        </div>

        <button type="submit" class="btn btn-sm btn-secondary btn-no-outline">更新</button>
      </form>
    </div>
  </div>



  <div id="container">Loading....</div>
  <script>
    const chartData = {{ chart_data | tojson
    }};
    const dates = chartData.date.map(date => Date.UTC(new Date(date).getFullYear(), new Date(date).getMonth(), new Date(date).getDate()));

    let showBand = {{ is_rise | lower }}; // 上がるパターンに合致しているか

    // 直近3日間の範囲を取得
    let lastDate = new Date(dates[dates.length - 1]);
    let threeDaysAgo = new Date(lastDate);
    threeDaysAgo.setDate(lastDate.getDate() - 2);

    let baseSeries = [
      {
        type: 'candlestick', name: '株価', yAxis: 0,
        data: dates.map((date, i) => [date, chartData.open[i], chartData.high[i], chartData.low[i], chartData.close[i]]),
        dataGrouping: { units: [["day", [1]]] }
      },
      { type: 'line', name: '移動平均線 (5日)', yAxis: 0, data: dates.map((date, i) => [date, chartData.ma5[i]]), color: 'magenta', lineWidth: 1 },
      { type: 'line', name: '移動平均線 (25日)', yAxis: 0, data: dates.map((date, i) => [date, chartData.ma25[i]]), color: 'limegreen', lineWidth: 1 },
      //{ type: 'line', name: '移動平均線 (75日)', yAxis: 0, data: dates.map((date, i) => [date, chartData.ma75[i]]), color: 'darkblue', lineWidth: 1 },
      { type: 'arearange', name: 'ボリンジャーバンド', yAxis: 0, data: dates.map((date, i) => [date, chartData.lower2[i], chartData.upper2[i]]), color: '#7cb5ec', fillOpacity: 0.15, lineWidth: 0, enableMouseTracking: false },

      { type: 'line', name: '短期 RCI', yAxis: 1, data: dates.map((date, i) => [date, chartData.rci9[i]]), color: 'magenta', lineWidth: 1 },

      { type: 'line', name: '長期 RCI', yAxis: 1, data: dates.map((date, i) => [date, chartData.rci26[i]]), color: 'green', lineWidth: 1 },
      { type: 'line', name: 'MACD', yAxis: 2, data: dates.map((date, i) => [date, chartData.macd[i]]), color: 'magenta', lineWidth: 1 },
      { type: 'line', name: 'SIGNAL', yAxis: 2, data: dates.map((date, i) => [date, chartData.macd_signal[i]]), color: 'green', lineWidth: 1 },
      { type: 'column', name: 'Volume', yAxis: 3, data: dates.map((date, i) => [date, chartData.volume[i]]), color: 'slategray', lineWidth: 1 },
    ];

    const options = {
      chart: { renderTo: 'container', width: 900, height: 1200 },

      title: { text: "{{ stock.name }} {{ stock.code }}" },
      rangeSelector: { selected: 2, inputDateFormat: '%Y-%m-%d', inputEditDateFormat: '%Y-%m-%d', inputEnabled: true },
      xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: { day: '%Y-%m-%d', week: '%Y-%m-%d', month: '%Y-%m', year: '%Y' },
        // 株価が上がるパターンに合致していれば直近3日間に背景色をつける
        plotBands: showBand ? [{
          from: threeDaysAgo.getTime(),
          to: lastDate.getTime(),
          color: 'rgba(255, 69, 0, 0.2)'  // 背景色
        }] : [],
      },
      yAxis: [
        { title: { text: "株価", align: "middle" }, height: "70%", offset: 30 },
        { title: { text: "RCI", align: "middle" }, top: "70%", height: "10%", offset: 30 },
        { title: { text: "MACD", align: "middle" }, top: "80%", height: "10%", offset: 30 },
        { title: { text: "Volume", align: "middle" }, top: "90%", height: "10%", offset: 30 }
      ],
      tooltip: {
        shared: true,
        formatter: function () {
          let s = `<b>${Highcharts.dateFormat('%Y-%m-%d', this.x)}</b><br>`;
          this.points.forEach(point => {
            if (point.series.type === 'candlestick') {
              s += `<span style="color:${point.series.color}">\u25CF</span> ${point.series.name}:<br>
                    Open: ${point.point.open.toLocaleString()}<br>
                    High: ${point.point.high.toLocaleString()}<br>
                    Low: ${point.point.low.toLocaleString()}<br>
                    Close: ${point.point.close.toLocaleString()}<br>`;
            } else {
              s += `<span style="color:${point.color}">\u25CF</span> ${point.series.name}: ${point.y.toLocaleString()}<br>`;
            }
          });
          return s;
        }
      },
      series: [
        ...baseSeries,
      ]
    };

    // トレンドラインの始点と終点を取得
    function fetchTrendLines() {
      const params = new URLSearchParams({
        lookback: document.getElementById("lookback").value,
        min_touches: document.getElementById("min_touches").value,
        order: document.getElementById("order").value
      });

      fetch(`/update_trendlines/{{ stock.code }}?${params.toString()}`)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTPエラー: ${response.status}`);
          }
          return response.json();
        })
        .then(data => {
          updateTrendLines(data);
        })
        .catch(error => {
          console.error("トレンドライン取得エラー:", error);
        });
    }

    // トレンドラインの始点と終点をチャートに表示する形式に変換
    function updateTrendLines(trendLines) {
      let trendlineSeries = trendLines.map((line, i) => ({
        type: "line",
        name: `Trendline ${i + 1}`,
        yAxis: 0,
        color: line.type === "uptrend" ? "blue" : "red",
        lineWidth: 2,
        data: [
          [Date.UTC(new Date(line.start[0]).getFullYear(), new Date(line.start[0]).getMonth(), new Date(line.start[0]).getDate()), line.start[1]],
          [Date.UTC(new Date(line.end[0]).getFullYear(), new Date(line.end[0]).getMonth(), new Date(line.end[0]).getDate()), line.end[1]]
        ]
      }));

      // チャートに表示するシリーズを指定
      options.series = [
        ...baseSeries,
        ...trendlineSeries
      ];

      // 新しくチャートを再生成
      new Highcharts.StockChart(options);
    }

    document.addEventListener("DOMContentLoaded", function () {
      // 初回のチャート表示
      new Highcharts.StockChart(options);

      // フォーム送信時の処理
      document.getElementById("trendline-form").addEventListener("submit", function (e) {
        e.preventDefault();  // フォームのデフォルト送信を防ぐ
        fetchTrendLines();
      });
    });
  </script>
</body>

</html>