type InjectJavascriptData = (
  a: string,
  b: string,
  c: string,
  d: string,
  e: string
) => string;
export const injectJavascriptData: InjectJavascriptData = (
  mapSwitch,
  iconSetting,
  stationMenu,
  trainMenu,
  uiSetting
) => {
  // 一番上のメニュー非表示　地図スイッチによって切り替え
  const topMenu =
    mapSwitch != "true"
      ? `
      document.querySelector('#header a').style.display = 'none';
      document.querySelector('#main').style.left = '0px';
      document.querySelector('#header').style.height = '50px';
      document.querySelector('#main').style.paddingTop = '54px';
      document.querySelector('#headerStr').style.display = 'none';
      `
      : `
      document.querySelector('.accordionClass').style.display = 'none';
      document.querySelector('#header').style.display = 'none';
      document.querySelector('#main').style.left = '0px';
      document.querySelector('#main').style.paddingTop = '0px';
      document.querySelector('#headerStr').style.display = 'none';
      `;

  // 上部ヘッダーの取り扱い、自動再読み込み、setStringsの実行
  const bootData = `
    // 起動時にブラウザにlodashを読み込むscript追加処理
    const script = document.createElement('script');
    script.src = "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js";
    document.head.appendChild(script);

    const script2 = document.createElement('link');
    script2.rel = "stylesheet";
    script2.href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.0/css/all.min.css";
    document.head.appendChild(script2);
    
    let stationList = {};
    fetch("https://n8n.haruk.in/webhook/jr-shikoku-station-list").then((response) => response.json()).then((data) => {
      stationList = data;
    }).then(()=>setReload());

    let trainDataList = [];
     const DatalistUpdate = () =>{
      try{
        fetch("https://n8n.haruk.in/webhook/jr-shikoku-position-custom-datalist").then((response) => response.json())
        .then((data) => data[0].data)
        .then((data) => {
          if(!_.isEqual(data, trainDataList)) {
            trainDataList = data;
            setReload();
          }
        });
      }catch(error){}
      setTimeout(DatalistUpdate, 60000);
    }
    DatalistUpdate();


    let trainDiagramData2 = {};
    const TrainDiagramData2Update = () =>{
      try{
        fetch("https://n8n.haruk.in/webhook/JR-shikoku-diagram-migrate-original")
          .then((response) => response.json())
          .then((res)=>res.data)
          .then((res) => {
              const data = {};
              res.forEach((d) => {
                const keys = Object.keys(d);
                data[keys] = d[keys];
              });
              return data;
            })
          .then((data) => {
            if(!_.isEqual(data, trainDiagramData2)) {
              trainDiagramData2 = data;
              setReload();
            }
          });
      }catch(error){}
      setTimeout(TrainDiagramData2Update, 60000);
    }
    TrainDiagramData2Update();
    
    let probremsData = [];

    const getProblemsData = () =>{
      try{
       fetch("https://n8n.haruk.in/webhook/jrshikoku-position-problems").then((response) => response.json()).then((data) => {
          if(!_.isEqual(data, probremsData)) {
            probremsData = data.data;
            setReload();
          }
        });
      }catch(error){}
      setTimeout(getProblemsData, 30000);
    }
    getProblemsData();

    const setReload = () =>{
      try{
        document.getElementById('refreshIcon').click();
        setStrings();
      }catch(error){}
    };
  `;
  // 左か右かを判定してアイコンを設置する
  const trainIcon = `
    const setStationIcon = (setIconElem,img,hasProblem) =>{
      const position = setIconElem.getAttribute("style").includes("left");
      const marginData = ${uiSetting === "tokyo" ? `"5px"`: `"2px"`}
      setIconElem.insertAdjacentHTML('beforebegin', "<img src="+img+" style='float:"+(position ? 'left' : 'right')+";height:22px;margin: "+marginData+";'>");
      setIconElem.remove();
    }
    
    const setTrainIcon = (列番データ) => {
      switch (列番データ) {
        //しおかぜメイン
        //8000 ノーマル
        case "2M":
        case "4M":
        case "6M":
        case "14M":
        case "16M":
        case "18M":
        case "26M":
        case "28M":
        case "30M":
        case "1M":
        case "3M":
        case "5M":
        case "13M":
        case "15M":
        case "17M":
        case "25M":
        case "27M":
        case "29M":
          return "https://storage.haruk.in/s8000nr.png";
        //8000 アンパン
        case "10M":
        case "22M":
        case "9M":
        case "21M":
          return "https://n8n.haruk.in/webhook/anpanman-pictures.png?trainNum=" +
            列番データ;

        //8600
        case "8M":
        case "12M":
        case "20M":
        case "24M":
        case "7M":
        case "11M":
        case "19M":
        case "23M":
          return "https://storage.haruk.in/s8600.png";
        
        //いしづちメイン
        //8000 ノーマル

        case "1004M":
        case "1006M":
        case "1014M":
        case "1016M":
        case "1018M":
        case "1026M":
        case "1028M":
        case "1030M":
        case "1001M":
        case "1003M":
        case "1005M":
        case "1013M":
        case "1015M":
        case "1017M":
        case "1025M":
        case "1027M":
        case "1029M":
          return "https://storage.haruk.in/s8000no.png";

        //8000 アンパン
        case "1010M":
        case "1022M":
        case "1009M":
        case "1021M":
          return  "https://n8n.haruk.in/webhook/anpanman-pictures.png?trainNum=" +
            列番データ;
        //8600
        case "1008M":
        case "1012M":
        case "1020M":
        case "1024M":
        case "1007M":
        case "1011M":
        case "1019M":
        case "1023M":
          return "https://storage.haruk.in/s8600_isz.png";

        //MEXP
        //8000
        case "1092M":
          return "https://storage.haruk.in/s8000nr.png";
        //8600
        case "1091M":
          return "https://storage.haruk.in/s8600_isz.png";
        //三桁いしづち
        //8000 アンパン
        case "1041M":
        case "1044M":
          return "https://n8n.haruk.in/webhook/anpanman-pictures.png?trainNum=" +
            列番データ;
        //8600
        case "1043M":
        case "1042M":
        case "1046M":
          return "https://storage.haruk.in/s8600_isz.png";
        //南風 2700ノーマル
        case "34D":
        case "38D":
        case "40D":
        case "42D":
        case "46D":
        case "50D":
        case "52D":
        case "54D":
        case "58D":
        case "31D":
        case "35D":
        case "39D":
        case "41D":
        case "43D":
        case "47D":
        case "51D":
        case "53D":
        case "55D":
          return "https://storage.haruk.in/s2700.png";
        //2700アンパン
        case "32D":
        case "36D":
        case "44D":
        case "48D":
        case "56D":
        case "33D":
        case "37D":
        case "45D":
        case "49D":
        case "57D":
          return "https://n8n.haruk.in/webhook/anpanman-pictures.png?trainNum=" +
            列番データ;
        //うずしお
        //2700
        case "3004D":
        case "3006D":
        case "3010D":
        case "3014D":
        case "3016D":
        case "3022D":
        case "3028D":
        case "3003D":
        case "3007D":
        case "3013D":
        case "3019D":
        case "3025D":
        case "3031D":
          return "https://storage.haruk.in/s2700_uzu.png";
        //2700 二両編成

        case "3008D":
        case "3020D":
        case "3026D":
        case "3001D":
        case "3005D":
        case "3011D":
        case "3017D":
        case "3023D":
        case "3029D":
          return "https://storage.haruk.in/s2700_uzu.png";
        //2600
        case "3002D":
        case "3012D":
        case "3018D":
        case "3024D":
        case "3030D":
        case "3009D":
        case "3015D":
        case "3021D":
        case "3027D":
        case "3033D":
          return "https://storage.haruk.in/s2600.png";
        //マリンライナー
        case "3104M":
        case "3106M":
        case "3108M":
        case "3110M":
        case "3112M":
        case "3114M":
        case "3116M":
        case "3118M":
        case "3120M":
        case "3122M":
        case "3124M":
        case "3126M":
        case "3128M":
        case "3130M":
        case "3132M":
        case "3134M":
        case "3136M":
        case "3138M":
        case "3140M":
        case "3142M":
        case "3144M":
        case "3146M":
        case "3148M":
        case "3150M":
        case "3152M":
        case "3154M":
        case "3156M":
        case "3158M":
        case "3160M":
        case "3162M":
        case "3164M":
        case "3166M":
        case "3168M":
        case "3170M":
        case "3105M":
        case "3107M":
        case "3109M":
        case "3111M":
        case "3113M":
        case "3115M":
        case "3117M":
        case "3119M":
        case "3121M":
        case "3123M":
        case "3125M":
        case "3127M":
        case "3129M":
        case "3131M":
        case "3133M":
        case "3135M":
        case "3137M":
        case "3139M":
        case "3141M":
        case "3143M":
        case "3145M":
        case "3147M":
        case "3149M":
        case "3151M":
        case "3153M":
        case "3155M":
        case "3157M":
        case "3159M":
        case "3161M":
        case "3163M":
        case "3165M":
        case "3167M":
        case "3169M":
        case "3175M":
          return "https://storage.haruk.in/s5001.png";
        case "3102M":
        case "3101M":
        case "3103M":
        case "3171M":
        case "3173M":
          return "https://storage.haruk.in/s5001k.png";

        //サンライズ瀬戸
        case "5032M":
        case "5031M":
        case "8041M": //琴平延長高松迄
        case "8031M": //琴平延長高松以降
        return "https://storage.haruk.in/w285.png";
        //宇和海
        //2000 ノーマル
        case "1052D":
        case "1054D":
        case "1056D":
        case "1060D":
        case "1062D":
        case "1064D":
        case "1068D":
        case "1070D":
        case "1072D":
        case "1076D":
        case "1078D":
        case "1080D":
        case "1082D":
        case "1051D":
        case "1055D":
        case "1057D":
        case "1061D":
        case "1063D":
        case "1065D":
        case "1069D":
        case "1071D":
        case "1073D":
        case "1075D":
        case "1077D":
        case "1079D":
        case "1081D":
          return "https://storage.haruk.in/s2000_uwa.png";
        //2000 アンパン込み
        case "1058D":
        case "1066D":
        case "1074D":
        case "1053D":
        case "1059D":
        case "1067D":
        return "https://n8n.haruk.in/webhook/anpanman-pictures.png?trainNum=" +
          列番データ;
        //しまんと
        case "2002D":
        case "2004D":
        case "2001D":
        case "2003D":
          return "https://storage.haruk.in/s2000_smn.png";
        //あしずり 2000
        case "2074D":
        case "2076D":
        case "2080D":
        case "2082D":
        case "2071D":
        case "2073D":
        case "2079D":
        case "2081D":
          return "https://n8n.haruk.in/webhook/anpanman-pictures.png?trainNum=" +
              列番データ;

        //あしずり 2700
        case "2072D":
        case "2078D":
        case "2084D":
        case "2075D":
        case "2077D":
        case "2083D":
          return "https://storage.haruk.in/s2700_asi.png";
        //剣山
        case "4002D":
        case "4004D":
        case "4006D":
        case "4001D":
        case "4003D":
        case "4005D":
        case "4007D":
          return "https://storage.haruk.in/s185tu.png";

        //よしのがわトロッコ
        case "8452D":
        case "8451D":
          return "https://storage.haruk.in/s185to_ai.png";

        //岡山高松アントロ
        case "8176D":
        case "8179D":
        //岡山琴平アントロ
        case "8277D":
        case "8278D":
          return "https://storage.haruk.in/s32to4.png";

        //千年ものがたり
        case "8021D":
        case "8022D":
          return "https://storage.haruk.in/s185mm1.png";

        //夜明けものがたり
        case "8082D":
        case "8083D":
        case "8073D":
        case "8074D":
          return "https://storage.haruk.in/s185ym1.png";
        //ラマルドボア
        case "9253M":
        case "9256M":
          return "https://storage.haruk.in/w213w.png";

        // 貨物
        case "74":
        case "75":
        case "70":
        case "71":
        case "73":
        case "76":
        case "3070":
        case "3071":
        case "3072":
        case "3073":
        case "3076":
        case "3077":
        case "3078":
        case "3079":
        case "8070":
        case "8071":
        case "8072":
        case "8077":
          return "https://storage.haruk.in/ef210a.png";

        // 伊予灘ものがたり 赤
        case "8091D":
        case "8093D":
          return "https://storage.haruk.in/s185iyor.png";
        // 伊予灘ものがたり 黄
        case "8092D":
        case "8094D":
          return "https://storage.haruk.in/s185iyoy.png";

        // 高徳線、徳島線、牟岐線、鳴門線普通列車系統
        // キハ40・47
        case "4303D":
        case "371D":
        case "316D":
        case "362D":
        case "4376D":
        case "951D":
        case "953D":
        case "955D":
        case "973D":
        case "975D":
        case "977D":
        case "979D":
        case "981D":
        case "950D":
        case "968D":
        case "970D":
        case "972D":
        case "974D":
        case "976D":
        case "980D":
        case "982D":
          return "https://storage.haruk.in/s40.png";
        // 1000形
        case "4311D":
        case "363D":
        case "356D":
        case "4374D":
        case "433D":
        case "4447D":
        case "451D":
        case "450D":
        case "4458D":
        case "474D":
          return "https://storage.haruk.in/s1000.png";
        // 1200形
        case "4301D":
        case "4327D":
        case "4329D":
        case "4343D":
        case "353D":
        case "355D":
        case "367D":
        case "310D":
        case "4326D":
        case "4334D":
        case "4342D":
        case "358D":
        case "364D":
        case "4453D":
        case "4455D":
        case "4457D":
        case "463D":
        case "475D":
        case "477D":
        case "485D":
        case "4430D":
        case "434D":
        case "438D":
        case "4460D":
        case "4464D":
        case "4466D":
        case "478D":
        case "484D":
        case "957D":
        case "4959D":
        case "4963D":
        case "4967D":
        case "4971D":
        case "952D":
        case "4954D":
        case "4958D":
        case "4962D":
        case "4966D":
          return "https://storage.haruk.in/s1200n.png";
        // 半定期臨時列車
        case "9174M":
          return "https://storage.haruk.in/s5001.png";
        case "9395D":
          return "https://storage.haruk.in/s1500.png";

        default: //指定車両でなく、Regexでの指定に移動
          //     // 琴平直通系普通電車
          //   if(new RegExp(/^(1|4|5)2\\d\\dM$/).test(列番データ)){
          //     setStationIcon(e.querySelector("img"),'https://storage.haruk.in/s7200.png',hasProblem);
          //     break;
          //   }
          //   else if(new RegExp(/^(1|4|5)(1|5|6)\\d\\dM$/).test(列番データ)){
          //     setStationIcon(e.querySelector("img"),'https://storage.haruk.in/s7000.png',hasProblem);
          //     break;
          //   }
          //   else if(new RegExp(/^(1|5|6)\\d\\dM$/).test(列番データ)){
          //     setStationIcon(e.querySelector("img"),'https://storage.haruk.in/s7000.png',hasProblem);
          //     break;
          //   }// 高徳線 普通列車系統
          //   else
          if (new RegExp(/^(4|5)3\\d\\dD$/).test(列番データ)) {
            return "https://storage.haruk.in/s1500.png";
          } else if (new RegExp(/^3\\d\\dD$/).test(列番データ)) {
            return "https://storage.haruk.in/s1500.png";
          } // 徳島線 普通列車系統
          else if (new RegExp(/^(4|5)4\\d\\dD$/).test(列番データ)) {
            return "https://storage.haruk.in/s1500.png";
          } else if (new RegExp(/^4\\d\\dD$/).test(列番データ)) {
            return "https://storage.haruk.in/s1500.png";
          } // 鳴門線普通列車系統
          else if (new RegExp(/^(4|5)9(5|6|7|8)\\dD$/).test(列番データ)) {
            return "https://storage.haruk.in/s1500.png";
          } else if (new RegExp(/^9(5|6|7|8)\\dD$/).test(列番データ)) {
            return "https://storage.haruk.in/s1500.png";
          }
          break;
      }
    }
    `;

  const normal_train_name = `
  const nameReplace = (列車名データ,列番データ,行き先情報,hasProblem,isLeft) =>{
    let isWanman = false;
    let trainName = "";
    let trainType = "";
    let trainTypeColor = "black";
    let viaData = "";
    let ToData = "";
    let TrainNumber = 列番データ;
    let isEdit = false;
    let isSeason = false;
    let TrainNumberOverride;
    try{
      const diagram = trainDiagramData2[列番データ] || trainTimeInfo[列番データ];
      if(diagram){
        const diagramData = diagram.split("#");
        ToData = diagramData[diagramData.length - 2].split(",")[0];
      }
    }catch(e){}
    if(列車名データ.split(":")[1]){
      const textBase = 列車名データ.split(":")[1].replace("\\r","");
      
      trainName = textBase;
    }
    if(列車名データ.match("サンポート")){
      const textBase = 列車名データ.split(":")[1].replace("\\r","");
      trainName = textBase;
    }
    
    if(new RegExp(/^4[1-9]\\d\\d[DM]$/).test(列番データ) || new RegExp(/^5[1-7]\\d\\d[DM]$/).test(列番データ) || new RegExp(/^3[2-9]\\d\\d[DM]$/).test(TrainNumber) ){
      flag=true;
      isWanman = true;
    }
    if(new RegExp(/^49[0-4]\\dD$/).test(列番データ) || new RegExp(/^9[0-4]\\dD$/).test(列番データ)){
      viaData = "(海経由)";
    }
    if(new RegExp(/^46\\d\\dD$/).test(列番データ) || new RegExp(/^6\\d\\dD$/).test(列番データ)){
      viaData = "(内子経由)";
    }
    if(列番データ.indexOf("H") != -1){
      trainName = "試運転";
    }
    else if(列番データ.indexOf("R") != -1){
      trainName = "回送";
    }
    else if(列番データ.indexOf("E") != -1){
      trainName = "回送";
    }
    else if(列番データ.indexOf("A") != -1){
      trainName = "回送";
    }
    else if(列番データ.indexOf("B") != -1){
      trainName = "回送";
    }
    else if(列番データ.indexOf("S") != -1){
      trainName = "臨時列車";
    }

    const getThrew = num =>{
    
      switch(num){
      //牟岐線直通列車情報
      //徳島線発牟岐線行き
      case "468D":
      case "478D":
      case "484D":
        viaData = "牟岐線直通";
        ToData = "牟岐";
        break;
      case "4430D":
      case "4472D":
        viaData = "牟岐線直通";
        isWanman = true;
        ToData = "牟岐";
        break;
      case "434D":
      case "474D":
      case "476D":
      case "480D":
        viaData = "牟岐線直通";
        ToData = "阿南";
        break;
      case "4452D":
      case "4466D":
      case "4470D":
        viaData = "牟岐線直通";
        isWanman = true;
        ToData = "阿南";
        break;
      case "4456D":
        viaData = "牟岐線直通";
        isWanman = true;
        ToData = "阿波海南"
        break;  
      //鳴門線発牟岐線行き
      case "951D":
        viaData = "牟岐線直通";
        ToData = "桑野";
        break;

      //牟岐線発高徳線行き
      case "358D":
        viaData = "高徳線直通";
        break;
      case "4314D":
      case "4326D":
      case "4334D":
      case "4342D":
      case "4350D":
      case "4368D":
        viaData = "高徳線直通";
        isWanman = true;
        break;

      //牟岐線発徳島線行き
      case "451D":
      case "475D":
        viaData = "徳島線直通";
        break;
      case "4447D":
      case "4455D":
      case "5467D":
      case "5471D":
      case "5479D":
        viaData = "徳島線直通";
        isWanman = true;
        break;
      //牟岐線発鳴門線行き
      
      case "952D":
        viaData = "鳴門線直通";
        break;
      case "4954D":
      case "4978D":
        viaData = "鳴門線直通";
        isWanman = true;
        break;

      //安芸行と併結列車を個別に表示、それ以外をdefaultで下りなら既定の行き先を、上りなら奈半利行を設定
      case "5814D":
      case "5816D":
        viaData = "ごめん・なはり線[快速]";
        ToData = "奈半利";
        break;
      case "5812D":
        viaData = "ごめん・なはり線[快速]";
        ToData = "安芸";
        break;
      case "5874D":
      case "5882D":
        viaData = "ごめん・なはり線[各停]";
        ToData = "安芸";
        break;
      case "248D":
      case "250D":
        viaData = "ごめん・なはり線[快速]";
        ToData = "(後免にて解結)\\n土佐山田/奈半利";
        break;
      default:
        if(new RegExp(/^58[1-3][1,3,5,7,9][DM]$/).test(列番データ)){
          viaData = "ごめん・なはり線[快速]";
          break;
        }
        else if(new RegExp(/^58[4-9][1,3,5,7,9][DM]$/).test(列番データ)){
          viaData = "ごめん・なはり線[各停]";
          break;
        }
        else if(new RegExp(/^58[3-4][0,2,4,6,8][DM]$/).test(列番データ)){
          viaData = "ごめん・なはり線[快速]";
          ToData = "奈半利";
          break;
        }
        else if(new RegExp(/^58[5-9][0,2,4,6,8][DM]$/).test(列番データ)){
          viaData = "ごめん・なはり線[各停]";
          ToData = "奈半利";
          break;
        }
      }
    }
    getThrew(列番データ);
    if(trainDataList.find(e => e.id === 列番データ) !== undefined){
      const data = trainDataList.find(e => e.id === 列番データ);
      //{id,trainName,viaData,ToData,TrainNumber,TrainNumberOverride,type,infoUrl,trainNumDistance,info,infogram,isEdit}
      
      switch(data.type){
        case "Normal":
          trainTypeColor = "black";
          isWanman = false;
          trainType = "普通";
          break;
        case "OneMan":
          trainTypeColor = "black";
          isWanman = true;
          trainType = "普通";
          break;
        case "Rapid":
          trainTypeColor = "rgba(0, 140, 255, 1)";
          isWanman = false;
          trainType = "快速";
          break;
        case "OneManRapid":
          trainTypeColor = "rgba(0, 140, 255, 1)";
          isWanman = true;
          trainType = "快速";
          break;
        case "LTDEXP":
          trainTypeColor = "red";
          isWanman = false;
          trainType = "特急";
          break;
        case "NightLTDEXP":
          trainTypeColor = "#d300b0ff";
          isWanman = false;
          trainType = "寝台特急";
          break;
        case "SPCL":
        case "SPCL_Normal":
          trainTypeColor = "#008d07ff";
          isWanman = false;
          trainType = "臨時";
          break;
        case "SPCL_Rapid":
          trainTypeColor = "rgba(0, 81, 255, 1)";
          isWanman = false;
          trainType = "臨時快速";
          break;
        case "SPCL_EXP":
          trainTypeColor = "#a52e2eff";
          isWanman = false;
          trainType = "臨時特急";
          break;
        case "Party":
          trainTypeColor = "#ff7300ff";
          isWanman = false;
          trainType = "団体臨時";
          break;
        case "Freight":
          trainTypeColor = "#00869ecc";
          isWanman = false;
          trainType = "貨物";
          break;
        case "Forwarding":
          trainTypeColor = "#727272cc";
          isWanman = false;
          trainType = "回送";
          break;
        case "FreightForwarding":
          trainTypeColor = "#727272cc";
          isWanman = false;
          trainType =  "単機回送";
          break;
        default:
          break;
      }
      isEdit = data.isEdit;
      isSeason = data.isSeason;
      if(data.trainName != ""){
        trainName = data.trainName;
        if(data.trainNumDistance != null){
          trainName += parseInt(列番データ.replace("M", "").replace("D", "")) - data.trainNumDistance+"号";
        }
      }
      if(data.viaData != ""){
        viaData = data.viaData;
      }
      if(data.ToData != ""){
        ToData = data.ToData;
      }
      if(data.TrainNumberOverride){
        TrainNumberOverride = data.TrainNumberOverride;
      }
    }
    //列番付与
    const returnText1 = (isWanman ? "ワンマン " : "") + trainName + viaData;
    行き先情報.innerText = "";
    ${uiSetting === "tokyo" ? `
      let stationIDs = [];
      let stationLines = [];
      Object.keys(stationList).forEach((key) => {
        const data = stationList[key].find(e => e.Station_JP === ToData )?.StationNumber;
        if(data){
          stationIDs.push(data);
          stationLines.push(key);
        }
      });
      let getColors = [];
      if(stationLines.length === 0){
        getColors = ["rgba(97, 96, 96, 0.81)"];
      }else{
        getColors = stationLines.map(e => GetLineBarColor(e));
      }
      let yosan2Color = undefined;
      switch(viaData){
        case "(内子経由)":
          yosan2Color = "#F5AC13";
          break;
        case "(海経由)":
          yosan2Color = "#9AA7D7";
          break;
        case "牟岐線直通":
          yosan2Color = "#00b8bb";
          break;
        case "徳島線直通":
          yosan2Color = "#2d506e";
          break;
        case "高徳線直通":
          yosan2Color = "#87CA3B";
          break;
        case "鳴門線直通":
          yosan2Color = "#881F61";
          break;
        case "予土線":
          yosan2Color = "#008a5a";
          break;
        default:
          break;
      }

      const gradient = getColors.length > 1 ? "linear-gradient(130deg, " + getColors[0] + " 0%, "+ getColors[0]+"50%, "+ getColors[1]+"50%, " + getColors[1] + " 100%)" : getColors[0];

      行き先情報.insertAdjacentHTML('beforebegin', "<div style='width:100%;display:flex;flex:1;flex-direction:"+(isLeft ? "column-reverse" : "column") + ";'>" + ( isEdit ? "<div style='position:absolute;"+ (isLeft ? "right" : "left") + ":0;"+ (isLeft ? "bottom" : "top") + ":0;background-color:#00b8bb;border-radius:15px;padding:0px;padding-left:4px;padding-right:4px;'><i class='fa-solid fa-user-group fa-sm' style='color:white;width:100%;height:100%;'></i></div>" : isSeason ? "<div style='position:absolute;"+ (isLeft ? "right" : "left") + ":0;"+ (isLeft ? "bottom" : "top") + ":0;background-color:#00b8bb;border-radius:15px;padding:0px;padding-left:4px;padding-right:4px;'><i class='fa-solid fa-calendar fa-sm' style='color:white;width:100%;height:100%;'></i></div>" : "") + "<p style='font-size:6px;padding:0;color:black;text-align:center;'>" + (TrainNumberOverride ? TrainNumberOverride : TrainNumber) + "</p><div style='flex:1;'></div><p style='font-size:8px;font-weight:bold;padding:0;color: black;text-align:center;'>" + (isWanman ? "ワンマン " : "") + "</p><p style='font-size:6px;font-weight:bold;padding:0;color: black;text-align:center;border-style:solid;border-width: "+(!!yosan2Color ? "2px" : "0px")+";border-color:" + yosan2Color + "'>" + viaData + "</p><p style='font-size:8px;font-weight:bold;padding:0;color: black;text-align:center;'>" + trainName + "</p><div style='width:100%;background:" + gradient + ";'><p style='font-size:10px;font-weight:bold;padding:0;margin:0;color:white;align-items:center;align-content:center;text-align:center;text-shadow:1px 1px 0px #00000030, -1px -1px 0px #00000030,-1px 1px 0px #00000030,  1px -1px 0px #00000030,1px 0px 0px #00000030, -1px  0px 0px #00000030,0px 1px 0px #00000030,  0px -1px 0px #00000030;'>" + (ToData ? ToData + "行" : ToData) + "</p></div><div style='width:100%;background:" + trainTypeColor + ";border-radius:"+(isLeft ? "4px 4px 0 0" : "0 0 4px 4px")+";'><p style='font-size:10px;font-weight:bold;font-style:italic;padding:0;color: white;text-align:center;'>" + trainType + "</p></div><p style='font-size:8px;font-weight:bold;padding:0;text-align:center;color: "+(hasProblem ? "red":"black")+";'>" + (hasProblem ? "‼️停止中‼️" : "") + "</p></div>");
`: `
      行き先情報.insertAdjacentHTML('beforebegin', "<p style='font-size:10px;font-weight:bold;padding:0;color: black;'>" + returnText1 + "</p>");
      行き先情報.insertAdjacentHTML('beforebegin', "<div style='display:inline-flex;flex-direction:row;'><p style='font-size:10px;font-weight: bold;padding:0;color:black;'>" + (ToData ? ToData + "行 " : ToData) + "</p><p style='font-size:10px;padding:0;color:black;'>" + (TrainNumberOverride ? TrainNumberOverride : TrainNumber) + "</p></div>");
      行き先情報.insertAdjacentHTML('beforebegin', "<p style='font-size:10px;font-weight:bold;padding:0;color: "+(hasProblem ? "red":"black")+";'>" + (hasProblem ? "‼️停止中‼️" : "") + "</p>");
      `}
      }
  `;

  const textInsert =
    `


const setNewTrainItem = (element,hasProblem,type)=>{
  var 列番データ = element.getAttribute('offclick').split('"')[1];
  if(trainDataList.find(e => e.id === 列番データ) !== undefined){
    const data = trainDataList.find(e => e.id === 列番データ);
    switch (data.type) {
      case "Normal":
        element.style.borderColor = "black";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "OneMan":
        element.style.borderColor = "black";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "Rapid":
        element.style.borderColor = "rgba(0, 140, 255, 1)";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "OneManRapid":
        element.style.borderColor = "rgba(0, 140, 255, 1)";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "LTDEXP":
        element.style.borderColor = "red";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "NightLTDEXP":
        element.style.borderColor = "#d300b0ff";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "SPCL":
      case "SPCL_Normal":
        element.style.borderColor = "#008d07ff";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "SPCL_Rapid":
        element.style.borderColor = "#0051ffff";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "SPCL_EXP":
        element.style.borderColor = "#a52e2eff";
        element.style.backgroundColor = '#ffffffcc';
        break;
      case "Party":
        element.style.borderColor = "#ff7300ff";
        element.style.backgroundColor = '#ffd0a9ff';
        break;
      case "Freight":
        element.style.borderColor = "#00869ecc";
        element.style.backgroundColor = '#c7c7c7cc';
        break;
      case "Forwarding":
        element.style.borderColor = "#727272cc";
        element.style.backgroundColor = '#c7c7c7cc';
        break;
      case "FreightForwarding":
        element.style.borderColor = "#727272cc";
        element.style.backgroundColor = '#c7c7c7cc';
        break;
      default:
        element.style.borderColor = 'black';
        element.style.backgroundColor = '#ffffffcc';
        break;
    }
  }else{
    if(element.getAttribute('offclick').includes("express")){
      element.style.borderColor = '#ff0000ff';
    }else if(element.getAttribute('offclick').includes("rapid")){
      element.style.borderColor = '#008cffff';
    }else{
      element.style.borderColor = 'black';
    }
  }
  element.style.borderWidth = '2px';
  element.style.borderStyle = 'solid';
  element.style.borderRadius = '10%';
  if(hasProblem){
    element.style.boxShadow = '0 0 10px rgba(255, 0, 0, 0.9)';
  }else{
    element.style.boxShadow = '0 0 4px rgba(0, 0, 0, 0.2)';
  }
  element.style.margin = '2px';
  element.style.display = 'flex';
  element.style.alignItems = 'center';
  element.style.justifyContent = 'center';
  element.style.width = '4.5em';
  element.style.minHeight = '80px';
  element.style.height = '100%';
  element.getElementsByTagName("img")[0].style.float = 'unset';
  element.style.webkitTapHighlightColor = 'rgba(0, 0, 0, 0)';
  element.style.transition = 'transform 0.1s ease-in-out';
  element.addEventListener('touchstart', () => element.style.transform = 'scale(0.8)');
  element.addEventListener('touchend', () => element.style.transform = 'scale(1)');
  if(element.getAttribute("style").includes("left")){
  // borderを使って五角形を生成 下り
    element.style.borderRadius = '30px 30px 120px 120px';
    element.style.flexDirection = 'column-reverse';
  }
  else if(element.getAttribute("style").includes("right")){
  // borderを使って五角形を生成 上り
    element.style.borderRadius = '120px 120px 30px 30px';
    element.style.flexDirection = 'column';
  }

}
    //列番付与
const setStrings = () =>{
  try {
    const elements = document.querySelectorAll('#disp > div > div > div[onclick]');
    const setNewTrainItemUI = ()=>{
      const aaa = (x2,pos) => {
        x2.style.display = 'flex';
        x2.style.flexDirection = 'row';
        if(pos == "right"){
          x2.style.alignItems = 'flex-start';
          x2.style.justifyContent = 'flex-start';
        }else if(pos == "left"){
          x2.style.alignItems = 'flex-end';
          x2.style.justifyContent = 'flex-end';
        }
        x2.style.flexWrap = 'wrap';
        x2.style.width = '100%';
        x2.style.height = "100%";
        
      }
      const aaa2 = (x2) => {
        x2.style.display = 'flex';
        x2.style.flexDirection = 'row';
        x2.style.alignItems = 'center';
        x2.style.justifyContent = 'center';
        x2.style.flexWrap = 'wrap';
        x2.style.width = '100%';
        x2.style.height = "unset";
        const x3 = x2.querySelectorAll(":scope > div");
        x3.forEach(i=>{
          i.style.position = "unset";
          i.style.display = "flex";
          i.style.flexDirection = "column";
          i.style.alignItems = "center";
          i.style.justifyContent = "center";
          i.style.flex = "1";
          i.style.backgroundColor = "#00000000";
          i.querySelectorAll(":scope > *").forEach(j=>{
            j.style.display = "flex";
            j.style.flex = "1";
            j.style.textAlign = "center";
            j.style.margin = "5px";
            j.style.padding = "5px";
          });
        });
      }
      const layoutBase = (e)=>{
        e.style.display = 'flex';
        e.style.height = "unset";
        e.style.flexDirection = 'row';
        e.style.justifyContent = 'center';
      }
      const elementBaseBase = document.querySelectorAll('[id^="stationBlock"]');
      const elementNotBase = document.querySelectorAll('#disp > [id*="～"]');
      elementNotBase.forEach(e=>{
        layoutBase(e);
        const x = e.querySelectorAll(':scope > [id^="Up"], :scope > [id^="Id"], :scope > [id^="Down"]');//配下のdiv要素を選択
        aaa(x[0],"left");
        aaa2(x[1]);
        aaa(x[2],"right");
        const upTrainCrossBarElement = e.querySelector(':scope > [id="upTrainCrossBar"]');
        if (upTrainCrossBarElement) {
          upTrainCrossBarElement.style.left = '0px';
        }
      });
      elementBaseBase.forEach(e=>{ //それぞれの駅ブロック横一列
        layoutBase(e);
        const x = e.querySelectorAll(':scope > div');//配下のdiv要素を選択
        //x[0] 登りブロック x[2] 下りブロック x[1] 駅ブロック
        aaa(x[0],"left");
        aaa2(x[1]);
        aaa(x[2],"right");
      });
    }
    
    ${uiSetting === "tokyo" ? `setNewTrainItemUI();`: ``}
    for (let element of elements) {
      if(element.getAttribute('offclick')){ continue; }
      element.setAttribute('offclick',element.getAttribute('onclick'))
      
      var 行き先情報 = element.getElementsByTagName("p")[0];
      ${uiSetting === "tokyo" ? `
      element.querySelector("img").insertAdjacentHTML('beforebegin',"<div style='flex:1;'></div>");
      element.querySelector("img").insertAdjacentHTML('afterend',"<div style='flex:1;'></div>");
      element.querySelector("img").style.padding = '5px';
      element.style.position = 'relative';
      if(element.getElementsByTagName("p")[1] != undefined){
        element.getElementsByTagName("p")[1].innerText = element.getElementsByTagName("p")[1].innerText.replace("(","").replace(")","");
        element.getElementsByTagName("p")[1].style.position = 'absolute';
        element.getElementsByTagName("p")[1].style.backgroundColor = 'red';
        element.getElementsByTagName("p")[1].style.color = 'white';
        element.getElementsByTagName("p")[1].style.fontSize = '10px';
        element.getElementsByTagName("p")[1].style.fontWeight = 'bold';
        element.getElementsByTagName("p")[1].style.padding = '2px';
        element.getElementsByTagName("p")[1].style.textAlign = 'center';
        element.getElementsByTagName("p")[1].style.borderRadius = '10px';
        if(element.getAttribute("style").includes("left")){
          element.getElementsByTagName("p")[1].style.bottom = '0px';
          element.getElementsByTagName("p")[1].style.left = '0px';
        }
        else if(element.getAttribute("style").includes("right")){
          element.getElementsByTagName("p")[1].style.right = '0px';
          element.getElementsByTagName("p")[1].style.top = '0px';
        }
      }`: ``}
      const isLeft = element.getAttribute("style").includes("left");
      var 列番データ = element.getAttribute('offclick').split('"')[1];
      var 列車名データ = element.getAttribute('offclick').split('"')[3];
      const trainData = trainPositionDatas.filter(e=>!(e.Pos && e.Pos.includes("予告窓"))).find(e => e.TrainNum == 列番データ);
      const hasProblem = probremsData.find((e)=>{
        return e.TrainNum == trainData.TrainNum && e.Pos == trainData.Pos;
      });
      var flag=false;
      var TrainType = undefined;
      setTrainMenuDialog(element)
     
      ${iconSetting == "true" ? `
        if(trainDataList.find(e => e.id === 列番データ) !== undefined){
          const trainIconUrl = trainDataList.find(e => e.id === 列番データ).img;
          if(!!trainIconUrl){
            setStationIcon(element.querySelector("img"),trainIconUrl,hasProblem);
          }
        }
        else{
          const trainIconUrl = setTrainIcon(列番データ);
          if(!!trainIconUrl){
            setStationIcon(element.querySelector("img"),trainIconUrl,hasProblem);
          }
        }
      ` : ""}
      nameReplace(列車名データ,列番データ,行き先情報,hasProblem,isLeft); 
      ${uiSetting === "tokyo" ? `setNewTrainItem(element,hasProblem);`: ``}
    }
    try{
      for(let d of document.getElementById('disp').childNodes){
        switch(d.id){
          case 'pMENU_2':
          case 'pMENU_2_En':
          case 'pMENU_3':
          case 'pMENU_3_En':
          case 'pMENU_k':
          case 'pMENU_k_En':
            continue;
          default:
            break;
        }

        d.style.width = '100vw';
        for(let f of d.childNodes){
          try{
            if(f.style.alignItems || f.style.textAlign){
              f.style.width = '38vw';
            }
            else{
              if(f.id == 'upTrainCrossBar'){
                f.style.width = '38vw';
              }
              else if(f.id == 'dwTrainCrossBar'){
                f.style.left = '62vw';
                f.style.width = '38vw';

              }
              else {
                f.style.width = '0vw';
              }
            }
            if(f.style.textAlign == 'center'){
              f.style.width = '24vw';
              f.style.display = 'flex';
              f.childNodes.forEach(i =>{
                i.style.width = 'unset';
                i.style.left = 'unset';
                i.style.top = 'unset';
                i.style.position = 'unset';
                i.style.flex = '1';
                i.style.margin = '5px'

                if(i.style.backgroundColor != 'rgb(247, 247, 247)'){
                  i.childNodes.forEach(m=> m.style.width = '20vw')
                }
              })
            }
            
          }catch(e){}
        }
      }



      document.querySelector('#pMENU_2').style.borderStyle='solid';
      document.querySelector('#pMENU_2').style.borderColor='#00d3e8';
      document.querySelector('#pMENU_2').style.borderWidth='2px';
      document.querySelector('#pMENU_2').style.borderRadius='10%';
      document.querySelector('#pMENU_3').style.borderStyle='solid';
      document.querySelector('#pMENU_3').style.borderColor='#00d3e8';
      document.querySelector('#pMENU_3').style.borderWidth='2px';
      document.querySelector('#pMENU_3').style.borderRadius='10%';
      document.querySelectorAll('#pMENU_2 div').forEach((d)=>d.style.padding = '10px'); 
      document.querySelectorAll('#pMENU_3 div').forEach((d)=>d.style.padding = '10px'); 
      document.querySelectorAll('#topHeader div').forEach((d)=>d.style.width = '100vw'); 
      document.querySelectorAll('#disp div')[0].style.width = '100vw'; 
      document.getElementById('disp').style.width = '100vw';
      document.getElementById('disp').style.overflowX = 'hidden';

    }catch(e){
      alert("本家サーバーからのデータ取得に失敗しました。");
      window.ReactNativeWebView.postMessage(JSON.stringify({type:"LoadError"}));
    }
  } catch (e) {}
}

const textInsert = new MutationObserver( (mutations) =>{
  setStrings();
  const currentLines = document.querySelector('#topHeader div').innerText;
  window.ReactNativeWebView.postMessage(JSON.stringify({type:"currentLines",currentLines}));
});

// 監視を開始
textInsert.observe(document.getElementById('disp'), {
  attributes: true, // 属性変化の監視
  //attributeOldValue: true, // 変化前の属性値を matation.oldValue に格納する
  //characterData: true, // テキストノードの変化を監視
  //characterDataOldValue: true, // 変化前のテキストを matation.oldValue に格納する
  childList: true, // 子ノードの変化を監視
  //subtree: true // 子孫ノードも監視対象に含める
});
`;

// 列車メニュー表示の起動用スクリプト
  const makeTrainView = `
    const makeTrainView = new MutationObserver( (mutations) => {
      for(let d of modal_content.getElementsByTagName("button") ){
        const data = d.onclick.toString().split("\\"")[1];
        d.onclick = () => window.ReactNativeWebView.postMessage(data)
      }
    });
    // 監視を開始
    makeTrainView.observe(document.getElementById('modal_content'), {
      //attributes: true, // 属性変化の監視
      //attributeOldValue: true, // 変化前の属性値を matation.oldValue に格納する
      //characterData: true, // テキストノードの変化を監視
      //characterDataOldValue: true, // 変化前のテキストを matation.oldValue に格納する
      childList: true, // 子ノードの変化を監視
      //subtree: true // 子孫ノードも監視対象に含める
    });
  `;
  const makeTrainMenu =
    trainMenu == "true"
      ? `
      // これの中身抽出ShowTrainTimeInfo("1228M","normal")
      // ShowTrainTimeInfo("142M","rapid:サンポート南風リレー")
      function setTrainMenuDialog(d){
        try{
          const offclick = d.getAttribute('offclick');
          if(!offclick) return;
          const s =  offclick.replace('ShowTrainTimeInfo(','').replaceAll('"','').replace(')','').split(',') ;
          const returnData = {type:"ShowTrainTimeInfo",trainNum:s[0],limited:s[1]};
          d.onclick = ()=>window.ReactNativeWebView.postMessage(JSON.stringify(returnData));
        }catch(e){
        }
        
      }
        function ShowTrainTimeInfo(trainNum,limited){
          window.ReactNativeWebView.postMessage(JSON.stringify({type:"ShowTrainTimeInfo",trainNum,limited}));
        };
      `
      : `function setTrainMenuDialog(d){}`;

  const makeStationMenu =
    stationMenu == "true"
      ? `
      //駅メニューダイアログの配置

const setStationMenuDialog = new MutationObserver( (mutations) => {
  const data =[];
  document.querySelectorAll('#disp div div').forEach(d=>d.id.indexOf("st")!= -1 && data.push(d));

  for(let d of data ){
    if(!d.offclick){
      d.offclick = d.onclick.toString();
    }
    d.onclick = () =>{ 
      const s = d.offclick.replace('(event)','').replaceAll("'", "").split('(')[1].split(')')[0].split(',');
      // これの中身抽出 PopUpMenu(event,'2','端岡','http://www.jr-shikoku.co.jp/01_trainbus/jikoku/pdf/hashioka.pdf','https://www.google.co.jp/maps/place/34.305027,133.967643','','1')
      window.ReactNativeWebView.postMessage(JSON.stringify({type:"PopUpMenu",event:s[0],id:s[1],name:s[2],pdf:s[3],map:s[4],url:s[5],chk:s[6]}));
    }
  }
  const data2 =[];
  document.querySelectorAll('#disp > div > div > div > div > font > div').forEach(d=>{
    if(!!d.onclick) data2.push(d);
  })

  for(let d of data2 ){
    if(!d.offclick){
      d.offclick = d.onclick.toString();
    }
    const stationID = d.childNodes[0].innerText;
    const PDFAddress = d.offclick.split("'")[1];
    const Name = d.childNodes[2].innerText;
    //alert(PDFAddress);
    d.onclick = () =>{ 
      //const s = d.offclick.replace('(event)','').replaceAll("'", "").split('(')[1].split(')')[0].split(',');
      // これの中身抽出 PopUpMenu(event,'2','端岡','http://www.jr-shikoku.co.jp/01_trainbus/jikoku/pdf/hashioka.pdf','https://www.google.co.jp/maps/place/34.305027,133.967643','','1')
      window.ReactNativeWebView.postMessage(JSON.stringify({type:"PopUpMenu",id:stationID,name:Name,pdf:PDFAddress}));
    }
  }
});

// 監視を開始
setStationMenuDialog.observe(document.querySelector('#disp'), {
  attributes: true, // 属性変化の監視
  //attributeOldValue: true, // 変化前の属性値を matation.oldValue に格納する
  //characterData: true, // テキストノードの変化を監視
  //characterDataOldValue: true, // 変化前のテキストを matation.oldValue に格納する
  childList: true, // 子ノードの変化を監視
  //subtree: true // 子孫ノードも監視対象に含める
});
`
      : ``;
  return (
    bootData +
    topMenu +
    trainIcon +
    normal_train_name +
    makeTrainView +
    makeTrainMenu +
    textInsert +
    makeStationMenu
  );
};
