

function Game() {
  const EXPRESSES = [
    'img/doctor_od.png',
    'img/doctor_od2.png',
    'img/doctor_od3.png',
    'img/doctor_od4.png',
    'img/doctor_od5.png',
    'img/doctor_od6.png',
    'img/doctor_od7.png'
  ];

  /////////* 横向き強制処理 */////////
  var isReverse = false;  //正面が逆かどうかのフラグを用意しておく

  if (navigator.userAgent.indexOf('Android') > 0) {
    //Androidなら正面設定を確認
    var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
    if (orientation.type === "portrait-secondary" || orientation.type === "landscape-primary") {
      isReverse = true;
    }
  }

  function orientCheck() {

    if (isReverse) {
      //正面が逆の場合
      var orientation = window.orientation;
      if (orientation === 0) {
        /*  縦画面時の処理  */
        return 0;
      } else {
        /*  横画面時の処理  */
        return 1;
      }
    } else {
      var orientation = window.orientation;
      if (orientation === 0) {
        /*  縦画面時の処理  */
        return 0;
      } else {
        /*  横画面時の処理  */
        return 1;
      }
    }
  }

  function getWindowRatio(flag) {



    if (flag != 1) flag = 0;
    if (orientCheck() ^ flag) {
      return window.innerHeight / window.innerWidth;
    }
    return window.innerWidth / window.innerHeight;

  }

  function aspectRatioCheck(flag) {

    var result = UAParser();
    if (result.device.type == "tablet") {
      return 1;
    }

    return 0;
    /*
    if (getWindowRatio(flag) < 1.7)
      return 1;
    return 0;*/

  }


  $(window).on("orientationchange", function () {
    setIsLandscpae(orientCheck());
    setIsSquareDevice(aspectRatioCheck(1));
  });

  // 初期化
  let cookies = document.cookie;
  let cookiesArray = cookies.split('; ');
  let _affinity = 0;
  let _isSound = 0; // 新規ユーザorリピータの検知にも使う
  for (var c of cookiesArray) {
    var cArray = c.split('=');
    // 取り出したいkeyと合致したら分岐
    if (cArray[0] == 'affinity') {
      // 好感度
      _affinity = parseInt(decodeURIComponent(
        cArray[1]
      ))
    }
    else if (cArray[0] == 'isSound') {
      // 音を出すかどうか
      _isSound = parseInt(decodeURIComponent(
        cArray[1]
      ))
    }
  }
  const [affinity, setAffinity] = React.useState(_affinity);
  const [isSound, setIsSound] = React.useState(_isSound)
  const [phase, setPhase] = React.useState(0); // 会話段階
  const [isClickThinkingMessage, setIsClickThinkingMessage] = React.useState(true);
  const [isAskingMessage, setIsAskingMessage] = React.useState(false);
  const [isClickAskingMessage, setIsClickAskingMessage] = React.useState(true);
  const [isSpeakingMessage, setIsSpeakingMessage] = React.useState(false);
  const [isClickSpeakingMessage, setIsClickSpeakingMessage] = React.useState(true);
  const [isLovingMessage, setIsLovingMessage] = React.useState(false);
  const [isAskMurabanku, setIsAskMurabanku] = React.useState(false);
  const [isMenuToggle, setIsMenuToggle] = React.useState(false);
  const [isLandscape, setIsLandscpae] = React.useState(orientCheck());
  const [isSquareDevice, setIsSquareDevice] = React.useState(aspectRatioCheck(1));




  // 処理

  document.getElementById("bgm").play();



  function onClickedHamburger() {
    if (!isMenuToggle) {
      setIsMenuToggle(true);
    } else {
      setIsMenuToggle(false);
    };
  }

  function increaseAffinity() {
    document.cookie = "affinity=" + encodeURIComponent(affinity + 1);
    setAffinity(affinity + 1);
    // console.log(document.cookie);
  };


  function onClikedDoor(kind) {

    switch (kind) {
      case 'soundOn':
        document.cookie = "isSound=" + encodeURIComponent(1) + "; max-age=300";
        document.getElementById("se-door").currentTime = 0;
        document.getElementById("se-door").play();
        setTimeout(function () { //Start the timer
          setIsSound(1);
        }.bind(this), 1000);
        break;
      case 'soundOff':

        document.cookie = "isSound=" + encodeURIComponent(-1);
        setIsSound(-1);
        break;
      case 'exit':
        document.getElementById("se-exit").currentTime = 0;
        document.getElementById("se-exit").play();
        window.location.href = 'https://www.youtube.com/watch?v=9otoX9Q3YJg&t=233s';
        break;
    }

  }

  function onClikedSpeechBubble(kind) {
    // console.log("kind=" + kind);
    switch (kind) {
      case 'thinking':
        if (isClickThinkingMessage) {
          setIsClickThinkingMessage(false);
          setTimeout(function () { //Start the timer
            setPhase(phase + 1);
            setIsAskingMessage(true);
          }.bind(this), 1000);
        }
        break;

      case 'asking':
        if (isClickAskingMessage) {
          setIsClickAskingMessage(false);
          setTimeout(function () { //Start the timer
            setPhase(phase + 1);
            setIsSpeakingMessage(true);
          }.bind(this), 1000);
        }
        break;

      case 'speaking':

        if (isClickSpeakingMessage) {
          increaseAffinity();
        }
        setIsClickSpeakingMessage(false);
        setIsLovingMessage(true);

        break;
    }
  }


  function renderSpeechBubble(id, kind, clickable, handleClick) {
    return (
      <SpeechBubble
        id={id}
        kind={kind}
        clickable={clickable}
        visible='true'
        handleClick={handleClick}
        message={message1} />
    )
  }


  function omuratoha() {

    document.getElementById("se-murabanku").currentTime = 0;
    document.getElementById("se-murabanku").play();

    setIsAskMurabanku(true);
    setTimeout(function () { //Start the timer
      setIsAskMurabanku(false);
    }.bind(this), 1000);
  }



  /////////* 出力 */////////

  // メニューバーに表示される内容
  let active = (isMenuToggle) ? "active" : "";
  let menu = <div className='menu'>
    <a href="https://gregarious-honeydew-f1e.notion.site/MURA-LIVE-10-12-49837a48340f4c7389af12c0cee4fbfc"><img id="onstage" className="button" src="img/button1.png"></img></a>
    <a href="./musics"><img id="music" className="button" src="img/button2.png"></img></a>
    <a href="javascript:void(0)" onClick={() => { omuratoha(); }}><img id="omuratoha" className="button" src="img/button3.png"></img></a>
    <a href="./himotoki"><img id="himotoki" className="button" src="img/button4.png"></img></a>
    <a href="./sns"><img id="sns" className="button" src="img/button5.png"></img></a>
    <a href="./special"><img id="special" className="button" src="img/button6.png"></img></a>
    <img id="lookthis" src="img/LookThis!.png"></img>
  </div>;


  let thinkBubble = renderSpeechBubble(
    0, 'thinking', isClickThinkingMessage, () => onClikedSpeechBubble('thinking')
  );

  let askBubble = "";
  if (isAskingMessage) {
    askBubble = <SpeechBubble
      kind='asking'
      clickable={isClickAskingMessage}
      handleClick={() => onClikedSpeechBubble('asking')}
      message={message2} />;

  };
  let speakBubble = "";
  if (isSpeakingMessage) {
    speakBubble = <SpeechBubble
      kind='speaking'
      clickable={isClickSpeakingMessage}
      handleClick={() => onClikedSpeechBubble('speaking')}
      message={message3} />;
  }
  let raiseAffinity = "";
  if (isLovingMessage) {
    raiseAffinity = <div className='love'>❤</div>
  }


  let appeerMurabanku = "";
  if (isAskMurabanku) {
    appeerMurabanku = <div className='murabanku'><img src="img/murabanku.png"></img></div>
  }

  let readAudio = "";




  let bgFirstScreen = "";

  let bgPlaceBacker = "";
  let bgPlaceBack = "";
  let bgPlaceOD = "";
  let bgPlaceFront = "";


  if (navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/i)) {
    // スマホ・タブレット（iOS・Android）の場合の処理を記述

  } else {
    // PCの場合の処理を記述
  }

  bgFirstScreen = <img id='bg-first-screen' src="img/background_pc_od_room.png"></img>;
  bgPlaceBacker = <img id='bg-place1' src="img/background_pc_od_room.png"></img>;
  bgPlaceBack = <img id='bg-place2' src="img/background_pc_od_room2.png"></img>;
  bgPlaceOD = <img id='bg-place3' src="img/background_pc_od_room3.png"></img>;
  bgPlaceFront = <div id='bg-place-upper-wrapper'><img id="bg-place-upper" src='img/background_pc_od_room4.png'></img><img id="bg-place-upper2" src='img/background_pc_od_room5.png'></img></div>;


  var result = "";
  if (!isLandscape) {
    result = <div>
      <br></br><br></br>
      <div className="description">スマホを横向きにしてください。<br></br>スマホの縦画面が禁止されています。<br></br>(インスタからお越しの方は、ブラウザで刮目ください)</div>
      <span id="icon-rotate-phone"></span>
    </div >;

  } else if (isSquareDevice) {
    result = <div>
      <br></br><br></br>
      <div className="description">大変恐縮ですが、PCかスマートフォンで閲覧のほど宜しくお願い致します。タブレット端末は禁止されております。</div>
    </div >;
  } else if (!isSound) {
    // 初訪問時
    result =
      <div>
        <div id="background">
        </div>
        <div id='first-screen'>
          <img src="img/door.png" id="door"></img>
          <div id='box-choise'>
            <a href="javascript:void(0)" onClick={() => { onClikedDoor('soundOn') }}><img src="img/door_message_yes.png"></img></a><a href="javascript:void(0)" onClick={() => { onClikedDoor('exit') }}><img src="img/door_message_no.png"></img></a>
          </div>
        </div>

      </div>;

  } else {
    // リピーター

    result =
      <div>
        {readAudio}
        <div id="background">
          <div id="bg-place-wrapper">
            {bgPlaceBacker}
            {bgPlaceBack}
            {bgPlaceOD}
          </div>
          <div id="bg-od-wrapper"><img id="bg-od" src={EXPRESSES[express[phase]]} ></img></div>
          {bgPlaceFront}
        </div>
        <div id="headline">
          <div id="headline-main">
            <div className="row">
              <div id="headline-main-title">
                <span>超秘密基地</span><br /><span><br className="sp_br" ></br>　ODEN研究所(仮)</span>
              </div>
            </div>
            <div id="headline-main-subtitle">　　　　　　　　MURAバんく。<br className="sp_br" ></br>Official Website
            </div>
          </div>
          <div id="menu-phone" className={active}>
            <a id="menu-trigger" onClick={() => {
              onClickedHamburger(!isMenuToggle)
            }} href="#">
              <span></span>
              <span></span>
              <span></span>

            </a>
            <nav>

              {menu}

            </nav>
          </div>
          <div id="menu-pc">
            {menu}
          </div>

        </div >

        {appeerMurabanku}

        <div id="statesline">
          <Affinity affinity={affinity} />
        </div>
        <div id="message-box">
          {thinkBubble}
          {askBubble}
          {speakBubble}
          {raiseAffinity}

        </div>
      </div >;

  }



  return result;
}



ReactDOM.render(
  <Game />,
  document.getElementById('game-section')
);
