無題

Pasted Nov 30, 2026, 4:08 PM1 file12,808 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgrs7yz2ghb1232
無題
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Film管理</title>

<style>

/* =========================================================
   基本変数
========================================================= */

:root{
  --main:#2563eb;
  --bg:#f3f6fb;

  --panel-alpha:1;
  --card-alpha:1;

  --cols:6;

  /*
    文字サイズは「body」から継承させない。
    各領域が自分専用の変数を使用する。
  */
  --title-size:20px;
  --meta-size:13px;
  --form-size:14px;
  --memo-size:14px;
  --setting-size:14px;
  --table-size:14px;
  --header-size:14px;

  --title-font:"Yu Gothic",YuGothic,sans-serif;
  --meta-font:"Yu Gothic",YuGothic,sans-serif;
  --form-font:"Yu Gothic",YuGothic,sans-serif;
  --memo-font:"Yu Gothic",YuGothic,sans-serif;
  --setting-font:"Yu Gothic",YuGothic,sans-serif;
  --table-font:"Yu Gothic",YuGothic,sans-serif;

  --text:#18202a;
  --sub:#687385;
  --line:#dce2ea;

  --input-bg:#fff;
  --panel-bg:#fff;
  --button-bg:#e9edf3;
  --button-text:#18202a;
  --header-bg:rgba(255,255,255,.94);

  --title-box-bg:rgba(255,255,255,.45);
  --stat-box-bg:rgba(255,255,255,.45);

  /*
    一覧のサイズ
    1=極限まで詰める
    5=ゆったり
  */
  --table-padding-y:0px;
  --table-padding-x:0px;
  --table-line-height:0.9;

  --table-sticky-top:49px;

  --rating1:#6b7280;
  --rating2:#1683ff;
  --rating3:#13a538;
  --rating4:#ff4f91;
  --rating5:#a000ff;
}

/* =========================================================
   ダークモード
========================================================= */

:root.dark{
  --bg:#11151b;
  --text:#eef2f7;
  --sub:#9da8b8;
  --line:#303844;

  --input-bg:#1b222c;
  --panel-bg:#1a2028;
  --button-bg:#29323e;
  --button-text:#eef2f7;
  --header-bg:rgba(20,25,32,.94);

  --title-box-bg:rgba(20,25,32,.55);
  --stat-box-bg:rgba(20,25,32,.55);
}

:root.dark .panel{
  border-color:#46515f;
}

:root.dark #pageEdit .field,
:root.dark #pageBackground .settingline,
:root.dark #pageSettings .settingline,
:root.dark #pageSettings .font-setting{
  border-color:#46515f;
}

:root.dark #pageBackground .sectiontitle,
:root.dark #pageSettings .sectiontitle{
  border-color:#46515f;
}

:root.dark .imagebox{
  border-color:#46515f;
}

:root.dark .rating-number.rating-5{
  color:#c084fc;
}

*{
  box-sizing:border-box;
}

html,
body{
  margin:0;
  min-height:100%;
}

body{
  color:var(--text);
  background:var(--bg);
  font-family:var(--setting-font);
}

#backgroundLayer{
  position:fixed;
  inset:0;
  z-index:0;
  background-position:center;
  background-size:cover;
  background-repeat:no-repeat;
  pointer-events:none;
}

header,
main{
  position:relative;
  z-index:1;
}

input,
select,
textarea,
button{
  font:inherit;
}

input,
select,
textarea{
  color:var(--text);
  background:var(--input-bg);
  border:1px solid var(--line);
  border-radius:7px;
  padding:7px 9px;
}

textarea{
  resize:vertical;
}

button{
  border:0;
  border-radius:8px;
  padding:8px 12px;
  background:var(--main);
  color:var(--main-text);
  cursor:pointer;
}

button:hover{
  filter:brightness(.95);
}

button.secondary{
  background:var(--button-bg);
  color:var(--button-text);
}

button.danger{
  background:#dc3545;
}

button.small{
  padding:5px 8px;
}

.hidden{
  display:none!important;
}

/* =========================================================
   上部バー
========================================================= */

header{
  position:sticky;
  top:0;
  z-index:50;
  background:var(--header-bg);
  backdrop-filter:blur(10px);
  border-bottom:1px solid var(--line);

  font-family:var(--setting-font);
  font-size:var(--header-size);
}

.head{
  max-width:1500px;
  margin:auto;
position:relative;
  padding:8px 12px;
  display:flex;
  align-items:center;
  gap:8px;
}

.logo{
  font-weight:800;
  margin-right:auto;
  white-space:nowrap;
}

nav{
  display:flex;
  gap:4px;
  flex-wrap:wrap;
}

nav button{
  background:transparent;
  color:var(--text);
}

nav button.active{
  background:var(--main);
  color:var(--main-text);
}

/* 上部バー中央:前画面ボタン */
.header-back-button{
  position:absolute;
  left:50%;
  transform:translateX(-50%);
  z-index:2;
  white-space:nowrap;
  border:1px solid var(--main);
  border-radius:7px;
  padding:5px 12px;
  background:var(--panel-bg);
  color:var(--main);
  font-weight:700;
}

.header-back-button:hover{
  background:color-mix(
    in srgb,
    var(--main) 10%,
    var(--panel-bg)
  );
}

/* =========================================================
   メイン
========================================================= */

main{
  max-width:1500px;
  margin:auto;
  padding:12px;
  font-family:var(--setting-font);
  font-size:var(--setting-size);
}

/* =========================================================
   パネル
========================================================= */

.panel{
  background:rgba(255,255,255,var(--panel-alpha));
  background-color:color-mix(
    in srgb,
    var(--panel-bg) calc(var(--panel-alpha) * 100%),
    transparent
  );
  border:1px solid rgba(210,218,228,.85);
  border-radius:12px;
  padding:12px;
  box-shadow:0 3px 15px rgba(0,0,0,.06);
  backdrop-filter:blur(2px);
}

.toolbar{
  display:flex;
  align-items:center;
  gap:7px;
  flex-wrap:wrap;
  margin-bottom:9px;
}

.toolbar input{
  flex:1;
  min-width:180px;
}

.hint{
  color:var(--sub);
  font-size:.8em;
}

/* =========================================================
   目録
========================================================= */

.grid{
  display:grid;
  grid-template-columns:repeat(var(--cols),minmax(0,1fr));
  gap:9px;
  align-items:stretch;
}

.card{
  min-width:0;
  overflow:hidden;
  border:1px solid rgba(210,218,228,.85);
  background:rgba(255,255,255,var(--card-alpha));
  background-color:color-mix(
    in srgb,
    var(--panel-bg) calc(var(--card-alpha) * 100%),
    transparent
  );
  border-radius:10px;
  cursor:pointer;
  backdrop-filter:blur(2px);

  display:flex;
  flex-direction:column;
}

.poster,
.no-poster{
  width:100%;
  aspect-ratio:2/3;
  flex:none;
}

.poster{
  object-fit:cover;
  display:block;
}

.no-poster{
  background:linear-gradient(135deg,#dce2ea,#f5f7fa);
  display:flex;
  align-items:center;
  justify-content:center;
  color:#8a94a3;
  font-size:2em;
}

.cardbody{
  padding:7px;
  display:flex;
  flex-direction:column;
  flex:1;
}

.cardtitle{
  font-family:var(--title-font);
  font-size:var(--title-size);
  font-weight:700;

  min-height:2.5em;

  display:flex;
  align-items:center;

  white-space:pre-wrap;
  overflow-wrap:anywhere;
  word-break:break-word;

  padding:5px 7px;
  border:1px solid rgba(210,218,228,.95);
  border-radius:6px;

  background:var(--title-box-bg);
}

.cardstats{
  display:grid;
  grid-template-columns:1fr 1fr;
  gap:5px;
  margin-top:5px;

  font-family:var(--meta-font);
  font-size:var(--meta-size);
}

.cardstat{
  min-width:0;
  min-height:2.45em;

  display:flex;
  align-items:center;
  justify-content:center;

  gap:4px;
  padding:2px 4px;

  color:var(--text);

  white-space:nowrap;
  overflow:hidden;
}

.cardstat-label{
  flex:none;
  font-weight:700;
}

.cardstat-number{
  min-width:3em;
  height:1.65em;

  display:inline-flex;
  align-items:center;
  justify-content:center;

  padding:0 6px;

  border:1px solid rgba(210,218,228,.95);
  border-radius:6px;

  background:var(--stat-box-bg);

  font-weight:700;
  line-height:1;
}

.rating-number.rating-1{
  color:var(--rating1);
}

.rating-number.rating-2{
  color:var(--rating2);
}

.rating-number.rating-3{
  color:var(--rating3);
}

.rating-number.rating-4{
  color:var(--rating4);
}

.rating-number.rating-5{
  color:var(--rating5);
}

:root.dark .rating-number.rating-5{
  color:#c084fc;
}

.cardgenres{
  display:none;
}

/* =========================================================
   目録:表示切り替え
========================================================= */

.grid.hide-title .cardtitle{
  display:none;
}

.grid.hide-info .cardstats{
  display:none;
}

/* =========================================================
   目録:検索・絞り込み・ソート収納
========================================================= */

#listControls.hidden{
  display:none;
}

#tableControls.hidden{
  display:none;
}


/* =========================================================
   絞り込み
========================================================= */

.filterbar{
  display:flex;
  gap:7px;
  flex-wrap:wrap;
  margin-bottom:9px;
  align-items:flex-start;
}

.filtergroup{
  border:1px solid var(--line);
  border-radius:8px;
  padding:6px 8px;
  background:rgba(255,255,255,.45);
}

.filterhead{
  display:flex;
  align-items:center;
  gap:5px;
}

.filtertitle{
  background:#eef1f5;
  color:#18202a;
  padding:5px 10px;
  border-radius:6px;
  cursor:pointer;
}

.dark .filtertitle{
  background:#303947;
  color:#eef2f7;
}

.filtertitle.active{
  background:var(--main);
  color:var(--main-text);
}

.filterclear{
  background:#eef1f5;
  color:#18202a;
  padding:5px 8px;
  border-radius:6px;
  cursor:pointer;
}

.dark .filterclear{
  background:#303947;
  color:#eef2f7;
}

.filterchoices{
  display:flex;
  gap:4px;
  flex-wrap:wrap;
  margin-top:5px;
  max-width:700px;
}

.filterButton{
  background:#eef1f5;
  color:#18202a;
  padding:4px 8px;
  border-radius:6px;
  border:2px solid transparent;
  cursor:grab;
}

.filterButton:active{
  cursor:grabbing;
}

.filterButton.dragging{
  opacity:.45;
}

.filterButton.dragover{
  transform:scale(1.08);
}

.dark .filterButton{
  background:#303947;
  color:#eef2f7;
}

.filterButton.selected{
  border:4px solid var(--main);
}

.dark .filterButton.selected{
  color:#eef2f7;
}

.genreChoices{
  display:none;
  width:100%;
  box-sizing:border-box;
}

.genreChoices.open{
  display:flex;
  flex-wrap:wrap;
  width:100%;
  max-width:none;
  gap:4px;
  margin-top:5px;
}

.attributeChoices{
  display:none;
}

.attributeChoices.open{
  display:flex;
}

#attributeChoices{
  display:none;
}

#attributeChoices.open{
  display:flex;
}

}

/* =========================================================
   完全新規:項目一覧
========================================================= */

.itemlist-wrap{
  width:100%;
  overflow:visible;
}

.itemlist-table{
  width:100%;
  border-spacing:0;
  border-collapse:separate;
  table-layout:auto;
  font-family:var(--table-font);
  font-size:var(--table-size);
}

.itemlist-table th,
.itemlist-table td{
  border-right:1px solid var(--line);
  border-bottom:1px solid var(--line);

  padding:
    var(--table-padding-y)
    var(--table-padding-x);

  vertical-align:middle;
  line-height:var(--table-line-height);

  background:color-mix(
    in srgb,
    var(--panel-bg) 94%,
    transparent
  );
}

.itemlist-table tbody td{
  vertical-align:middle;
}

.itemlist-table th{
  position:sticky;
  top:var(--table-sticky-top);
  z-index:10;
  background:var(--panel-bg);
  font-weight:800;
  white-space:nowrap;
}

.itemlist-table thead tr:first-child th{
  border-top:1px solid var(--line);
}

.itemlist-table tbody tr:hover td{
  background:color-mix(
    in srgb,
    var(--main) 6%,
    var(--panel-bg)
  );
}

/* 項目一覧:閲覧・保存した記録の強調ライン */
.itemlist-table tbody tr.itemlist-focus-line td{
  position:relative;
}

.itemlist-table tbody tr.itemlist-focus-line td::after{
  content:"";
  position:absolute;
  left:0;
  right:0;
  bottom:0;
  height:3px;
  background:var(--main);
  transform:scaleX(0);
  transform-origin:left center;
  animation:itemlistFocusLine 1s ease-out forwards;
  pointer-events:none;
}

@keyframes itemlistFocusLine{
  0%{
    transform:scaleX(0);
    opacity:1;
  }
  85%{
    transform:scaleX(1);
    opacity:1;
  }
  100%{
    transform:scaleX(1);
    opacity:0;
  }
}

.itemlist-edit{
  width:1%;
  white-space:nowrap;
  text-align:center;
  vertical-align:middle!important;
}

/*
  一覧をできるだけ縦に詰めるため、
  編集ボタンを通常のボタン形状ではなく
  極小のリンク風表示にする。
*/
.itemlist-edit button{
  width:auto;
  height:auto;
  min-width:0;
  padding:0;
  margin:0;
  border:0;
  border-radius:0;
  white-space:nowrap;
  display:inline;
  background:transparent;
  color:var(--main);
  font-size:1em;
  line-height:1;
  cursor:pointer;
}
:root.dark .itemlist-edit button{
  color:var(--text);
}

.itemlist-edit button:hover{
  filter:none;
  text-decoration:underline;
}

.itemlist-title{
  min-width:120px;
  max-width:var(--itemlist-title-width);
  font-weight:700;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  line-height:1.25;
}


.itemlist-title-button{
  display:block;
  width:100%;
  padding:0;
  margin:0;
  border:0;
  border-radius:0;
  background:transparent;
  color:var(--text);
  text-align:left;
  font-weight:700;
  cursor:pointer;
  overflow-wrap:anywhere;
  word-break:break-word;
}

.itemlist-title-button:hover{
  filter:none;
  text-decoration:underline;
}

.itemlist-title-plain{
  color:var(--text);
}

.itemlist-number{
  text-align:center;
  white-space:nowrap;
  width:1%;
}

.itemlist-rating{
  text-align:center;
  white-space:nowrap;
  font-weight:700;
  width:1%;
}

.itemlist-dates{
  width:1%;
  min-width:0;
  white-space:nowrap;
  line-height:1.25;
}

.itemlist-genres{
  min-width:75px;
  max-width:165px;
  overflow-wrap:anywhere;
  word-break:break-word;
  line-height:1.25;
}

.itemlist-memo{
  min-width:140px;
  max-width:360px;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
  line-height:1.25;
}


.itemlist-empty{
  text-align:center;
  color:var(--sub);
  padding:18px!important;
}

.itemlist-table tbody tr{
  vertical-align:top;
}

.itemlist-table tbody td{
  font-size:var(--table-size);
  line-height:0.45;
}

.itemlist-table tbody td.itemlist-title,
.itemlist-table tbody td.itemlist-number,
.itemlist-table tbody td.itemlist-rating,
.itemlist-table tbody td.itemlist-dates,
.itemlist-table tbody td.itemlist-genres,
.itemlist-table tbody td.itemlist-memo{
  line-height:0.45;
}

/* 一覧サイズ1でも見出し行はサイズ2相当の高さを確保 */
.itemlist-table th{
  padding-top:8px;
  padding-bottom:8px;
}

/* =========================================================
   属性
========================================================= */

.attribute-grid{
  display:grid;
  grid-template-columns:
    repeat(6, minmax(0, 1fr));
  gap:6px;
  width:100%;
}

.attribute-item{
  min-width:0;
  height:34px;
  box-sizing:border-box;

  display:flex;
  align-items:center;

  padding:4px 7px;

  border:2px solid;
  border-radius:5px;

  box-sizing:border-box;
}

.attribute-item input[type="checkbox"]{
  width:16px;
  height:16px;
  margin:0;
  flex:0 0 auto;
}

/* 赤 */
.attribute-red{
  background:#ff1744;
  border-color:#ff1744;
}

/* 青 */
.attribute-blue{
  background:#2979ff;
  border-color:#2979ff;
}

/* 黄 */
.attribute-yellow{
  background:#ffd600;
  border-color:#ffd600;
}

/* 緑 */
.attribute-green{
  background:#00c853;
  border-color:#00c853;
}

/* 橙 */
.attribute-orange{
  background:#ff6d00;
  border-color:#ff6d00;
}

/* 紫 */
.attribute-purple{
  background:#aa00ff;
  border-color:#aa00ff;
}

/* ピンク */
.attribute-pink{
  background:#ff4081;
  border-color:#ff4081;
}

/* 水色 */
.attribute-cyan{
  background:#00b8d4;
  border-color:#00b8d4;
}

/* 灰 */
.attribute-gray{
  background:#808080;
  border-color:#666666;
}

/* 茶 */
.attribute-brown{
  background:#5d4037;
  border-color:#3e2723;
}

/* 白 */
.attribute-white{
  background:#ffffff;
  border-color:#777777;
  box-shadow:
    inset 0 0 0 1px #777777;
}

/* 黒 */
.attribute-black{
  background:#000000;
  border-color:#777777;
  box-shadow:
    inset 0 0 0 1px #777777;
}

.attribute-item input[type="text"]{
  min-width:0;
  width:100%;
  height:24px;
  margin-left:6px;
  padding:2px 5px;

  box-sizing:border-box;

  border:1px solid rgba(0,0,0,.35);
  border-radius:3px;

  background:#ffffff;
  color:#111111;

  font-size:13px;
}

.attribute-item input[type="text"]:focus{
  outline:2px solid rgba(0,0,0,.35);
  outline-offset:-1px;
}


.itemlist-time{
  text-align:center;
  white-space:nowrap;
  width:40px;
}

.itemlist-year{
  text-align:center;
  white-space:nowrap;
  width:45px;
}

.itemlist-dates{
  width:80px;
  min-width:80px;
  white-space:nowrap;
  text-align:left;
}



/* =========================================================
   フォーム
========================================================= */

#pageEdit{
  font-family:var(--form-font);
  font-size:var(--form-size);
}

.formgrid{
  display:grid;
  grid-template-columns:
    155px 155px 155px
    minmax(0,1fr)
    minmax(0,1fr)
    minmax(0,1fr);
  column-gap:3px;
  row-gap:7px;
}

.field{
  display:flex;
  flex-direction:column;
  gap:4px;
}

/*
  追加・編集画面の配置

  1段目:タイトル・読み
  2段目:時間・公開・視聴回数・ジャンル
  3段目:製作国・監督・主演
  4段目:メーカー・評価・気楽
  5段目:不快・ABC・難解・画質
*/

/* =========================================================
   1段目
   タイトル・読み
   C:フォーム全体を2等分
   2項目を完全に同じ幅にする
========================================================= */

.formgrid .field:nth-child(1){
  grid-column:1 / 7;
  grid-row:1;
  width:calc(50% - 12.5px);
  max-width:none;
  min-width:0;
}

.formgrid .field:nth-child(2){
  grid-column:1 / 7;
  grid-row:1;
  width:calc(50% - 12.5px);
  max-width:none;
  min-width:0;
  margin-left:calc(50% + 12.5px);
}

.formgrid .field:nth-child(1) input,
.formgrid .field:nth-child(1) textarea,
.formgrid .field:nth-child(2) input,
.formgrid .field:nth-child(2) textarea{
  width:100%;
  max-width:100%;
  min-width:0;
  box-sizing:border-box;
}

/* =========================================================
   2段目
   時間・公開・視聴回数・ジャンル

   A:時間・公開・視聴回数
   B:ジャンル
========================================================= */

.formgrid .field:nth-child(3){
  grid-column:1;
}

.formgrid .field:nth-child(4){
  grid-column:2;
}

.formgrid .field:nth-child(5){
  grid-column:3;
}

.formgrid .field:nth-child(6){
  grid-column:4 / 7;
}


/* =========================================================
   3段目
   製作国・監督・主演

   A:製作国
   B:監督
   B:主演
========================================================= */

.formgrid .field:nth-child(8){
  grid-column:1;
}

.formgrid .field:nth-child(9){
  grid-column:2 / 4;
}

.formgrid .field:nth-child(10){
  grid-column:4 / 7;
}

/* =========================================================
   4段目
   メーカー・評価・気楽
========================================================= */

.formgrid .field:nth-child(7){
  grid-column:1 / 3;
  grid-row:4;
}

/* =========================================================
   評価6項目専用エリア
   外側の6列グリッドに合わせる

   【将来追加用スペース】
   将来、新しい評価項目を追加する場合は
   「気楽」の右隣に追加する。
========================================================= */


.formgrid .rating-fields{
  grid-column:1 / 7;
  grid-row:4 / 6;

  display:grid;

  grid-template-columns:
    155px 155px 155px
    minmax(0,1fr)
    minmax(0,1fr)
    minmax(0,1fr);

  column-gap:25px;
  row-gap:7px;

  align-items:start;

  min-width:0;
}


/* 評価 */
.formgrid .rating-fields .field:nth-child(1){
  grid-column:3 / 5;
  grid-row:1;
}

/* 気楽 */
.formgrid .rating-fields .field:nth-child(2){
  grid-column:5 / 7;
  grid-row:1;
  transform:translateX(-530px);
}

/* 不快 */
.formgrid .rating-fields .field:nth-child(3){
  grid-column:1 / 3;
  grid-row:2;
  transform:translateX(90px);
}

/* ABC */
.formgrid .rating-fields .field:nth-child(4){
  grid-column:3 / 5;
  grid-row:2;
  position:relative;
  z-index:2;
}

/* 難解 */
.formgrid .rating-fields .field:nth-child(5){
  grid-column:5;
  grid-row:2;
  transform:translateX(-218px);
  position:relative;
  z-index:2;
}

/* 画質 */
.formgrid .rating-fields .field:nth-child(6){
  grid-column:6;
  grid-row:2;
  transform:translateX(-300px);
  z-index:1;
}

/* =========================================================
   全幅
========================================================= */

.field.full{
  grid-column:1/-1;
}


/* =========================================================
   入力欄
========================================================= */

.field label{
  font-weight:650;
}

.formArea{
  font-family:var(--form-font);
  font-size:var(--form-size);
}

.titleArea{
  font-family:var(--form-font);
  font-size:var(--form-size);
  min-height:42px;
  resize:vertical;
}

.memoArea{
  font-family:var(--memo-font);
  font-size:var(--memo-size);
}


/*
  追加・編集画面の入力欄を見やすくする
*/

#pageEdit .field input,
#pageEdit .field textarea{
  border:2px solid var(--line);
}


/* =========================================================
   A項目
   時間・公開・視聴回数・製作国

   数字中心なので短め
========================================================= */

#pageEdit #fTime,
#pageEdit #fYear,
#pageEdit #fCount,
#pageEdit #fCountry{
  width:100%;
  max-width:100%;
}

/* =========================================================
   B項目
   ジャンル・メーカー・監督・主演
   4項目を同じ幅に統一
========================================================= */

#pageEdit #fGenre,
#pageEdit #fMaker,
#pageEdit #fDirector,
#pageEdit #fCast{
  width:330px;
  max-width:330px;
  box-sizing:border-box;
}

/* =========================================================
   フォーカス
========================================================= */

#pageEdit .field input:focus,
#pageEdit .field textarea:focus{
  outline:none;
  border-color:var(--main);
  box-shadow:0 0 0 2px color-mix(
    in srgb,
    var(--main) 15%,
    transparent
  );
}


.sectiontitle{
  font-weight:800;
  border-bottom:1px solid var(--line);
  padding-bottom:5px;
  margin:13px 0 8px;
}


/* =========================================================
   1~5入力
========================================================= */

/*
  評価・不快・ABC・難解・画質は
  12345を必ず横一列にする。
*/
.ratingrow{
  display:flex;
  gap:2px;
  flex-wrap:nowrap;
  white-space:nowrap;
  align-items:center;
  width:max-content;
  max-width:100%;
}

.ratingrow button{
  background:var(--button-bg);
  color:var(--button-text);
  min-width:38px;
  flex:0 0 auto;
}

.formgrid > .field:has(.ratingrow){
  min-width:0;
}

.ratingrow button.on{
  background:var(--main);
  color:var(--main-text);
}

/* =========================================================
   ポスター
========================================================= */

.imagebox{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
  min-height:90px;
  padding:8px;
  border:2px dashed var(--line);
  border-radius:10px;
}

.thumb{
  position:relative;
  width:80px;
}

.thumb img{
  width:80px;
  height:110px;
  object-fit:cover;
  border-radius:7px;
}

.thumb button{
  position:absolute;
  top:2px;
  right:2px;
  padding:1px 6px;
  background:rgba(0,0,0,.7);
}

/* =========================================================
   視聴日
========================================================= */

.dates{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  gap:7px;
}

/* =========================================================
   設定・背景
========================================================= */

#pageSettings,
#pageBackground,
  font-family:var(--setting-font);
  font-size:var(--setting-size);
}

.settingline{
  display:grid;
  grid-template-columns:125px 1fr;
  align-items:center;
  gap:8px;
  padding:7px 0;
  border-bottom:1px solid #edf0f4;
}

#pageBackground .background-color-setting{
  margin-bottom:12px;
}


/* 設定:イメージカラーとダークモードの間隔 */
#pageSettings .settingline:first-of-type{
  margin-bottom:8px;
}

/* 背景:背景カラーと背景透過の間隔 */
#pageBackground .settingline:first-of-type{
  margin-bottom:12px;
}

.dark .settingline{
  border-color:#2b333e;
}

.choice-buttons{
  display:flex;
  gap:4px;
  flex-wrap:wrap;
}

.choice{
  min-width:38px;
  padding:5px 8px;
  background:var(--button-bg);
  color:var(--button-text);
  border:2px solid transparent;
}

.choice.selected{
  background:var(--main);
  color:var(--main-text);
  border-color:var(--main);
}

.choice.disabled{
  opacity:.35;
  cursor:not-allowed;
}

/* =========================================================
   一覧サイズ
========================================================= */

.table-size-hint{
  margin-top:4px;
}

/* =========================================================
   カラー
========================================================= */

.colors{
  display:flex;
  gap:7px;
  flex-wrap:wrap;
  align-items:center;
}

.color{
  width:28px;
  height:28px;
  border-radius:50%;
  border:3px solid transparent;
  cursor:grab;
  box-shadow:0 0 0 1px rgba(0,0,0,.15);
}

/* 白・黒が背景に紛れないための枠 */
.color.color-white{
  border:2px solid #777777;
}

.color.color-offwhite{
  border:2px solid #999999;
}

/* 黒色の〇 */
.color.color-black{
  border:3px solid #777 !important;
  box-shadow:0 0 0 2px #777 !important;
}

.color:active{
  cursor:grabbing;
}

.color.dragging{
  opacity:.45;
}

.color.dragover{
  transform:scale(1.12);
}

.color.selected{
  border-color:#111;
  box-shadow:
    0 0 0 2px white inset,
    0 0 0 1px #111;
}

/* =========================================================
   文字設定
========================================================= */

.font-setting{
  display:grid;
  grid-template-columns:105px minmax(0,1fr);
  gap:8px;
  padding:9px 0;
  border-bottom:1px solid #edf0f4;
  min-height:58px;
  align-items:center;
}

.dark .font-setting{
  border-color:#2b333e;
}

.font-setting-label{
  font-weight:700;
  white-space:nowrap;
}

.font-control{
  display:flex;
  align-items:center;
  flex-wrap:wrap;
  gap:4px;
}

.font-size-options{
  display:flex;
  gap:5px;
  flex:none;
  margin-right:18px;
}

.font-options{
  display:flex;
  flex-wrap:wrap;
  gap:5px;
  margin-left:0;
}

.font-option{
  width:42px;
  min-width:42px;
  height:34px;

  display:flex;
  align-items:center;
  justify-content:center;

  background:var(--button-bg);
  color:var(--button-text);

  border:2px solid transparent;
  padding:4px 6px;
  border-radius:6px;

  white-space:nowrap;
}

.font-option.selected{
  background:var(--main);
  color:white;
  border-color:var(--main);
}

.font-sample{
  font-size:1.05em;
  font-weight:700;
}

/* =========================================================
   背景ページ
========================================================= */

.drop-area{
  min-height:150px;
  display:flex;
  align-items:center;
  justify-content:center;
  text-align:center;
  border:2px dashed var(--line);
  border-radius:10px;
  transition:.15s;
}

.drop-area.dragover{
  border-color:var(--main);
  background:rgba(37,99,235,.07);
}

.bg-preview{
  width:100%;
  max-height:300px;
  object-fit:contain;
  border-radius:8px;
  margin-top:10px;
}

/* =========================================================
   画像検索
========================================================= */

.modal{
  position:fixed;
  inset:0;
  background:rgba(0,0,0,.65);
  z-index:100;
  display:flex;
  align-items:center;
  justify-content:center;
  padding:15px;

  font-family:var(--setting-font);
  font-size:var(--setting-size);
}

.modalbox{
  width:min(950px,100%);
  max-height:90vh;
  overflow:auto;
  background:var(--panel-bg);
  color:var(--text);
  border-radius:14px;
  padding:14px;
}

.searchimgs{
  display:grid;
  grid-template-columns:repeat(6,1fr);
  gap:7px;
}

.searchimg{
  border:2px solid transparent;
  border-radius:7px;
  overflow:hidden;
  cursor:pointer;
}

.searchimg.selected{
  border-color:var(--main);
}

.searchimg img{
  width:100%;
  aspect-ratio:2/3;
  object-fit:cover;
  display:block;
}

/* =========================================================
   完全新規:一覧から画像を表示するモーダル
========================================================= */

.movieImageModalBox{
  width:min(1100px,100%);
  max-height:90vh;
  overflow:auto;
  background:var(--panel-bg);
  color:var(--text);
  border-radius:14px;
  padding:14px;
}

.movieImageView{
  display:flex;
  flex-wrap:wrap;
  justify-content:center;
  align-items:flex-start;
  gap:12px;
}

.movieImageView img{
  width:auto;
  max-width:min(260px,42vw);
  max-height:70vh;
  object-fit:contain;
  border-radius:8px;
}

/* =========================================================
   レスポンシブ
========================================================= */

@media(max-width:900px){

  .grid{
    grid-template-columns:repeat(min(5,var(--cols)),minmax(0,1fr));
  }

  .searchimgs{
    grid-template-columns:repeat(5,1fr);
  }

  .itemlist-table{
    min-width:1050px;
  }
}

@media(max-width:700px){

  .formgrid{
    grid-template-columns:1fr;
  }

  .formgrid .field:nth-child(1),
  .formgrid .field:nth-child(2),
  .formgrid .field:nth-child(3),
  .formgrid .field:nth-child(4),
  .formgrid .field:nth-child(5),
  .formgrid .field:nth-child(6),
  .formgrid .field:nth-child(7),
  .formgrid .field:nth-child(8),
  .formgrid .field:nth-child(9),
  .formgrid .field:nth-child(10){
    grid-column:1/-1;
  }

  .settingline,
  .font-setting{
    grid-template-columns:1fr;
  }

  .dates{
    grid-template-columns:1fr;
  }

  .grid{
    grid-template-columns:repeat(3,minmax(0,1fr));
  }

  .searchimgs{
    grid-template-columns:repeat(3,1fr);
  }

  .movieImageView img{
    max-width:80vw;
    max-height:65vh;
  }
}

@media(max-width:500px){

  .grid{
    grid-template-columns:repeat(2,minmax(0,1fr));
  }

  .logo{
    display:none;
  }

  .cardtitle{
    font-size:var(--title-size);
  }

  .cardstats{
    gap:3px;
  }

  .cardstat{
    gap:3px;
    padding:2px 2px;
  }

  .cardstat-number{
    padding:0 4px;
  }

  .font-size-options{
    margin-right:12px;
  }
}
#pageEdit .formgrid {
  column-gap: 25px;
  row-gap: 7px;
}

.formgrid > .field:nth-child(13),
.formgrid > .field:nth-child(14),
.formgrid > .field:nth-child(15),
.formgrid > .field:nth-child(16){
  transform:none;
}


/* =========================================================
   目録・属性絞り込み:3段表示
========================================================= */

#attributeChoices{
  display:none !important;
  grid-template-columns:repeat(4, 1fr);
  gap:4px;
  width:100%;
  max-width:700px;
}

#attributeChoices.open{
  display:grid !important;
}

#attributeChoices .attribute-filter-button{
  min-width:0;
  width:100%;
  box-sizing:border-box;
  text-align:center;
}

/* 目録・属性絞り込み:通常モードの文字色 */
:root:not(.dark) #attributeChoices .attribute-gray{
  color:#ffffff;
}

:root:not(.dark) #attributeChoices .attribute-brown{
  color:#ffffff;
}

:root:not(.dark) #attributeChoices .attribute-white:not(.selected){
  color:#18202a;
}

:root:not(.dark) #attributeChoices .attribute-purple{
  color:#ffffff;
}

:root:not(.dark) #attributeChoices .attribute-black{
  color:#ffffff;
}


#attributeChoices .attribute-selected-mark{
  font-size:20px;
  font-weight:900;
}

/* =========================================================
   目録・属性絞り込み:選択時の内側太枠
========================================================= */

#attributeChoices .attribute-filter-button.selected{
  box-sizing:border-box;
  box-shadow:inset 0 0 0 4px rgba(255,255,255,.9);
}

/* =========================================================
   目録・属性絞り込み:ダークモードでも属性色を維持
========================================================= */

.dark #attributeChoices .attribute-filter-button.attribute-red{
  background:#ff1744;
}

.dark #attributeChoices .attribute-filter-button.attribute-blue{
  background:#2979ff;
}

.dark #attributeChoices .attribute-filter-button.attribute-yellow{
  background:#ffd600;
}

.dark #attributeChoices .attribute-filter-button.attribute-green{
  background:#00c853;
}

.dark #attributeChoices .attribute-filter-button.attribute-orange{
  background:#ff6d00;
}

.dark #attributeChoices .attribute-filter-button.attribute-purple{
  background:#aa00ff;
}

.dark #attributeChoices .attribute-filter-button.attribute-pink{
  background:#ff4081;
}

.dark #attributeChoices .attribute-filter-button.attribute-cyan{
  background:#00b8d4;
}

.dark #attributeChoices .attribute-filter-button.attribute-gray{
  background:#808080;
}

.dark #attributeChoices .attribute-filter-button.attribute-brown{
  background:#5d4037;
}

.dark #attributeChoices .attribute-filter-button.attribute-white{
  background:#ffffff;
}

.dark #attributeChoices .attribute-filter-button.attribute-black{
  background:#000000;
}

/* =========================================================
   目録・属性「白」:ダークモードでも暗い文字
========================================================= */

.dark #attributeChoices .attribute-filter-button.attribute-white{
  color:#18202a !important;
}

/* =========================================================
   一覧・属性絞り込み:目録と同じ見た目
   ※一覧専用。目録側 #attributeChoices には触れない
========================================================= */
#tableAttributeChoices{
  display:none !important;
  grid-template-columns:repeat(4, 1fr);
  gap:4px;
  width:100%;
  max-width:700px;
}

#tableAttributeChoices.open{
  display:grid !important;
}

#tableAttributeChoices .attribute-filter-button{
  min-width:0;
  width:100%;
  box-sizing:border-box;
  text-align:center;
}

:root:not(.dark) #tableAttributeChoices .attribute-gray{
  color:#ffffff;
}

:root:not(.dark) #tableAttributeChoices .attribute-brown{
  color:#ffffff;
}

:root:not(.dark) #tableAttributeChoices .attribute-white:not(.selected){
  color:#18202a;
}

:root:not(.dark) #tableAttributeChoices .attribute-purple{
  color:#ffffff;
}

:root:not(.dark) #tableAttributeChoices .attribute-black{
  color:#ffffff;
}

#tableAttributeChoices .attribute-selected-mark{
  font-size:20px;
  font-weight:900;
}

#tableAttributeChoices .attribute-filter-button.selected{
  box-sizing:border-box;
  box-shadow:inset 0 0 0 4px rgba(255,255,255,.9);
}

/* ダークモードでも属性色を維持 */
.dark #tableAttributeChoices .attribute-filter-button.attribute-red{
  background:#ff1744;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-blue{
  background:#2979ff;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-yellow{
  background:#ffd600;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-green{
  background:#00c853;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-orange{
  background:#ff6d00;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-purple{
  background:#aa00ff;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-pink{
  background:#ff4081;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-cyan{
  background:#00b8d4;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-gray{
  background:#808080;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-brown{
  background:#5d4037;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-white{
  background:#ffffff;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-black{
  background:#000000;
}

.dark #tableAttributeChoices .attribute-filter-button.attribute-white{
  color:#18202a !important;
}

/* 編集画面:前後移動ボタン */
.edit-nav-spacer-large{
  display:inline-block;
  width:70px;
}

.edit-nav-spacer-small{
  display:inline-block;
  width:15px;
}

.edit-nav-button{
  width:45px;
  height:35px;
  padding:0;
  font-size:24px;
  font-weight:900;
  line-height:1;
  cursor:pointer;
}

/* =========================================================
   ODS説明ページ
========================================================= */

.ods-help{
  line-height:1.7;
}

.ods-help h3{
  margin-top:24px;
  margin-bottom:10px;
}

.ods-table{
  display:grid;
  grid-template-columns:minmax(100px, 1fr) 30px minmax(150px, 1.5fr);
  gap:4px 8px;
  margin:12px 0 20px;
}

.ods-table > div{
  padding:4px 6px;
}

.ods-table > div:nth-child(3n+1){
  font-weight:bold;
}

.ods-example{
  background:#f5f5f5;
  border:1px solid #ddd;
  border-radius:6px;
  padding:10px 12px;
  margin:10px 0;
}

.ods-date-example{
  display:flex;
  flex-wrap:wrap;
  gap:8px 18px;
  background:#f5f5f5;
  border:1px solid #ddd;
  border-radius:6px;
  padding:10px 12px;
  margin:10px 0;
}

.ods-color-grid{
  display:grid;
  grid-template-columns:repeat(4, minmax(90px, 1fr));
  gap:8px;
  margin:12px 0 16px;
}

.ods-color-grid > div{
  padding:7px 8px;
  border:1px solid #ddd;
  border-radius:6px;
  background:#fff;
  text-align:center;
}

.ods-flow{
  text-align:center;
  font-weight:bold;
  background:#f5f5f5;
  border:1px solid #ddd;
  border-radius:6px;
  padding:12px;
  margin:12px 0;
}

@media(max-width:700px){
  .ods-color-grid{
    grid-template-columns:repeat(3, minmax(80px, 1fr));
  }
}

@media(max-width:480px){
  .ods-color-grid{
    grid-template-columns:repeat(2, minmax(80px, 1fr));
  }
}

/* 目録上部:表示項目と列数を横並びにする */
.list-display-group {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 6px;
}

.list-display-label {
  white-space: nowrap;
  font-weight: bold;
  margin-left: 8px;
}

#pageTable .toolbar > span {
  font-weight: bold;
}

.list-display-group .choice-buttons {
  display: flex;
  flex-wrap: nowrap;
  gap: 4px;
}

/* =========================================================
   検索欄開閉ボタン
========================================================= */

.search-toggle-button{
  font-weight:800;
  border:1px solid var(--main);
  color:var(--main);
  background:color-mix(
    in srgb,
    var(--main) 8%,
    var(--panel-bg)
  );
  padding:5px 10px;
}

.search-toggle-button:hover{
  background:color-mix(
    in srgb,
    var(--main) 15%,
    var(--panel-bg)
  );
}

/* =========================================================
   目録:タイトル・情報 表示切り替えボタン
========================================================= */

#showTitleButton,
#showInfoButton{
  font-weight:800;
  box-shadow:
    inset 0 0 0 2px var(--main);
}

#showTitleButton.selected,
#showInfoButton.selected{
  font-weight:900;
  box-shadow:
    inset 0 0 0 3px var(--main);
}

</style>

<script src="https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js"></script>

</head>

<body>

<div id="backgroundLayer"></div>

<header>
<div class="head">

<div class="logo">🎬 Film管理</div>

<button
  type="button"
  class="header-back-button"
  onclick="goPreviousPage()"
>↩️ 前画面</button>

<nav>
<button id="navTable" onclick="showPage('table')">一覧</button>
<button id="navList" onclick="showPage('list')">目録</button>
<button id="navAdd" onclick="newMovie()">編集</button>
<button id="navBg" onclick="showPage('background')">背景</button>
<button id="navSetting" onclick="showPage('settings')">設定</button>
</nav>

</div>
</header>

<main>

<!-- =======================================================
     目録
======================================================= -->

<section id="pageList">

<div class="panel">

<div class="toolbar">

<button
type="button"
class="secondary small search-toggle-button"
onclick="toggleListControls()"
>
▲ 検索欄開閉
</button>


<div class="list-display-group">

<span class="list-display-label">
  表示 
</span>

<button
type="button"
id="showTitleButton"
class="filterButton selected"
>
タイトル
</button>

<button
type="button"
id="showInfoButton"
class="filterButton selected"
>
情報
</button>

<span class="list-display-label">
  目録の列数 
</span>

<div
id="colChoices"
class="choice-buttons"
></div>

</div>


</div>


<div id="listControls">

<div class="toolbar">

<input
id="search"
placeholder="タイトル・読み・監督・主演・メモ内ワードなど検索"
>

<button onclick="newMovie()">+追加</button>

<button
class="secondary"
onclick="resetFilters()"
>
条件解除
</button>

</div>

<div class="filterbar">

<div class="filtergroup">

<div class="filterhead">

<button
type="button"
class="filtertitle active"
>
評価
</button>

<button
type="button"
id="ratingClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="ratingChoices"
class="filterchoices"
></div>

</div>

<div class="filtergroup">

<div class="filterhead">

<button
type="button"
class="filtertitle active"
>
気楽
</button>

<button
type="button"
id="entertainmentClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="entertainmentChoices"
class="filterchoices"
></div>

</div>

<div class="filtergroup">

<div class="filterhead">

<button
type="button"
class="filtertitle active"
>
回数
</button>

<button
type="button"
id="countClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="countChoices"
class="filterchoices"
></div>

</div>

<div
id="attributeFilterGroup"
class="filtergroup"
>

<div class="filterhead">

<button
type="button"
id="attributeToggle"
class="filtertitle active"
>
属性
</button>

<button
type="button"
id="attributeClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="attributeChoices"
class="filterchoices attributeChoices"
></div>

</div>

</div>

<div
id="genreFilterGroup"
class="filtergroup"
>

<div class="filterhead">

<button
type="button"
id="genreToggle"
class="filtertitle active"
>
ジャンル
</button>

<button
type="button"
id="genreClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="genreChoices"
class="filterchoices genreChoices"
></div>

</div>

</div>

<div class="toolbar">

<label>
ソート
<select id="sort">
<option value="reading">タイトル</option>
<option value="time">時間</option>
<option value="year">公開</option>
<option value="date">視聴日</option>
<option value="count">回数</option>
<option value="rating">評価</option>
<option value="entertainment">気楽</option>
<option value="discomfort">不快</option>
<option value="abc">ABC</option>
<option value="difficulty">難解</option>
<option value="quality">画質</option>
<option value="country">製作国</option>
<option value="maker">メーカー</option>
</select>

</label>

<button
class="secondary small"
onclick="toggleDirection()"
>
昇順 / 降順
</button>

<span
id="resultCount"
class="hint"
></span>

</div>

</div>

<div
id="movieGrid"
class="grid"
></div>

</div>

</section>


<!-- =======================================================
     一覧
======================================================= -->

<section
id="pageTable"
class="hidden"
>

<div class="panel">

<div class="toolbar">

<button
type="button"
class="secondary small search-toggle-button"
onclick="toggleTableControls()"
>
▲ 検索欄開閉
</button>


<span>
  一覧のサイズ
</span>

<div
id="tableSizeChoices"
class="choice-buttons"
></div>


<span>
  タイトル枠
</span>

<div
id="titleWidthChoices"
class="choice-buttons"
></div>

</div>

<div id="tableControls">

<div class="toolbar">

<input
id="tableSearch"

placeholder="タイトル・読み・監督・主演・メモ内ワードなど検索"
>

<button
class="secondary"
onclick="resetTableFilters()"
>
条件解除
</button>

</div>

<div class="filterbar">

<div class="filtergroup">

<div class="filterhead">

<button
type="button"
class="filtertitle active"
>
評価
</button>

<button
type="button"
id="tableRatingClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="tableRatingChoices"
class="filterchoices"
></div>

</div>

<div class="filtergroup">

<div class="filterhead">

<button
type="button"
class="filtertitle active"
>
気楽
</button>

<button
type="button"
id="tableEntertainmentClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="tableEntertainmentChoices"
class="filterchoices"
></div>

</div>

<div class="filtergroup">

<div class="filterhead">

<button
type="button"
class="filtertitle active"
>
回数
</button>

<button
type="button"
id="tableCountClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="tableCountChoices"
class="filterchoices"
></div>

</div>

<div
  id="tableAttributeFilterGroup"
  class="filtergroup"
>

  <div class="filterhead">

    <button
      type="button"
      id="tableAttributeToggle"
      class="filtertitle active"
    >
      属性
    </button>

    <button
      type="button"
      id="tableAttributeClear"
      class="filterclear"
    >
      解除
    </button>

  </div>

  <div
    id="tableAttributeChoices"
    class="filterchoices"
  ></div>

</div>

</div>

<div
id="tableGenreFilterGroup"
class="filtergroup"
>

<div class="filterhead">

<button
type="button"
id="tableGenreToggle"
class="filtertitle active"
>
ジャンル
</button>

<button
type="button"
id="tableGenreClear"
class="filterclear"
>
解除
</button>

</div>

<div
id="tableGenreChoices"
class="filterchoices genreChoices"
></div>

</div>

<div class="toolbar">

<label>
ソート

<select id="tableSort">
<option value="reading">タイトル</option>
<option value="time">時間</option>
<option value="year">公開</option>
<option value="date">視聴日</option>
<option value="count">回数</option>
<option value="rating">評価</option>
<option value="entertainment">気楽</option>
<option value="discomfort">不快</option>
<option value="abc">ABC</option>
<option value="difficulty">難解</option>
<option value="quality">画質</option>
<option value="country">製作国</option>
<option value="maker">メーカー</option>
</select>

</label>

<button
class="secondary small"
onclick="toggleTableDirection()"
>
昇順 / 降順
</button>

<span
id="tableResultCount"
class="hint"
></span>

</div>

</div>

<div class="itemlist-wrap">

<table class="itemlist-table">

<thead>

<tr>

<th class="itemlist-edit">
編集
</th>

<th>
タイトル
</th>

<th>
時間
</th>

<th>
公開
</th>

<th>
ジャンル
</th>

<th>
回数
</th>

<th>
評価
</th>

<th>
気楽
</th>

<th>
不快
</th>

<th>
ABC
</th>

<th>
難解
</th>

<th>
画質
</th>

<th>
視聴日
</th>

<th>
メモ
</th>

</tr>

</thead>

<tbody
id="itemlistBody"
></tbody>

</table>

</div>

</div>

</section>

<!-- =======================================================
     追加・編集
======================================================= -->

<section
id="pageEdit"
class="hidden"
>

<div class="panel">

<div class="toolbar">

<button onclick="saveMovie()">
保存
</button>

<button
class="secondary"
onclick="clearEditForm()"
>
消去
</button>

<button
id="deleteBtn"
class="danger"
onclick="deleteMovie()"
>
削除
</button>

<span
class="edit-nav-spacer-large"
></span>

<button
id="editPrevBtn"
class="edit-nav-button"
type="button"
onclick="editPreviousMovie()"
>
◀
</button>


<span
class="edit-nav-spacer-small"
></span>

<button
id="editNextBtn"
class="edit-nav-button"
type="button"
onclick="editNextMovie()"
>
▶
</button>


</div>


<div class="formgrid">

<div class="field">

<label>タイトル</label>

<textarea
id="fTitle"
class="titleArea"
rows="2"
></textarea>

</div>

<div class="field">

<label>読み</label>

<input
id="fReading"
class="formArea"
>

</div>

<div class="field">

<label>時間</label>

<input
  id="fTime"
  class="formArea"
  type="text"
  value="0"
>


</div>

<div class="field">

<label>公開</label>

<input
id="fYear"
class="formArea"
type="number"
min="0"
>

</div>

<div class="field">

<label>視聴回数</label>

<input
id="fCount"
class="formArea"
type="number"
min="0"
value="0"
>

</div>

<div class="field">

<label>ジャンル</label>

<input
id="fGenre"
class="formArea"
placeholder="複数は全角スペース区切り"
>

</div>

<div class="field">

<label>メーカー</label>

<input
id="fMaker"
class="formArea"
>

</div>

<div class="field">

<label>製作国</label>

<input
id="fCountry"
class="formArea"
>

</div>

<div class="field">

<label>監督</label>

<input
id="fDirector"
class="formArea"
>

</div>

<div class="field">

<label>主演</label>

<input
id="fCast"
class="formArea"
>

</div>


<div class="rating-fields">

<div class="field">

<label>評価</label>
<div id="ratingInput" class="ratingrow"></div>

</div>

<div class="field">

<label>気楽</label>
<div id="entertainmentInput" class="ratingrow"></div>

</div>

<div class="field">

<label>不快</label>
<div id="discomfortInput" class="ratingrow"></div>

</div>

<div class="field">

<label>ABC</label>
<div id="abcInput" class="ratingrow"></div>

</div>

<div class="field">

<label>難解</label>
<div id="difficultyInput" class="ratingrow"></div>

</div>

<div class="field">

<label>画質</label>
<div id="qualityInput" class="ratingrow"></div>

</div>

</div>


<div class="field full">

<label>属性</label>

<div
id="attributeInput"
class="attribute-grid"
>

  <div
    class="attribute-item attribute-red"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-blue"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-yellow"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-green"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-orange"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-purple"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-pink"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-cyan"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-gray"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-brown"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-white"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

  <div
    class="attribute-item attribute-black"
  >
    <input type="checkbox">
    <input type="text" maxlength="20">
  </div>

</div>

</div>


<div class="field full">

<label>視聴日</label>


<div class="dates">

<input id="date1" type="date">
<input id="date2" type="date">
<input id="date3" type="date">

</div>

<span class="hint">
最大3回。保存時に最新の日付が左になります。
</span>

</div>

<div class="field full">

<label>メモ</label>

<textarea
id="fMemo"
class="memoArea"
rows="7"
></textarea>

</div>

<div class="field full">

<label>映画画像</label>

<div class="toolbar">

<button onclick="openImageSearch()">
ネットから取得
</button>

<button
class="secondary"
onclick="document.getElementById('posterFile').click()"
>
画像を指定
</button>

<input
id="posterFile"
type="file"
accept="image/*"
multiple
hidden
>

</div>

<div
id="posterBox"
class="imagebox"
></div>

</div>

</div>

</div>

</section>

<!-- =======================================================
     背景
======================================================= -->

<section
id="pageBackground"
class="hidden"
>

<div class="panel">

<div class="sectiontitle">
背景
</div>

<div class="settingline background-color-setting">

<b>背景カラー</b>

<div
id="backgroundColors"
class="colors"
></div>

</div>

<div class="settingline">

<b>背景透過</b>

<div>

<div
id="backgroundStrength"
class="choice-buttons"
></div>

<div
id="strengthHint"
class="hint"
style="margin-top:4px"
>
背景画像がないため現在は無効です。
</div>

</div>

</div>

<div class="sectiontitle">
背景画像
</div>

<div class="hint">
画像を指定するとアプリの背景になります。
</div>

<div
id="backgroundDrop"
class="drop-area"
style="margin-top:8px"
>

<div>

<button
  onclick="document.getElementById('backgroundFile').click()"
>
  画像を指定
</button>

<button
  class="secondary"
  onclick="clearBackground()"
>
  画像を消去
</button>

<button
  id="toggleBackground"
  class="secondary"
  type="button"
  onclick="toggleBackgroundVisibility()"
>
  背景画像を非表示
</button>

<div
class="hint"
style="margin-top:8px"
>
ここへ画像をドラッグ&ドロップすることもできます。
</div>

</div>

</div>

<input
id="backgroundFile"
type="file"
accept="image/*"
hidden
>

<img
id="backgroundPreview"
class="bg-preview hidden"
>

</div>

</section>

<!-- =======================================================
     設定
======================================================= -->

<section
    id="pageSettings"
    class="hidden"
>

    <div class="panel">

        <div class="settingline">

            <b>イメージカラー</b><br>

            <div
                id="mainColors"
                class="colors"
            ></div>

        </div>


        <div class="settingline">

            <b>ダークモード</b>

            <div
                id="darkModeChoices"
                class="choice-buttons"
            ></div>

        </div>


        <div class="sectiontitle">
            文字設定
        </div>

        <div class="hint">
            各項目は適用範囲が完全に独立しています。
            「設定」のサイズを変更しても、目録カードのタイトル・評・回や追加編集画面の文字サイズは変化しません。
        </div>

        <div id="fontSettings"></div>


        <div class="sectiontitle">
            データ
        </div>

        <div class="toolbar">

            <button
                type="button"
                onclick="showPage('ods')"
            >
                ODS読み込み
            </button>

            <input
                type="file"
                id="odsFileInput"
                accept=".ods"
                style="display:none"
            >

            <button
                class="danger"
                onclick="clearAll()"
            >
                全データ削除
            </button>

        </div>

        <div class="hint">
            ODSファイルから映画データを読み込みます。既存の映画はタイトルを基準に更新し、新しい映画は追加します。
        </div>

    </div>

</section>


<!-- =======================================================
     ODS読み取り
======================================================= -->

<section
    id="pageODS"
    class="hidden"
>

    <div class="panel">


        <!-- =====================================================
             ODS操作
        ===================================================== -->

        <div class="toolbar">

            <button
                class="secondary"
                onclick="showPage('settings')"
            >
                ← 設定に戻る
            </button>

            <b>ODS読み取り</b>

        </div>


        <div class="sectiontitle">
            ODS操作
        </div>

        <div class="toolbar">

            <button
                onclick="document.getElementById('odsFileInput').click()"
            >
                ODSを読み込む
            </button>

            <button
                type="button"
                onclick="exportMoviesToODS()"
            >
                ODSを出力する
            </button>

        </div>

        <div class="hint">
            ODSファイルを読み込むと、ODSの各列を映画管理帳の対応する項目へ反映します。
        </div>

        <div class="hint">
            ODSを出力すると、現在の映画データをODSファイルとして保存できます。
        </div>


        <!-- =====================================================
             ODSについて
        ===================================================== -->

        <div class="sectiontitle">
            ODSデータについて
        </div>

        <div class="backup-explain">

            <p>
                ODSファイルは、映画データを一括して読み込み・出力するために使用します。
            </p>

            <p>
                ODSの<strong>列名を基準</strong>にしてデータを読み込みます。
                列の位置だけではなく、列名によって対応する項目を判断します。
            </p>

            <p>
                既存の映画は<strong>タイトル</strong>を基準に更新し、
                新しいタイトルの映画は新規追加します。
            </p>

        </div>


        <!-- =====================================================
             ODS項目
        ===================================================== -->

        <div class="sectiontitle">
            ODSの項目と映画管理帳の対応
        </div>

        <div class="backup-explain">

            <p>
                <b>タイトル</b> → タイトル 
                <b>読み</b> → 読み 
                <b>時間</b> → 時間 
                <b>公開</b> → 公開 
                <b>ジャンル</b> → ジャンル
            </p>

            <p>
                <b>回数</b> → 回数 
                <b>評価</b> → 評価 
                <b>気楽</b> → 気楽 
                <b>不快</b> → 不快 
                <b>ABC</b> → ABC
            </p>

            <p>
                <b>難解</b> → 難解 
                <b>画質</b> → 画質 
                <b>視聴日1</b> → 最新の視聴日 
                <b>視聴日2</b> → 2番目に新しい視聴日 
                <b>視聴日3</b> → 3番目に新しい視聴日
            </p>

            <p>
                <b>メモ</b> → メモ 
                <b>製作国</b> → 製作国 
                <b>監督</b> → 監督 
                <b>主演</b> → 主演 
                <b>メーカー</b> → メーカー
            </p>

            <p>
                <b>画像</b> → 画像番号 
                <b>赤~黒</b> → 属性
            </p>

        </div>


        <!-- =====================================================
             画像
        ===================================================== -->

        <div class="sectiontitle">
            画像
        </div>

        <div class="backup-explain">

            <p>
                ODSの<strong>「画像」</strong>列には、映画に対応する画像番号を入力します。
            </p>

            <p>
                画像番号は4桁で管理します。
            </p>

            <div class="ods-example">
                0001 0002 0003 0004 ……
            </div>

            <p>
                例えば <code>1</code> と入力された場合も、
                アプリ内部では <code>0001</code> として管理します。
            </p>

            <p>
                画像番号を持つ映画を読み込むと、
                保存先フォルダの<strong>imagesフォルダ</strong>から
                対応する画像ファイルを自動認識します。
            </p>

        </div>


        <!-- =====================================================
             画像ファイル名
        ===================================================== -->

        <div class="sectiontitle">
            画像ファイル名の仕様
        </div>

        <div class="backup-explain">

            <p>
                例えば画像番号が <code>0001</code> の場合、
                <strong>0001を基準</strong>として画像ファイルを認識します。
            </p>

            <p>
                <strong>最優先されるのは画像番号そのもののファイル</strong>です。
            </p>

            <div class="ods-example">
                0001.jpg<br>
                0001.jpeg<br>
                0001.png<br>
                0001.webp
            </div>

            <p>
                これらのように <code>0001</code> だけで構成されたファイル名が存在する場合、
                これが最優先されます。
            </p>

            <p>
                さらに、画像番号の後ろに識別文字を付けたファイルも認識します。
            </p>

            <div class="ods-example">
                0001_01.jpg<br>
                0001_02.jpg<br>
                0001a.jpg<br>
                0001b.webp<br>
                0001-01.jpg
            </div>

            <p>
                一方、画像番号そのものが別の数字まで続くファイルは認識しません。
            </p>

            <div class="ods-example">
                00010.jpg ← 認識しない<br>
                0002.jpg ← 0001としては認識しない<br>
                10001.jpg ← 認識しない
            </div>

            <p>
                画像ファイルの拡張子は固定されません。
                JPG、JPEG、PNG、WebPなど、画像として扱える形式を使用できます。
            </p>

            <p>
                同じ画像番号を複数の映画が持っている場合は、
                <strong>同じ画像がそれぞれの映画に表示されます。</strong>
            </p>

        </div>


        <!-- =====================================================
             ジャンル
        ===================================================== -->

        <div class="sectiontitle">
            ジャンル
        </div>

        <div class="backup-explain">

            <p>
                ジャンルが複数ある場合は、
                <strong>全角スペース「 」</strong>で区切ります。
            </p>

            <div class="ods-example">
                アクション コメディ ドラマ
            </div>

            <p>
                この場合は、
                「アクション」「コメディ」「ドラマ」の3つのジャンルとして読み込まれます。
            </p>

        </div>


        <!-- =====================================================
             視聴日
        ===================================================== -->

        <div class="sectiontitle">
            視聴日
        </div>

        <div class="backup-explain">

            <p>
                視聴日は3つまで保存できます。
            </p>

            <p>
                <b>視聴日1</b> → 一番新しい視聴日<br>
                <b>視聴日2</b> → 2番目に新しい視聴日<br>
                <b>視聴日3</b> → 3番目に新しい視聴日
            </p>

            <p>
                ODSの「視聴日1~3」に日付が入っている場合は、
                日付を新しい順に整理して保存します。
            </p>

            <p>
                1つなら視聴日1、2つなら視聴日1・2、
                3つなら視聴日1・2・3として使用します。
            </p>

            <p>
                古いODS形式の<strong>「最終視聴日」</strong>にも対応しています。
            </p>

            <p>
                「視聴日1~3」に1つでも日付が入っている場合は、
                新しい形式を優先し、「最終視聴日」は使用しません。
            </p>

        </div>


        <!-- =====================================================
             属性
        ===================================================== -->

        <div class="sectiontitle">
            属性
        </div>

<p>
🟥 <b>赤</b> 
🟦 <b>青</b> 
🟨 <b>黄</b> 
🟩 <b>緑</b> 
🟧 <b>橙</b> 
🟪 <b>紫</b> 
🩷 <b>桃</b> 
🩵 <b>水</b> 
🔳 <b>灰</b> 
🟫 <b>茶</b> 
⬜ <b>白</b> 
⬛ <b>黒</b>
</p>

<p>
ODSでは、この12色の日本語名が属性の列名になります。
順番もこの順番で固定されています。
</p>
        <div class="backup-explain">

            <p>
                ODSで属性の欄に<strong>何か文字が入っていればON</strong>、
                空欄なら<strong>OFF</strong>として読み込みます。
            </p>

            <p>
                例として「赤」の欄に「○」or 「1」と入力されていれば赤属性がON(チェック)になるのみで
            </p>

 <p>
                ODSに入っている文字そのものは属性コメントとしては保存されません。
            </p>

        </div>

        <div class="backup-explain">

            <p>
                <strong>灰・茶・白・黒はチェック入れると通常一覧、目録で表示しなくなる隠し属性で絞り込みで選択したときのみ表示されます。</strong>
            </p>

            <p>
                隠し属性もODSでは通常の属性と同じように読み込み・出力できます。
            </p>

        </div>


        <!-- =====================================================
             属性コメント
        ===================================================== -->

        <div class="sectiontitle">
属性コメントについて
</div>

<div class="backup-explain">

<p>
属性コメントは、映画ごとに別々に保存されるものではありません。
<b>映画管理帳全体で共通</b>です。
</p>

<p>
例えば赤のコメントを「レッド」に設定したあと、
別の場所で赤のコメントを「あか」に変更すると、
赤のコメントはすべての映画で「あか」になります。
</p>

</div>


        <!-- =====================================================
             ODS列数
        ===================================================== -->

        <div class="sectiontitle">
            ODSの列数
        </div>

        <div class="backup-explain">

            <p>
                現在のODSは<strong>33列</strong>です。
            </p>

            <p>
                列の順番は次のとおりです。
            </p>

            <div class="ods-example">
                タイトル<br>
                読み<br>
                時間<br>
                公開<br>
                回数<br>
                評価<br>
                気楽<br>
                不快<br>
                ABC<br>
                難解<br>
                画質<br>
                視聴日1<br>
                視聴日2<br>
                視聴日3<br>
                メモ<br>
                製作国<br>
                監督<br>
                主演<br>
                メーカー<br>
                ジャンル<br>
                画像<br>
                赤<br>
                青<br>
                黄<br>
                緑<br>
                橙<br>
                紫<br>
                桃<br>
                水<br>
                灰<br>
                茶<br>
                白<br>
                黒
            </div>

        </div>


        <!-- =====================================================
             ODS出力
        ===================================================== -->

        <div class="sectiontitle">
            ODS出力について
        </div>

        <div class="backup-explain">

            <p>
                「ODSを出力する」を実行すると、
                現在の映画データを33列のODSファイルとして保存します。
            </p>

            <p>
                出力したODSファイルは、後から「ODSを読み込む」で読み込むことができます。
            </p>

            <p>
                既存の映画はタイトルを基準に更新され、
                新しい映画は追加されます。
            </p>

        </div>


    </div>

</section>

<!-- =======================================================
     ネット画像検索
======================================================= -->

<div
id="imageModal"
class="modal hidden"
>

<div class="modalbox">

<div class="toolbar">

<b>ネット画像取得</b>

<button
class="secondary"
onclick="closeImageSearch()"
>
閉じる
</button>

</div>

<div class="toolbar">

<input
id="imageQuery"
placeholder="映画タイトル"
>

<button onclick="searchImages()">
検索
</button>

</div>

<div class="hint">
画像を複数選択して登録できます。
</div>

<div
id="searchResults"
class="searchimgs"
style="margin-top:10px"
></div>

<div class="toolbar">

<button onclick="addSelectedImages()">
選択画像を登録
</button>

</div>

</div>

</div>

<!-- =======================================================
     一覧タイトル画像表示
======================================================= -->

<div
id="movieImageModal"
class="modal hidden"
>

<div class="movieImageModalBox">

<div class="toolbar">

<b id="movieImageModalTitle">
画像
</b>

<button
class="secondary"
onclick="closeMovieImageModal()"
>
閉じる
</button>

</div>

<div
id="movieImageView"
class="movieImageView"
></div>

</div>

</div>

<script>

/* =========================================================
   カラー
========================================================= */

const COLORS=[
  "#2563eb",
  "#7c3aed",
  "#db2777",
  "#dc2626",
  "#ea580c",
  "#ca8a04",
  "#16a34a",
  "#059669",
  "#0891b2",
  "#0f766e",
  "#475569",
  "#111827",
  "#64748b",
  "#06b6d4",
  "#10b981",
  "#eab308",
  "#f3f6fb",
];

/* =========================================================
   評価数字固定色
========================================================= */

const RATING_COLORS={
  1:"#6b7280",
  2:"#1683ff",
  3:"#13a538",
  4:"#ff4f91",
  5:"#a000ff"
};

/* =========================================================
   フォント
========================================================= */

const FONTS=[

{
name:"游ゴシック",
css:'"Yu Gothic",YuGothic,sans-serif'
},

{
name:"メイリオ",
css:'Meiryo,sans-serif'
},

{
name:"BIZ UDPゴシック",
css:'"BIZ UDPGothic","BIZ UDPゴシック",sans-serif'
},

{
name:"BIZ UDP明朝",
css:'"BIZ UDPMincho","BIZ UDP明朝",serif'
},

{
name:"MS Pゴシック",
css:'"MS PGothic","MS Pゴシック",sans-serif'
},

{
name:"MS P明朝",
css:'"MS PMincho","MS P明朝",serif'
}

];


/* =========================================================
   文字サイズ
========================================================= */

const FONT_SIZES=[
  "12px",
  "13px",
  "14px",
  "16px",
  "18px"
];

const HEADER_FONT_SIZES=[
  "13px",
  "16px",
  "19px",
  "22px",
  "26px"
];

/* =========================================================
   一覧サイズ
   1=極限まで詰める
   5=ゆったり
========================================================= */

const TABLE_SIZES=[

  {
    y:"0px",
    x:"0px",
    lineHeight:"0.1"
  },

  {
    y:"1px",
    x:"2px",
    lineHeight:"1.04"
  },

  {
    y:"4px",
    x:"5px",
    lineHeight:"1.08"
  },

  {
    y:"8px",
    x:"10px",
    lineHeight:"1.12"
  },

  {
    y:"14px",
    x:"16px",
    lineHeight:"1.15"
  }

];


/* =========================================================
   保存先フォルダ
========================================================= */

let movieFolderHandle=null;


/* =========================================================
   IndexedDB
========================================================= */

function openMovieFolderDB(){

  return new Promise(
    (resolve,reject)=>{

      const request=
        indexedDB.open(
          "movieManagementApp",
          1
        );

      request.onupgradeneeded=
        event=>{

          const db=
            event.target.result;

          if(
            !db.objectStoreNames.contains(
              "settings"
            )
          ){

            db.createObjectStore(
              "settings"
            );

          }

        };

      request.onsuccess=
        ()=>{
          resolve(
            request.result
          );
        };

      request.onerror=
        ()=>{
          reject(
            request.error
          );
        };

    }
  );

}


/* =========================================================
   保存済みFolderHandle読み込み
========================================================= */

async function loadMovieFolderHandle(){

  try{

    const db=
      await openMovieFolderDB();

    const handle=
      await new Promise(
        (resolve,reject)=>{

          const transaction=
            db.transaction(
              "settings",
              "readonly"
            );

          const store=
            transaction.objectStore(
              "settings"
            );

          const request=
            store.get(
              "movieFolder"
            );

          request.onsuccess=
            ()=>{
              resolve(
                request.result || null
              );
            };

          request.onerror=
            ()=>{
              reject(
                request.error
              );
            };

        }
      );

    db.close();

    if(
      handle &&
      handle.kind==="directory"
    ){

      movieFolderHandle=
        handle;

    }else{

      movieFolderHandle=null;

    }

  }catch(error){

    console.error(
      "保存先フォルダ情報の読み込みに失敗しました。",
      error
    );

    movieFolderHandle=null;

  }

}


/* =========================================================
   FolderHandle保存
========================================================= */

async function saveMovieFolderHandle(
  handle
){

  try{

    const db=
      await openMovieFolderDB();

    await new Promise(
      (resolve,reject)=>{

        const transaction=
          db.transaction(
            "settings",
            "readwrite"
          );

        const store=
          transaction.objectStore(
            "settings"
          );

        const request=
          store.put(
            handle,
            "movieFolder"
          );

        request.onsuccess=
          ()=>{
            resolve();
          };

        request.onerror=
          ()=>{
            reject(
              request.error
            );
          };

      }
    );

    db.close();

  }catch(error){

    console.error(
      "保存先フォルダ情報の保存に失敗しました。",
      error
    );

  }

}


/* =========================================================
   保存先フォルダ選択
========================================================= */

async function selectMovieFolder(){

  if(
    typeof window.showDirectoryPicker!=="function"
  ){

    alert(
      "このブラウザでは保存先フォルダ機能を利用できません。"
    );

    return false;

  }

  try{

    const handle=
      await window.showDirectoryPicker({
        id:"movie-management-folder",
        mode:"readwrite"
      });

    if(
      !handle ||
      handle.kind!=="directory"
    ){

      return false;

    }

    movieFolderHandle=
      handle;

    await saveMovieFolderHandle(
      handle
    );


    /*
      フォルダを新しく選択した直後に、
      そのフォルダ内の映画データと設定を読み込む。
    */

    await loadSettingsFromFolder();

    await loadMoviesFromFolder();


    /*
      読み込んだデータを画面へ反映する。
    */

    applySettings();

    renderAttributeFilter();

    renderSettings();

    renderBackground();

    renderList();

    renderItemList();


    return true;

  }catch(error){

    if(
      error &&
      error.name==="AbortError"
    ){

      return false;

    }

    console.error(
      "保存先フォルダの選択に失敗しました。",
      error
    );

    alert(
      "保存先フォルダの選択に失敗しました。"
    );

    return false;

  }

}


/* =========================================================
   保存先フォルダ確認
========================================================= */

async function ensureMovieFolder(){

  /*
    FolderHandleがない場合は、
    新しい保存先フォルダを選択する。
  */

  if(!movieFolderHandle){

    return await selectMovieFolder();

  }


  try{

    /*
      現在のアクセス権を確認。
    */

    let permission=
      await movieFolderHandle.queryPermission({
        mode:"readwrite"
      });


    /*
      許可されていない場合だけ、
      ブラウザへ許可を要求する。
    */

    if(permission!=="granted"){

      permission=
        await movieFolderHandle.requestPermission({
          mode:"readwrite"
        });

      if(permission!=="granted"){

        return false;

      }

    }


    /*
      実際にフォルダの中身へアクセスして、
      FolderHandleが現在も使用できるか確認する。

      「.」という名前のフォルダを探すのではなく、
      values()で実際にフォルダへアクセスする。
    */

    const iterator=
      movieFolderHandle.values();

    await iterator.next();


    /*
      ここまで到達したら、
      FolderHandleは使用可能。
    */

    return true;


  }catch(error){

    console.warn(
      "保存先フォルダへアクセスできません。新しいフォルダを選択します。",
      error
    );


    /*
      古いFolderHandleを破棄する。
    */

    movieFolderHandle=null;


    /*
      IndexedDBに残っている古いFolderHandleも削除する。
    */

    try{

      const db=
        await openMovieFolderDB();

      await new Promise(
        (resolve,reject)=>{

          const transaction=
            db.transaction(
              "settings",
              "readwrite"
            );

          const store=
            transaction.objectStore(
              "settings"
            );

          const request=
            store.delete(
              "movieFolder"
            );

          request.onsuccess=
            ()=>{
              resolve();
            };

          request.onerror=
            ()=>{
              reject(
                request.error
              );
            };

        }
      );

      db.close();

    }catch(dbError){

      console.error(
        "古い保存先フォルダ情報の削除に失敗しました。",
        dbError
      );

    }


    /*
      新しい保存先フォルダを選択する。
    */

    return await selectMovieFolder();

  }

}



/* =========================================================
   映画データ
========================================================= */

let movies=[];


/* =========================================================
   フォルダから映画データ読み込み
========================================================= */

async function loadMoviesFromFolder(){

  if(!movieFolderHandle){

    return false;

  }

  try{

    const fileHandle=
      await movieFolderHandle.getFileHandle(
        "movies.json"
      );

    const file=
      await fileHandle.getFile();

    const text=
      await file.text();

    const data=
      JSON.parse(text);

    if(!Array.isArray(data)){

      return false;

    }

    movies=data;


    /*
      imagesフォルダから、
      imageIdに対応する画像を自動認識する。

      例:
      imageId = "0001"

      認識:
      0001.jpg
      0001.jpeg
      0001.png
      0001.webp
      0001_00.jpg
      0001_01.jpg
      0001a.jpg

      認識しない:
      00010.jpg
      0002.jpg
      10001.jpg

      優先順位:
      1. imageId完全一致
      2. imageId + _ / - / . + 文字
      3. imageId + 英字
    */

    const imagesFolder=
      await getMovieImagesFolder();

    if(imagesFolder){

      for(
        const movie
        of movies
      ){

        const imageId=
          String(
            movie.imageId || ""
          ).trim();

        if(!imageId){

          continue;

        }

        const exactImages=[];
        const relatedImages=[];

        const escapedImageId=
          imageId.replace(
            /[.*+?^${}()|[\]\\]/g,
            "\\$&"
          );

        const relatedPattern=
          new RegExp(
            "^"+
            escapedImageId+
            "(?:[_\\-.]|[a-zA-Z]).*$",
            "i"
          );

        for await(
          const entry
          of imagesFolder.values()
        ){

          if(
            entry.kind!=="file"
          ){

            continue;

          }

          const fileName=
            entry.name;

          const dotIndex=
            fileName.lastIndexOf(".");

          if(dotIndex<=0){

            continue;

          }

          const baseName=
            fileName.slice(
              0,
              dotIndex
            );

          /*
            完全一致
          */

          if(
            baseName===imageId
          ){

            exactImages.push(
              fileName
            );

            continue;

          }

          /*
            imageIdの後ろに
            _ / - / . / 英字
            が続くもの
          */

          if(
            relatedPattern.test(
              baseName
            )
          ){

            relatedImages.push(
              fileName
            );

          }

        }

        /*
          完全一致を最優先。
          同じ種類のファイルが複数ある場合は
          ファイル名順にする。

          例:

          0001.jpg
          0001.jpeg
          0001_00.jpg
          0001_01.jpg
          0001a.jpg
        */

        exactImages.sort(
          (a,b)=>
            a.localeCompare(
              b,
              undefined,
              {
                numeric:true,
                sensitivity:"base"
              }
            )
        );

        relatedImages.sort(
          (a,b)=>
            a.localeCompare(
              b,
              undefined,
              {
                numeric:true,
                sensitivity:"base"
              }
            )
        );

        movie.images=[
          ...exactImages,
          ...relatedImages
        ];

      }

    }


    return true;

  }catch(error){

    if(
      error &&
      error.name==="NotFoundError"
    ){

      return false;

    }

    console.error(
      "movies.json の読み込みに失敗しました。",
      error
    );

    return false;

  }

}

/* =========================================================
   設定
========================================================= */

let settings={

  main:"#2563eb",

  bg:"#f3f6fb",

  cols:6,

  tableSize:3,

  titleWidth:4,

  strength:1,

  backgroundImageHidden:false,

  dark:false,

  fonts:{},

  colorOrder:[
    ...COLORS
  ],

  genreOrder:[]

};


/* =========================================================
   フォルダから設定読み込み
========================================================= */

async function loadSettingsFromFolder(){

  if(!movieFolderHandle){

    return false;

  }

  try{

    const fileHandle=
      await movieFolderHandle.getFileHandle(
        "settings.json"
      );

    const file=
      await fileHandle.getFile();

    const text=
      await file.text();

    const data=
      JSON.parse(text);

    if(
      !data ||
      typeof data!=="object" ||
      Array.isArray(data)
    ){

      return false;

    }

    settings=data;

        if(typeof settings.backgroundImageHidden!=="boolean"){
          settings.backgroundImageHidden=false;
        }

    return true;

  }catch(error){

    if(
      error &&
      error.name==="NotFoundError"
    ){

      return false;

    }

    console.error(
      "settings.json の読み込みに失敗しました。",
      error
    );

    return false;

  }

}


/* =========================================================
   設定の不足項目を補正
========================================================= */

if(
  !settings.fonts ||
  typeof settings.fonts!=="object"
){

  settings.fonts={};

}


if(!settings.cols){

  settings.cols=6;

}


if(
  !Number.isInteger(
    settings.tableSize
  ) ||
  settings.tableSize<1 ||
  settings.tableSize>5
){

  settings.tableSize=3;

}

if(
  !Number.isInteger(
    settings.tableSize
  ) ||
  settings.tableSize<1 ||
  settings.tableSize>5
){

  settings.tableSize=3;

}


if(
  !Number.isInteger(
    settings.titleWidth
  ) ||
  settings.titleWidth<1 ||
  settings.titleWidth>5
){

  settings.titleWidth=4;

}

if(!settings.strength){

  settings.strength=1;

}


if(!settings.main){

  settings.main="#2563eb";

}


if(!settings.bg){

  settings.bg="#f3f6fb";

}


if(
  typeof settings.dark!=="boolean"
){

  settings.dark=false;

}


if(
  !settings.attributeComments ||
  typeof settings.attributeComments!=="object"
){

  settings.attributeComments={};

}



/* =========================================================
   ジャンル並び順の初期化・互換
========================================================= */

function sortGenresForSave(genres){

  const collator=
    new Intl.Collator(
      "ja-JP",
      {
        numeric:true,
        sensitivity:"base"
      }
    );

  function category(genre){

    const first=
      String(genre)
        .trim()
        .charAt(0);

    if(/[0-90-9]/.test(first)){
      return 1;
    }

    if(/[A-Za-zA-Za-z]/.test(first)){
      return 2;
    }

    if(/[ぁ-ゖァ-ヺ]/.test(first)){
      return 3;
    }

    return 4;
  }

  return [...genres].sort(
    (a,b)=>{

      const ca=category(a);
      const cb=category(b);

      if(ca!==cb){
        return ca-cb;
      }

      return collator.compare(
        String(a),
        String(b)
      );

    }
  );

}

function normalizeGenreOrder(){

  let order=
    Array.isArray(settings.genreOrder)
    ? settings.genreOrder
    : [];

  const genres=[

    ...new Set(
      movies.flatMap(
        m=>
          Array.isArray(m.genres)
          ? m.genres
          : []
      )
    )

  ];

  order=
    order.filter(
      genre=>genres.includes(genre)
    );

  genres.forEach(
    genre=>{

      if(!order.includes(genre)){
        order.push(genre);
      }

    }
  );

  settings.genreOrder=order;

}

/* =========================================================
   カラー並び順の初期化・互換
========================================================= */

function normalizeColorOrder(){

  let order=
    Array.isArray(settings.colorOrder)
    ? settings.colorOrder
    : [];

  order=
    order.filter(
      color=>COLORS.includes(color)
    );

  COLORS.forEach(
    color=>{

      if(!order.includes(color)){
        order.push(color);
      }

    }
  );

  settings.colorOrder=order;

}

normalizeColorOrder();
normalizeGenreOrder();

let editId=null;
let posters=[];

/*
  編集前の画面を記録。
  目録から編集したら目録へ、
  一覧から編集したら一覧へ戻す。
*/
let editOriginPage="list";
let editOriginScrollY=0;

let currentMainPage="list";
let previousMainPage="list";

let sortDir=1;
let tableSortDir=1;

let selectedRatings=new Set();
let selectedEntertainment=new Set();
let selectedCounts=new Set();
let selectedGenres=new Set();

let selectedAttribute=null;


/* =========================================================
   ジャンル絞り込み開閉状態
========================================================= */

let genreFilterOpen=false;
let tableGenreFilterOpen=false;
let tableAttributeFilterOpen=false;

/* =========================================================
   $
========================================================= */

function $(id){
  return document.getElementById(id);
}

/* =========================================================
   エスケープ
========================================================= */

function esc(value=""){

  return String(value)
    .replace(/[&<>"']/g,m=>({

      "&":"&amp;",
      "<":"&lt;",
      ">":"&gt;",
      '"':"&quot;",
      "'":"&#39;"

    }[m]));

}

/* =========================================================
   保存
========================================================= */

function clearEditForm(){

  $("fTitle").value="";
  $("fReading").value="";
  $("fTime").value="0";
  $("fYear").value="";
  $("fCount").value="0";
  $("fGenre").value="";
  $("fMaker").value="";
  $("fCountry").value="";
  $("fDirector").value="";
  $("fCast").value="";
  $("fMemo").value="";

  $("date1").value="";
  $("date2").value="";
  $("date3").value="";

    posters=[];

 [
  "ratingInput",
  "entertainmentInput",
  "discomfortInput",
  "abcInput",
  "difficultyInput",
  "qualityInput"
].forEach(
  id=>setRating(id,"")
);

  const attributeItems =
    document.querySelectorAll(
      "#attributeInput .attribute-item"
    );

  attributeItems.forEach(
    item=>{

      const checkbox =
        item.querySelector(
          'input[type="checkbox"]'
        );

      const comment =
        item.querySelector(
          'input[type="text"]'
        );

      checkbox.checked=false;

     const color =
  [...item.classList]
    .find(
      name =>
        name !== "attribute-item" &&
        name.startsWith("attribute-")
    )
    ?.replace(
      "attribute-",
      ""
    );


      comment.value =
        settings.attributeComments[color] || "";

    }
  );


  renderPosters();

  autoDraft();


}

async function saveMovies(){

  /*
    保存先フォルダを確認する。

    FolderHandleが正常ならそのまま使用。
    フォルダが削除・移動などで使用できなくなっている場合は、
    ensureMovieFolder()側で古いHandleを破棄して
    新しいフォルダを選択する。
  */
  if(
    !await ensureMovieFolder()
  ){

    return;

  }

  try{

    const fileHandle =
      await movieFolderHandle.getFileHandle(
        "movies.json",
        {
          create:true
        }
      );

    const writable =
      await fileHandle.createWritable();

    await writable.write(
      JSON.stringify(
        movies,
        null,
        2
      )
    );

    await writable.close();

  }catch(error){

    console.error(
      "movies.json の保存に失敗しました。",
      error
    );

    alert(
      "movies.json の保存に失敗しました。\n\n"+
      error.name+
      "\n"+
      error.message
    );

  }

}

async function saveSettings(){

  /*
    保存先フォルダを確認する。

    FolderHandleが正常ならそのまま使用。
    使用できない場合は新しいフォルダを選択する。
  */
  if(
    !await ensureMovieFolder()
  ){

    return;

  }

  try{

    const fileHandle=
      await movieFolderHandle.getFileHandle(
        "settings.json",
        {
          create:true
        }
      );

    const writable=
      await fileHandle.createWritable();

    await writable.write(
      JSON.stringify(
        settings,
        null,
        2
      )
    );

    await writable.close();

  }catch(error){

    console.error(
      "settings.json の保存に失敗しました。",
      error
    );

  }

  applySettings();

}


/* =========================================================
   背景
========================================================= */

function hasBackground(){
      return !!(
        settings &&
        settings.backgroundFileName &&
        !settings.backgroundImageHidden
      );
    }


function applyBackgroundStrength(){

  const alphaValues=[
    1,
    .85,
    .70,
    .55,
    .40
  ];

  const index=
    Math.max(
      1,
      Math.min(
        5,
        Number(settings.strength)||1
      )
    )-1;

  const alpha=alphaValues[index];

  const finalAlpha=
    hasBackground()
    ? alpha
    : 1;

  document.documentElement.style.setProperty(
    "--panel-alpha",
    finalAlpha
  );

  document.documentElement.style.setProperty(
    "--card-alpha",
    finalAlpha
  );

}

/* =========================================================
   設定適用
========================================================= */

function applySettings(){

  const root=document.documentElement;

  root.style.setProperty(
    "--main",
    settings.main
  );

  /*
    メインカラーの明るさに応じて
    メインカラー上の文字色を自動調整する。

    明るい色 → 黒文字
    暗い色   → 白文字
  */
  const mainColor =
    String(settings.main || "#2563eb")
      .replace("#","");

  let mainTextColor="#ffffff";

  if(mainColor.length===6){

    const r=parseInt(
      mainColor.slice(0,2),
      16
    );

    const g=parseInt(
      mainColor.slice(2,4),
      16
    );

    const b=parseInt(
      mainColor.slice(4,6),
      16
    );

    const brightness=
      (r*299 + g*587 + b*114) / 1000;

    if(brightness>=180){
      mainTextColor="#18202a";
    }

  }

  root.style.setProperty(
    "--main-text",
    mainTextColor
  );

  root.style.setProperty(
    "--bg",
    settings.bg
  );

  root.style.setProperty(
    "--cols",
    settings.cols
  );

  const targets=[

    ["title","--title-size","--title-font"],

    ["meta","--meta-size","--meta-font"],

    ["form","--form-size","--form-font"],

    ["memo","--memo-size","--memo-font"],

    ["setting","--setting-size","--setting-font"],

    ["header","--header-size","--setting-font"],

    ["table","--table-size","--table-font"]

  ];

 targets.forEach(
  ([key,sizeVar,fontVar])=>{

    const s=getFontSetting(key);

    const sizeList =
      key === "header"
        ? HEADER_FONT_SIZES
        : FONT_SIZES;

    root.style.setProperty(
      sizeVar,
      sizeList[s.size]
    );

    root.style.setProperty(
      fontVar,
      FONTS[s.font].css
    );

  }
);

  const tableSize=
    Math.max(
      1,
      Math.min(
        5,
        Number(settings.tableSize)||3
      )
    );

  const tableSpacing=
    TABLE_SIZES[
      tableSize-1
    ];

  const titleWidth=
    Math.max(
      1,
      Math.min(
        5,
        Number(settings.titleWidth)||4
      )
    );

  const titleWidths=[
    "130px",
    "190px",
    "250px",
    "330px",
    "420px"
  ];

  root.style.setProperty(
    "--itemlist-title-width",
    titleWidths[
      titleWidth-1
    ]
  );

  root.style.setProperty(
    "--table-padding-y",
    tableSpacing.y
  );

  root.style.setProperty(
    "--table-padding-x",
    tableSpacing.x
  );

  root.style.setProperty(
    "--table-line-height",
    tableSpacing.lineHeight
  );

  root.classList.toggle(
    "dark",
    !!settings.dark
  );

  applyBackgroundStrength();

  updateTableStickyTop();

}

/* =========================================================
   フォント設定
========================================================= */

function getFontSetting(key){

  if(
    !settings.fonts[key] ||
    typeof settings.fonts[key]!=="object"
  ){

    settings.fonts[key]={
      size:0,
      font:0
    };

  }

  const s=settings.fonts[key];

  if(
    !Number.isInteger(s.size) ||
    s.size<0 ||
    s.size>4
  ){

    s.size=0;

  }

  if(
    !Number.isInteger(s.font) ||
    s.font<0 ||
    s.font>=FONTS.length
  ){

    s.font=0;

  }

  return s;

}

/* =========================================================
   一覧ヘッダー位置
========================================================= */

function updateTableStickyTop(){

  const header=
    document.querySelector("header");

  if(!header)return;

  document.documentElement.style.setProperty(
    "--table-sticky-top",
    header.offsetHeight+"px"
  );

}

/* =========================================================
   ページ
========================================================= */

function showPage(page){

if(page!=="edit" && page!==currentMainPage){
  previousMainPage=currentMainPage;
  currentMainPage=page;
}

  $("pageList").classList.toggle(
    "hidden",
    page!=="list"
  );

  $("pageTable").classList.toggle(
    "hidden",
    page!=="table"
  );

  $("pageEdit").classList.toggle(
    "hidden",
    page!=="edit"
  );

  $("pageBackground").classList.toggle(
    "hidden",
    page!=="background"
  );

  $("pageSettings").classList.toggle(
    "hidden",
    page!=="settings"
  );

  $("pageODS").classList.toggle(
    "hidden",
    page!=="ods"
  );

  document
    .querySelectorAll("nav button")

    .forEach(
      b=>b.classList.remove("active")
    );

  if(page==="list"){

    $("navList").classList.add("active");

    renderList();

  }

  if(page==="table"){

    $("navTable").classList.add("active");

    renderItemList();

    updateTableStickyTop();

  }

  if(page==="edit"){

    $("navAdd").classList.add("active");

  }

  if(page==="background"){

    $("navBg").classList.add("active");

    renderBackground();

  }

  if(page==="settings"){

    $("navSetting").classList.add("active");

    renderSettings();

  }

}

function goPreviousPage(){

  // 編集画面では、既存の戻る処理を利用
  if(!$("pageEdit").classList.contains("hidden")){
    returnFromEdit();
    return;
  }

  if(previousMainPage===currentMainPage){
    return;
  }

  showPage(previousMainPage);
}

/* =========================================================
   新規
========================================================= */

function newMovie(){

  editId=null;
  posters=[];

  /*
    「追加」から作成した新規映画は
    保存後に必ず目録へ戻る。
  */
/*
        新規編集でも、開く前の画面へ戻る。
      */
      editOriginPage=
        $("pageTable").classList.contains("hidden")
        ? "list"
        : "table";

      editOriginScrollY=window.scrollY || 0;

  clearForm();

  $("deleteBtn").classList.add(
    "hidden"
  );

  showPage("edit");

  restoreDraft();

}

/* =========================================================
   編集
========================================================= */

function editMovie(id){

  const movie=
    movies.find(
      m=>m.id===id
    );

  if(!movie)return;

  /*
    編集画面から◀▶で移動した場合は、
    元の画面と元のスクロール位置を
    上書きしない。

    最初に編集を開始したときだけ、
    元の画面を記録する。
  */
  const alreadyEditing=
    !$("pageEdit").classList.contains(
      "hidden"
    );

  if(!alreadyEditing){

    editOriginPage=
      $("pageTable").classList.contains("hidden")
      ? "list"
      : "table";

    editOriginScrollY=
      window.scrollY || 0;

  }

  editId=id;

  posters=[
    ...(Array.isArray(movie.images)
      ? movie.images
      : [])
  ];

  $("deleteBtn").classList.remove(
    "hidden"
  );

  fillForm(movie);

  showPage("edit");

}

function getEditNavigationIndex(){

  if(!editId){
    return -1;
  }

  const list =
    getEditNavigationMovies();

  return list.findIndex(
    movie =>
      String(movie.id) === String(editId)
  );

}

function editNextMovie(){

  const list =
    getEditNavigationMovies();

  const index =
    getEditNavigationIndex();

  if(index < 0){
    return;
  }

  if(index >= list.length - 1){
    return;
  }

  editMovie(
    list[index + 1].id
  );

}

function editPreviousMovie(){

  const list =
    getEditNavigationMovies();

  const index =
    getEditNavigationIndex();

  if(index <= 0){
    return;
  }

  editMovie(
    list[index - 1].id
  );

}


/* =========================================================
   編集画面から元の画面へ戻る
========================================================= */

function animateItemListRow(movieId){
  if(movieId===null || movieId===undefined)return;

  const button=document.querySelector(
    `[data-edit-id="${CSS.escape(String(movieId))}"]`
  );

  const row=button?.closest("tr");
  if(!row)return;

  row.classList.remove("itemlist-focus-line");
  void row.offsetWidth;
  row.classList.add("itemlist-focus-line");
}

function returnFromEdit(){

  showPage(editOriginPage || "list");

  requestAnimationFrame(
    ()=>{
      window.scrollTo(
  0,
  editOriginScrollY || 0
);

if(editOriginPage==="table" && editId){
  animateItemListRow(editId);
}

    }
  );

}

/* =========================================================
   フォーム
========================================================= */

function clearForm(){

  [
    "fTitle",
    "fReading",
    "fYear",
    "fGenre",
    "fMaker",
    "fCountry",
    "fDirector",
    "fCast",
    "fMemo",
    "date1",
    "date2",
    "date3"
  ].forEach(
    id=>{
      $(id).value="";
    }
  );

  $("fTime").value=0;

  $("fCount").value=0;

   [
    "ratingInput",
    "entertainmentInput",
    "discomfortInput",
    "abcInput",
    "difficultyInput",
    "qualityInput"
  ].forEach(
    id=>setRating(id,"")
  );

const attributeItems =
  document.querySelectorAll(
    "#attributeInput .attribute-item"
  );

attributeItems.forEach(
  item=>{

    const checkbox =
      item.querySelector(
        'input[type="checkbox"]'
      );

    const comment =
      item.querySelector(
        'input[type="text"]'
      );

    checkbox.checked=false;

    const color =
      [...item.classList]
        .find(
          name =>
            name !== "attribute-item" &&
            name.startsWith("attribute-")
        )
        ?.replace(
          "attribute-",
          ""
        );

    comment.value =
      settings.attributeComments[color] || "";

  }
);

  renderPosters();

}

function fillForm(m){

  $("fTitle").value=m.title || "";

  $("fReading").value=
    m.reading || "";

  $("fTime").value=
  m.time ?? 0;

  $("fYear").value=
    Number(m.year)||"";

  $("fCount").value=
    Number(m.count)||0;

  $("fGenre").value=
    (Array.isArray(m.genres)
      ? m.genres
      : []).join(" ");

  $("fMaker").value=
    m.maker || "";

  $("fCountry").value=
    m.country || "";

  $("fDirector").value=
    m.director || "";

  $("fCast").value=
    m.cast || "";

  $("fMemo").value=
    m.memo || "";

  putDates(
    Array.isArray(m.dates)
      ? m.dates
      : []
  );

  setRating(
  "ratingInput",
  m.rating
);

setRating(
  "entertainmentInput",
  m.entertainment
);

setRating(
  "discomfortInput",
  m.discomfort
);

  setRating(
    "abcInput",
    m.abc
  );

  setRating(
    "difficultyInput",
    m.difficulty
  );

  setRating(
    "qualityInput",
    m.quality
  );

  const attributes=
    Array.isArray(m.attributes)
      ? m.attributes
      : [];

  const attributeItems=
    document.querySelectorAll(
      "#attributeInput .attribute-item"
    );

  attributeItems.forEach(
    (item,index)=>{

      const data=
        attributes[index] || {};

      const color =
  [...item.classList]
    .find(
      name =>
        name !== "attribute-item" &&
        name.startsWith(
          "attribute-"
        )
    )
    ?.replace(
      "attribute-",
      ""
    );


      const checkbox=
        item.querySelector(
          'input[type="checkbox"]'
        );

      const comment=
        item.querySelector(
          'input[type="text"]'
        );

      checkbox.checked=
        data.checked===true;

      comment.value =
  settings.attributeComments[color] ||
  "";


    }
  );


  renderPosters();

}

/* =========================================================
   日付
========================================================= */

function sortDatesLatestFirst(dates){

  return dates
    .filter(Boolean)
    .sort(
      (a,b)=>
        new Date(b)-new Date(a)
    )
    .slice(0,3);

}

function putDates(dates){

  const sorted=
    sortDatesLatestFirst(
      [...dates]
    );

  $("date1").value=
    sorted[0] || "";

  $("date2").value=
    sorted[1] || "";

  $("date3").value=
    sorted[2] || "";

}

/* =========================================================
   1~5入力
========================================================= */

function setRating(id,value){

  const box=$(id);

  box.innerHTML="";

  const min =
    (id==="discomfortInput" || id==="abcInput")
    ? 0
    : 1;

  for(let i=min;i<=5;i++){

    const button=
      document.createElement("button");

    button.type="button";

    button.textContent=i;

    button.dataset.v=i;

if(
  value !== "" &&
  value !== null &&
  value !== undefined &&
  i === Number(value)
){

  button.classList.add("on");
}


    button.addEventListener(
      "click",
      ()=>{

        box
          .querySelectorAll("button")
          .forEach(
            b=>b.classList.remove("on")
          );

        button.classList.add("on");

        autoDraft();

      }
    );

    box.appendChild(button);

  }

}

function ratingValue(id){

  const active=
    document.querySelector(
      "#"+id+" .on"
    );

  if(!active){
    return "";
  }

  return Number(
    active.dataset.v
  );
}


 /* =========================================================
    保存
 ========================================================= */

 async function saveMovie(){

   /*
     まず保存先フォルダを確保する。
   */
   if(
     !await ensureMovieFolder()
   ){

     return;

   }


   /*
     タイトル確認
   */
   const title=
     $("fTitle")
       .value
       .trim();

   if(!title){

     alert(
       "タイトルを入力してください。"
     );

     return;

   }


   /*
     ========================================================
     重要
     ========================================================

     保存前に、フォルダ内の既存movies.jsonを必ず読む。

     Edge側にデータが1件あっても、
     フォルダ側にはChromeで作った過去データがある。

     そのため、

       フォルダの過去データ
       +
       現在Edgeにあるデータ

     を合体させてから保存する。
   */

   let folderMovies=[];

   try{

     const fileHandle=
       await movieFolderHandle.getFileHandle(
         "movies.json"
       );

     const file=
       await fileHandle.getFile();

     const text=
       await file.text();

     const data=
       JSON.parse(text);

     if(Array.isArray(data)){

       folderMovies=data;

     }

   }catch(error){

     /*
       movies.jsonが存在しない場合は、
       新規フォルダとして扱う。
     */

     if(
       error &&
       error.name!=="NotFoundError"
     ){

       console.error(
         "既存movies.jsonの読み込みに失敗しました。",
         error
       );

       alert(
         "既存のmovies.jsonを読み込めませんでした。\n\n"+
         error.name+
         "\n"+
         error.message
       );

       return;

     }

   }


   /*
     ========================================================
     フォルダデータと現在のアプリデータを統合
     ========================================================

     同じIDなら現在のアプリ側を優先。
     違うIDなら両方残す。
   */

   const mergedMovies=[];

   const movieMap=
     new Map();


   /*
     まずフォルダ側の過去データを入れる。
   */

   folderMovies.forEach(
     movie=>{

       if(
         movie &&
         movie.id
       ){

         movieMap.set(
           movie.id,
           movie
         );

       }

     }
   );


   /*
     次に現在Edge側にあるデータを入れる。

     これにより、Edgeで登録した1件も残る。
   */

   movies.forEach(
     movie=>{

       if(
         movie &&
         movie.id
       ){

         movieMap.set(
           movie.id,
           movie
         );

       }

     }
   );


   movieMap.forEach(
     movie=>{

       mergedMovies.push(
         movie
       );

     }
   );


   /*
     現在のmoviesを統合済みデータへ変更。
   */

   movies=
     mergedMovies;


   /*
     保存前に新規か編集かを記録。
   */

   const isNew=!editId;


   /*
     映画ID
   */

   const movieId=
     editId ||
     (
       crypto.randomUUID
       ? crypto.randomUUID()
       : Date.now().toString()
     );


   /*
     視聴日
   */

   const dates=
     sortDatesLatestFirst([

       $("date1").value,
       $("date2").value,
       $("date3").value

     ]);


   /*
     属性コメントを保存
   */

   const attributeItems=
     [
       ...document.querySelectorAll(
         "#attributeInput .attribute-item"
       )
     ];

   attributeItems.forEach(
     item=>{

       const color=
         [...item.classList]
           .find(
             name=>
               name!=="attribute-item" &&
               name.startsWith("attribute-")
           )
           ?.replace(
             "attribute-",
             ""
           );

       if(!color){

         return;

       }

       const comment=
         item.querySelector(
           'input[type="text"]'
         );

       const value=
         comment
           ? comment.value
           : "";

       if(value){

         settings.attributeComments[color]=
           value;

       }

     }
   );


   /*
     映画データ作成
   */

   const movie={

     id:movieId,

     title:title,

     reading:
       $("fReading")
         .value
         .trim(),

     time:
  $("fTime").value.trim(),


     year:
       Math.max(
         0,
         Number(
           $("fYear").value || 0
         )
       ),

     count:
       Math.max(
         0,
         Number(
           $("fCount").value || 0
         )
       ),

     genres:
       sortGenresForSave(
         $("fGenre")
           .value
           .split(" ")
           .map(
             x=>x.trim()
           )
           .filter(Boolean)
       ),

     maker:
       $("fMaker")
         .value
         .trim(),

     country:
       $("fCountry")
         .value
         .trim(),

     director:
       $("fDirector")
         .value
         .trim(),

     cast:
       $("fCast")
         .value
         .trim(),

     memo:
       $("fMemo").value,

     dates:dates,

     rating:
  ratingValue(
    "ratingInput"
  ),

entertainment:
  ratingValue(
    "entertainmentInput"
  ),

discomfort:
  ratingValue(
    "discomfortInput"
  ),

     abc:
       ratingValue(
         "abcInput"
       ),

     difficulty:
       ratingValue(
         "difficultyInput"
       ),

     quality:
       ratingValue(
         "qualityInput"
       ),

     attributes:[
       ...document.querySelectorAll(
         "#attributeInput .attribute-item"
       )
     ].map(
       item=>{

         const checkbox=
           item.querySelector(
             'input[type="checkbox"]'
           );

         const color=
           [...item.classList]
             .find(
               name=>
                 name!=="attribute-item" &&
                 name.startsWith("attribute-")
             )
             ?.replace(
               "attribute-",
               ""
             );

         return{

           color:color,

           checked:
             checkbox
               ? checkbox.checked
               : false

         };

       }
     ),

     images:[
       ...posters
     ]

   };


   /*
     ========================================================
     画像保存
     ========================================================
   */

   const imageFiles=[];

   for(
     let index=0;
     index<posters.length;
     index++
   ){

     const image=
       posters[index];


     /*
       新しく追加された画像
     */

     if(
       typeof image==="string" &&
       image.startsWith("data:")
     ){

       const response=
         await fetch(image);

       const blob=
         await response.blob();

       const extension=
         blob.type.includes("/")
         ? blob.type.split("/")[1]
         : "jpg";

       const file=
         new File(
           [blob],
           movieId+
           "_"+
           index+
           "."+
           extension,
           {
             type:blob.type
           }
         );

       const fileName=
         await saveImageFile(
           file,
           movieId,
           index
         );

       if(fileName){

         imageFiles.push(
           fileName
         );

       }

     }


     /*
       既存画像
     */

     else if(
       typeof image==="string" &&
       image
     ){

       imageFiles.push(
         image
       );

     }

   }


   movie.images=
     imageFiles;


   /*
     ========================================================
     今回の映画を統合済みmoviesへ反映
     ========================================================
   */

   if(editId){

     movies=
       movies.map(
         m=>
           m.id===editId
           ? movie
           : m
       );

   }else{

     movies.push(
       movie
     );

   }


   /*
     ジャンル順を正規化
   */

   normalizeGenreOrder();


   /*
     ========================================================
     保存
     ========================================================
   */

   await saveMovies();

   await saveSettings();


   /*
  ========================================================
  正式保存成功後、対応する下書きを削除
  ========================================================
*/

clearTimeout(
  draftTimer
);

try{

  const draftFileHandle=
    await movieFolderHandle.getFileHandle(
      "draft.json"
    );

  const draftFile=
    await draftFileHandle.getFile();

  const draftText=
    await draftFile.text();

  if(draftText){

    const savedDraft=
      JSON.parse(
        draftText
      );

    /*
      同じ映画の下書きなら削除する。
      新規保存の場合は id が空の下書きも削除する。
    */
    if(
      savedDraft.id === movieId ||
      (
        isNew &&
        !savedDraft.id
      )
    ){

      await movieFolderHandle.removeEntry(
        "draft.json"
      );

    }

  }

}catch(error){

  if(
    !error ||
    error.name!=="NotFoundError"
  ){

    console.error(
      "保存後のdraft.json削除に失敗しました。",
      error
    );

  }

}

 /*
     ========================================================
     新規追加
     ========================================================
   */

if(isNew){

  selectedRatings.clear();
  selectedCounts.clear();
  selectedGenres.clear();

  $("search").value="";

  showPage("table");

  requestAnimationFrame(()=>{
    const editButton=document.querySelector(
      `[data-edit-id="${CSS.escape(String(movieId))}"]`
    );

    const row=editButton?.closest("tr");

    if(row){
      const header=document.querySelector("header");
      const headerHeight=header
        ? header.offsetHeight
        : 0;

      const tableHeader=document.querySelector(
        ".itemlist-table thead"
      );

      const tableHeaderHeight=tableHeader
        ? tableHeader.offsetHeight
        : 0;

      const rowTop=
        row.getBoundingClientRect().top+
        window.scrollY;

      window.scrollTo(
        0,
        Math.max(
          0,
          rowTop-
          headerHeight-
          tableHeaderHeight-
          6
        )
      );

      animateItemListRow(movieId);
    }
  });

  return;
}

/*
  ========================================================
  編集
  保存後は「一覧」へ戻る。
  一覧から編集した場合は、
  編集した映画の位置までスクロールする。
  映画の並び順・movies.jsonの順番は変更しない。
  ========================================================
*/

showPage(
  "table"
);

requestAnimationFrame(
  ()=>{
    
    /*
      一覧から編集した場合だけ、
      編集した映画の位置までスクロールする。
    */
    if(
      editOriginPage==="table" &&
      editId
    ){

      const editButton=
        document.querySelector(
          `[data-edit-id="${CSS.escape(String(editId))}"]`
        );

      if(editButton){

        const row=
          editButton.closest("tr");

        if(row){

          const header=
            document.querySelector("header");

          const headerHeight=
            header
            ? header.offsetHeight
            : 0;

          const tableHeader=
            document.querySelector(
              ".itemlist-table thead"
            );

          const tableHeaderHeight=
            tableHeader
            ? tableHeader.offsetHeight
            : 0;

          const rowTop=
            row.getBoundingClientRect().top+
            window.scrollY;

          window.scrollTo(
            0,
            Math.max(
              0,
              rowTop-
              headerHeight-
              tableHeaderHeight-
              6
            )
          );

animateItemListRow(editId);

        }

      }

    }else{

      /*
        一覧以外からの編集は、
        従来どおり先頭へ戻す。
      */
      window.scrollTo(
        0,
        0
      );

    }

  }
);

}

/* =========================================================
   ODS読み込み
========================================================= */

$("odsFileInput").addEventListener(
  "change",
  async event=>{

    const file=
      event.target.files[0];

    if(!file){
      return;
    }

    try{

      const buffer=
        await file.arrayBuffer();

      const workbook=
        XLSX.read(
          buffer,
          {
            type:"array"
          }
        );

      const sheetName=
        workbook.SheetNames[0];

      const sheet=
        workbook.Sheets[sheetName];

      const rows=
        XLSX.utils.sheet_to_json(
          sheet,
          {
            defval:""
          }
        );

      if(!rows.length){

        alert(
          "ODSにデータがありません。"
        );

        return;

      }

      const result=
        importMoviesFromODS(rows);

      saveMovies();
      saveSettings();

      renderList();
      renderItemList();

      alert(
        "ODSを読み込みました。\n\n"+
        "追加:"+result.added+"本\n"+
        "更新:"+result.updated+"本"
      );

    }catch(error){

      console.error(error);

      alert(
        "ODSの読み込みに失敗しました。"
      );

    }finally{

      event.target.value="";

    }

  }
);


/* =========================================================
   ODS → 映画データ
========================================================= */

function importMoviesFromODS(rows){

  let added=0;
  let updated=0;

  rows.forEach(
    row=>{

      const title=
        String(
          row["タイトル"] || ""
        ).trim();

      if(!title){
        return;
      }

      const existing=
        movies.find(
          movie=>
            String(movie.title || "")
              .trim()===title
        );

      const movieData={

  title:title,

  imageId:
  (() => {

    const value=
      String(
        row["画像"] ?? ""
      )
      .trim()
      .replace(/\D/g,"");

    return value
      ? value.padStart(4,"0").slice(-4)
      : "";

  })(),

  time:
    String(
      row["時間"] ?? ""
    ).trim(),

        year:
          numberValue(
            row["公開"]
          ),

                genres:
          parseODSGenres(
            row["ジャンル"]
          ),

        attributes:[
          {
            color:"red",
            checked:
              String(
                row["赤"] ?? ""
              ).trim()!==""
          },
          {
            color:"blue",
            checked:
              String(
                row["青"] ?? ""
              ).trim()!==""
          },
          {
            color:"yellow",
            checked:
              String(
                row["黄"] ?? ""
              ).trim()!==""
          },
          {
            color:"green",
            checked:
              String(
                row["緑"] ?? ""
              ).trim()!==""
          },
          {
            color:"orange",
            checked:
              String(
                row["橙"] ?? ""
              ).trim()!==""
          },
          {
            color:"purple",
            checked:
              String(
                row["紫"] ?? ""
              ).trim()!==""
          },
          {
            color:"pink",
            checked:
              String(
                row["桃"] ?? ""
              ).trim()!==""
          },
          {
            color:"cyan",
            checked:
              String(
                row["水"] ?? ""
              ).trim()!==""
          },
          {
            color:"gray",
            checked:
              String(
                row["灰"] ?? ""
              ).trim()!==""
          },
          {
            color:"brown",
            checked:
              String(
                row["茶"] ?? ""
              ).trim()!==""
          },
          {
            color:"white",
            checked:
              String(
                row["白"] ?? ""
              ).trim()!==""
          },
          {
            color:"black",
            checked:
              String(
                row["黒"] ?? ""
              ).trim()!==""
          }
        ],

        count:
          numberValue(
            row["回数"]
          ),


        rating:
  numberValue(
    row["評価"]
  ),

entertainment:
  emptyNumberValue(
    row["気楽"]
  ),

discomfort:
  emptyNumberValue(
    row["不快"]
  ),

abc:
  emptyNumberValue(
    row["ABC"]
  ),


        difficulty:
          numberValue(
            row["難解"]
          ),

        quality:
          numberValue(
            row["画質"]
          ),

        dates:
  (
    [
      row["視聴日1"],
      row["視聴日2"],
      row["視聴日3"]
    ]
      .map(value => String(value ?? "").trim())
      .filter(value => value !== "")
      .length > 0
  )
    ? sortDatesLatestFirst(
        [
          row["視聴日1"],
          row["視聴日2"],
          row["視聴日3"]
        ]
          .map(value => String(value ?? "").trim())
          .filter(value => value !== "")
      ).slice(0,3)
    : parseODSDates(
        row["最終視聴日"]
      ),



        memo:
          String(
            row["メモ"] || ""
           ),

        maker:
          String(
            row["メーカー"] || ""
          ).trim(),

        country:
          String(
            row["製作国"] || ""
          ).trim(),

        director:
          String(
            row["監督"] || ""
          ).trim(),

        cast:
          String(
            row["主演"] || ""
          ).trim(),

        reading:
          String(
            row["読み"] || ""
          ).trim()

      };

      if(existing){

        /*
          画像などODSに存在しない情報は
          既存データを維持する。
        */

        Object.assign(
          existing,
          movieData
        );

        updated++;

      }else{

        movies.push({

          id:
            crypto.randomUUID
            ? crypto.randomUUID()
            : Date.now().toString()
              +"_"+Math.random(),

          ...movieData,

          images:[]

        });

        added++;

      }

    }
  );

  normalizeGenreOrder();

  return {
    added:added,
    updated:updated
  };

}

function exportMoviesToODS(){

  const headers = [

    "タイトル",
    "読み",
    "時間",
    "公開",
    "回数",
    "評価",
    "気楽",
    "不快",
    "ABC",
    "難解",
    "画質",
   "視聴日1",
"視聴日2",
"視聴日3",
"メモ",
"ジャンル",
"製作国",
"監督",
    "主演",
    "メーカー",
    "画像",
    "赤",
    "青",
    "黄",
    "緑",
    "橙",
    "紫",
    "桃",
    "水",
    "灰",
    "茶",
    "白",
    "黒"

  ];


  const rows = [headers];

const exportMovies = [...movies].sort((a, b) => {
  const x = a.reading || "";
  const y = b.reading || "";

  return String(x).localeCompare(
    String(y),
    "ja",
    {
      numeric: true,
      sensitivity: "base"
    }
  );
});

exportMovies.forEach(movie => {

      const dates =
        Array.isArray(movie.dates)
        ? sortDatesLatestFirst(
            movie.dates
          ).slice(0,3)
        : [];


      const attributes =
        Array.isArray(movie.attributes)
        ? movie.attributes
        : [];


      const attributeValue =
        color=>{

          const attr =
            attributes.find(
              a=>
                a &&
                a.color===color
            );

          return(
            attr &&
            attr.checked
          )
          ? "○"
          : "";

        };


      rows.push([

        movie.title || "",

        movie.reading || "",

        movie.time || "",

        movie.year || "",

        movie.count ?? "",

        movie.rating ?? "",

        movie.entertainment ?? "",

        movie.discomfort ?? "",

        movie.abc ?? "",

        movie.difficulty ?? "",

        movie.quality ?? "",

        dates[0] || "",
dates[1] || "",
dates[2] || "",

movie.memo || "",
Array.isArray(movie.genres)
  ? movie.genres.join(" ")
  : "",
movie.country || "",
movie.director || "",

movie.cast || "",
movie.maker || "",
movie.imageId || "",

        /*
          属性
          従来仕様のまま
        */

        attributeValue("red"),
        attributeValue("blue"),
        attributeValue("yellow"),
        attributeValue("green"),
        attributeValue("orange"),
        attributeValue("purple"),
        attributeValue("pink"),
        attributeValue("cyan"),
        attributeValue("gray"),
        attributeValue("brown"),
        attributeValue("white"),
        attributeValue("black")

      ]);

    }
  );


  const worksheet =
    XLSX.utils.aoa_to_sheet(
      rows
    );


  const workbook =
    XLSX.utils.book_new();


  XLSX.utils.book_append_sheet(
    workbook,
    worksheet,
    "映画データ"
  );


  XLSX.writeFile(
    workbook,
    "film管理データ.ods",
    {
      bookType:"ods"
    }
  );

}

/* =========================================================
   ODS数値
========================================================= */

function numberValue(value){

  const n=
    Number(
      String(value)
        .replace(/,/g,"")
        .trim()
    );

  return Number.isFinite(n)
    ? Math.max(0,n)
    : 0;

}

function emptyNumberValue(value){

  const text=
    String(
      value ?? ""
    )
    .replace(/,/g,"")
    .trim();

  if(text===""){
    return "";
  }

  const n=
    Number(text);

  return Number.isFinite(n)
    ? Math.max(0,n)
    : "";

}

/* =========================================================
   ODSジャンル
   全角スペースだけで複数ジャンル
========================================================= */

function parseODSGenres(value){

  return sortGenresForSave(
    String(
      value || ""
    )
    .trim()
    .split(" ")
    .map(
      genre=>
        genre.trim()
    )
    .filter(Boolean)
  );

}



/* =========================================================
   ODS最終視聴日
========================================================= */

function parseODSDates(value){

  if(
    value===null ||
    value===undefined ||
    value===""
  ){

    return [];

  }

  /*
    ODS / Excel のシリアル日付
  */

  if(
    typeof value==="number"
  ){

    const date=
      XLSX.SSF.parse_date_code(
        value
      );

    if(date){

      const y=
        String(date.y);

      const m=
        String(date.m)
          .padStart(2,"0");

      const d=
        String(date.d)
          .padStart(2,"0");

      return [
        `${y}-${m}-${d}`
      ];

    }

  }

  /*
    文字列の日付を
    YYYY-MM-DD に統一
  */

  const text=
    String(value)
      .trim();

  if(!text){
    return [];
  }

  const match=
    text.match(
      /^(\d{4})[\/\-.年](\d{1,2})[\/\-.月](\d{1,2})日?$/
    );

  if(match){

    const y=match[1];

    const m=
      String(match[2])
        .padStart(2,"0");

    const d=
      String(match[3])
        .padStart(2,"0");

    return [
      `${y}-${m}-${d}`
    ];

  }

  return [text];

}


/* =========================================================
   削除
========================================================= */

function deleteMovie(){

  if(!editId)return;

  if(
    confirm(
      "この映画を削除しますか?"
    )
  ){

    movies=
      movies.filter(
        m=>m.id!==editId
      );

    normalizeGenreOrder();

    saveMovies();
    saveSettings();

    showPage(
  editOriginPage === "table"
    ? "table"
    : "list"
);

  }

}

/* =========================================================
   絞り込み共通
========================================================= */

function filterMovies(searchValue=""){

  const q=
    String(searchValue)
      .trim()
      .toLowerCase();

  return movies.filter(
    movie=>{

      const text=[
        movie.title,
        movie.reading,
        movie.maker,
        movie.country,
        movie.director,
        movie.cast,
        movie.memo,
        ...(Array.isArray(movie.genres)
          ? movie.genres
          : [])
      ]
      .join(" ")
      .toLowerCase();


      if(
        q &&
        !text.includes(q)
      ){

        return false;

      }


      if(
        selectedRatings.size &&
        !selectedRatings.has(
          String(
            movie.rating || 0
          )
        )
      ){

        return false;

      }

if(
  selectedEntertainment.size &&
  !selectedEntertainment.has(
    String(
      movie.entertainment || 0
    )
  )
){

  return false;

}

            if(
        selectedCounts.size
      ){

        const count=
          Number(
            movie.count || 0
          );

        const countMatch=
          [...selectedCounts]
            .some(
              value=>{
                if(value==="5-10"){
                  return (
                    count>=5 &&
                    count<=10
                  );
                }

                if(value==="11-"){
                  return count>=11;
                }

                return (
                  count===
                  Number(value)
                );
              }
            );

        if(!countMatch){
          return false;
        }

      }



      /*
        ジャンル絞り込み

        選択されたジャンルが1つでもある場合、
        映画がそのジャンルを1つでも持っていれば表示する。
      */

      if(
        selectedGenres.size
      ){

        const movieGenres=
          Array.isArray(movie.genres)
          ? movie.genres.map(
              genre=>
                String(genre)
          )
          : [];

        const hasGenre=
          [...selectedGenres]
            .some(
              genre=>
                movieGenres.includes(
                  String(genre)
                )
            );

        if(!hasGenre){

          return false;

        }

      }


      if(
        selectedAttribute &&
        !(
          Array.isArray(movie.attributes)
            ? movie.attributes
            : []
        )[[
          "red",
          "blue",
          "yellow",
          "green",
          "orange",
          "purple",
          "pink",
          "cyan",
          "gray",
          "brown",
          "white",
          "black"
        ].indexOf(selectedAttribute)]
          ?.checked
      ){

        return false;

      }


      /*
        隠し属性

        灰・茶・白・黒が設定されている映画は、
        属性絞り込みをしていない通常表示では隠す。
      */

      if(!selectedAttribute){

        const attributes=
          Array.isArray(movie.attributes)
            ? movie.attributes
            : [];

        if(
          attributes.some(
            attribute=>
              attribute &&
              (
                attribute.color==="gray" ||
                attribute.color==="brown" ||
                attribute.color==="white" ||
                attribute.color==="black"
              ) &&
              attribute.checked===true
          )
        ){

          return false;

        }

      }


      return true;

    }
  );

}


function getEditNavigationMovies(){

  const search =
    $("tableSearch")?.value || "";

  let list =
    filterMovies(search);

  const type =
    $("tableSort").value;

  list.sort(
    (a,b)=>{

      let x="";
      let y="";
      let numeric=false;

      if(type==="reading"){

        x=a.reading || "";
        y=b.reading || "";

      }

      if(type==="time"){

        x=Number(
          a.time || 0
        );

        y=Number(
          b.time || 0
        );

        numeric=true;

      }

      if(type==="year"){

        x=Number(
          a.year || 0
        );

        y=Number(
          b.year || 0
        );

        numeric=true;

      }

      if(type==="date"){

        x=
          Array.isArray(a.dates) &&
          a.dates[0]
          ? new Date(a.dates[0]).getTime()
          : 0;

        y=
          Array.isArray(b.dates) &&
          b.dates[0]
          ? new Date(b.dates[0]).getTime()
          : 0;

        numeric=true;

      }

      if(type==="count"){

        x=Number(
          a.count || 0
        );

        y=Number(
          b.count || 0
        );

        numeric=true;

      }

      if(type==="rating"){

        x=Number(
          a.rating || 0
        );

        y=Number(
          b.rating || 0
        );

        numeric=true;

      }

      if(type==="entertainment"){

        x=Number(
          a.entertainment || 0
        );

        y=Number(
          b.entertainment || 0
        );

        numeric=true;

      }

      if(type==="discomfort"){

        x=Number(
          a.discomfort || 0
        );

        y=Number(
          b.discomfort || 0
        );

        numeric=true;

      }

      if(type==="abc"){

        x=Number(
          a.abc || 0
        );

        y=Number(
          b.abc || 0
        );

        numeric=true;

      }

      if(type==="difficulty"){

        x=Number(
          a.difficulty || 0
        );

        y=Number(
          b.difficulty || 0
        );

        numeric=true;

      }

      if(type==="quality"){

        x=Number(
          a.quality || 0
        );

        y=Number(
          b.quality || 0
        );

        numeric=true;

      }

      if(type==="country"){

        x=a.country || "";
        y=b.country || "";

      }

      if(type==="maker"){

        x=a.maker || "";
        y=b.maker || "";

      }

      if(numeric){

        return (
          x-y
        )*tableSortDir;

      }

      return String(x)
        .localeCompare(
          String(y),
          "ja",
          {
            numeric:true,
            sensitivity:"base"
          }
        )*tableSortDir;

    }
  );

  return list;

}


/* =========================================================
   目録
========================================================= */

function renderAttributeFilter(){

  const box=$("attributeChoices");

  if(!box){
    return;
  }

  box.innerHTML="";

  const colors=[
    "red",
    "blue",
    "yellow",
    "green",
    "orange",
    "purple",
    "pink",
    "cyan",
    "gray",
    "brown",
    "white",
    "black"
  ];

  colors.forEach(
    color=>{

      const button=
        document.createElement("button");

      button.type="button";

      button.className=
  "filterButton attribute-filter-button attribute-" + color;

      const comment=
        settings.attributeComments &&
        settings.attributeComments[color]
          ? settings.attributeComments[color]
          : "";

      button.textContent=
        comment.slice(0,3);

     button.dataset.color=color;

button.addEventListener(
  "click",
  ()=>{

    if(selectedAttribute===color){

      selectedAttribute=null;

    }else{

      selectedAttribute=color;

    }

    renderList();
    renderItemList();

  }
);

box.appendChild(button);


    }
  );

}

function renderList(){

  let list=
    filterMovies(
      $("search").value
    );

  const type=
    $("sort").value;

  list.sort(
  (a,b)=>{

    let x="";
    let y="";
    let numeric=false;

    if(type==="reading"){

      x=a.reading || "";
      y=b.reading || "";

    }

    if(type==="time"){

      x=Number(
        String(a.time ?? "")
          .split("/")[0]
      ) || 0;

      y=Number(
        String(b.time ?? "")
          .split("/")[0]
      ) || 0;

      numeric=true;

    }

    if(type==="year"){

      x=Number(
        a.year || 0
      );

      y=Number(
        b.year || 0
      );

      numeric=true;

    }

    if(type==="date"){

      x=
        Array.isArray(a.dates) &&
        a.dates[0]
        ? new Date(a.dates[0]).getTime()
        : 0;

      y=
        Array.isArray(b.dates) &&
        b.dates[0]
        ? new Date(b.dates[0]).getTime()
        : 0;

      numeric=true;

    }

    if(type==="count"){

      x=Number(
        a.count || 0
      );

      y=Number(
        b.count || 0
      );

      numeric=true;

    }

    if(type==="rating"){

      x=Number(
        a.rating || 0
      );

      y=Number(
        b.rating || 0
      );

      numeric=true;

    }

    if(type==="entertainment"){

      x=Number(
        a.entertainment || 0
      );

      y=Number(
        b.entertainment || 0
      );

      numeric=true;

    }

    if(type==="discomfort"){

      x=Number(
        a.discomfort || 0
      );

      y=Number(
        b.discomfort || 0
      );

      numeric=true;

    }

    if(type==="abc"){

      x=Number(
        a.abc || 0
      );

      y=Number(
        b.abc || 0
      );

      numeric=true;

    }

    if(type==="difficulty"){

      x=Number(
        a.difficulty || 0
      );

      y=Number(
        b.difficulty || 0
      );

      numeric=true;

    }

    if(type==="quality"){

      x=Number(
        a.quality || 0
      );

      y=Number(
        b.quality || 0
      );

      numeric=true;

    }

    if(type==="country"){

      x=a.country || "";
      y=b.country || "";

    }

    if(type==="maker"){

      x=a.maker || "";
      y=b.maker || "";

    }

    if(numeric){

      return (
        x-y
      )*sortDir;

    }

    return String(x)
      .localeCompare(
        String(y),
        "ja",
        {
          numeric:true,
          sensitivity:"base"
        }
      )*sortDir;

  }
);

  $("resultCount").textContent=
    list.length+"本";


  /*
    目録では画像ファイル名を直接srcに入れず、
    imagesフォルダから画像を読み込む。
  */
  $("movieGrid").innerHTML="";


    Promise.all(
    list.map(
      async movie=>{

        const image=
          Array.isArray(movie.images)
          ? movie.images[0]
          : null;

        const imageUrl=
          image
          ? await loadMovieImage(image)
          : "";


        const rating=
          Number(movie.rating || 0);


        const timeValue =
          String(movie.time ?? "");

        const time =
          timeValue.includes("/")
            ? timeValue.split("/")[0] + "/"
            : timeValue;


        const ratingClass=
          rating>=1 && rating<=5
          ? "rating-"+rating
          : "";


        const card=
          document.createElement(
            "div"
          );

        card.className="card";

        card.dataset.id=
          movie.id;


        const poster=
          imageUrl
          ?
          `<img
            class="poster"
            src="${esc(imageUrl)}"
            alt=""
          >`
          :
          `<div class="no-poster">
            🎬
          </div>`;


        card.innerHTML=`

          ${poster}

          <div class="cardbody">

            <div
              class="cardtitle"
              title="${esc(movie.title)}"
            >${esc(movie.title)}</div>

            <div class="cardstats">

              <div class="cardstat rating">

                <span
                  class="cardstat-number rating-number ${ratingClass}"
                >
                  ${
                    rating
                    ? rating
                    : "-"
                  }
                </span>

                <span class="cardstat-label">
                  評
                </span>

              </div>

              <div class="cardstat time">

                <span class="cardstat-number">
                  ${time}
                </span>

                <span class="cardstat-label">
                  分
                </span>

              </div>

            </div>

          </div>

        `;


        card.addEventListener(
          "click",
          ()=>{
            editMovie(
              card.dataset.id
            );
          }
        );

        return card;

      }
    )
  ).then(
    cards=>{

      cards.forEach(
        card=>{
          $("movieGrid")
            .appendChild(card);
        }
      );

      equalizeCardTitleRows();

      renderFilters();

    }
  );

}


function renderTableAttributeFilter(){

  const box=$("tableAttributeChoices");

  if(!box){
    return;
  }

  box.innerHTML="";

  const colors=[
    "red",
    "blue",
    "yellow",
    "green",
    "orange",
    "purple",
    "pink",
    "cyan",
    "gray",
    "brown",
    "white",
    "black"
  ];

  box.classList.toggle(
    "open",
    tableAttributeFilterOpen
  );

  colors.forEach(
    color=>{

      const button=
        document.createElement("button");

      button.type="button";

      button.className=
        "filterButton attribute-filter-button attribute-" +
        color +
        (
          selectedAttribute===color
            ? " selected"
            : ""
        );

      const comment=
        settings.attributeComments &&
        settings.attributeComments[color]
          ? settings.attributeComments[color]
          : "";

      if(selectedAttribute===color){

        button.textContent="👻";

        button.classList.add(
          "attribute-selected-mark"
        );

      }else{

        button.textContent=
          comment.slice(0,3);

        button.classList.remove(
          "attribute-selected-mark"
        );

      }

      button.dataset.color=color;

      button.addEventListener(
        "click",
        ()=>{

          if(selectedAttribute===color){

            selectedAttribute=null;

          }else{

            selectedAttribute=color;

          }

          renderFilters();

          renderList();
          renderItemList();

        }
      );

      box.appendChild(button);

    }
  );

}


/* =========================================================
   完全新規:項目一覧
========================================================= */

function renderItemList(){

  const body=
    $("itemlistBody");

  let list=
    filterMovies(
      $("tableSearch").value
    );

  const type=
    $("tableSort").value;

  list.sort(
  (a,b)=>{

    let x="";
    let y="";
    let numeric=false;

    if(type==="reading"){

      x=a.reading || "";
      y=b.reading || "";

    }

    if(type==="time"){

      x=Number(
        String(a.time ?? "")
          .split("/")[0]
      ) || 0;

      y=Number(
        String(b.time ?? "")
          .split("/")[0]
      ) || 0;

      numeric=true;

    }

    if(type==="year"){

      x=Number(
        a.year || 0
      );

      y=Number(
        b.year || 0
      );

      numeric=true;

    }

    if(type==="date"){

      x=
        Array.isArray(a.dates) &&
        a.dates[0]
        ? new Date(a.dates[0]).getTime()
        : 0;

      y=
        Array.isArray(b.dates) &&
        b.dates[0]
        ? new Date(b.dates[0]).getTime()
        : 0;

      numeric=true;

    }

    if(type==="count"){

      x=Number(
        a.count || 0
      );

      y=Number(
        b.count || 0
      );

      numeric=true;

    }

    if(type==="rating"){

      x=Number(
        a.rating || 0
      );

      y=Number(
        b.rating || 0
      );

      numeric=true;

    }

    if(type==="entertainment"){

      x=Number(
        a.entertainment || 0
      );

      y=Number(
        b.entertainment || 0
      );

      numeric=true;

    }

    if(type==="discomfort"){

      x=Number(
        a.discomfort || 0
      );

      y=Number(
        b.discomfort || 0
      );

      numeric=true;

    }

    if(type==="abc"){

      x=Number(
        a.abc || 0
      );

      y=Number(
        b.abc || 0
      );

      numeric=true;

    }

    if(type==="difficulty"){

      x=Number(
        a.difficulty || 0
      );

      y=Number(
        b.difficulty || 0
      );

      numeric=true;

    }

    if(type==="quality"){

      x=Number(
        a.quality || 0
      );

      y=Number(
        b.quality || 0
      );

      numeric=true;

    }

    if(type==="country"){

      x=a.country || "";
      y=b.country || "";

    }

    if(type==="maker"){

      x=a.maker || "";
      y=b.maker || "";

    }

    if(numeric){

      return (
        x-y
      )*tableSortDir;

    }

    return String(x)
      .localeCompare(
        String(y),
        "ja",
        {
          numeric:true,
          sensitivity:"base"
        }
      )*tableSortDir;

  }
);

  $("tableResultCount").textContent=
    list.length+"本";

  if(!list.length){

    body.innerHTML=`

      <tr>

        <td
          colspan="13"
          class="itemlist-empty"
        >
          登録されている映画はありません。
        </td>

      </tr>

    `;

    renderFilters();

    return;

  }

  body.innerHTML=
    list.map(
      movie=>{

        const rating=
          Number(movie.rating || 0);

        const ratingClass=
          rating>=1 && rating<=5
          ? "rating-"+rating
          : "";

        const dates=
          sortDatesLatestFirst(
            Array.isArray(movie.dates)
            ? [...movie.dates]
            : []
          );

        const genres=
          Array.isArray(movie.genres)
          ? movie.genres.join(" ")
          : "";

        const images=
          Array.isArray(movie.images)
          ? movie.images.filter(Boolean)
          : [];

        const title=
          esc(movie.title || "");

        const titleHtml=
          images.length
          ?
          `
            <button
  type="button"
  class="itemlist-title-button"
  data-image-id="${esc(movie.id)}"
  title="${esc(movie.title || "")}"
>

              ${title}
            </button>
          `
          :
          `
            <span
  class="itemlist-title-plain"
  title="${esc(movie.title || "")}"
>
  ${title}
</span>


          `;

        return `

          <tr>

            <td class="itemlist-edit">

              <button
                type="button"
                data-edit-id="${esc(movie.id)}"
                title="編集"
                aria-label="編集"
              >
                ✎
              </button>

            </td>

            <td class="itemlist-title">
              ${titleHtml}
            </td>

            <td class="itemlist-time">
  ${esc(
  String(movie.time ?? "").includes("/")
    ? String(movie.time ?? "").split("/")[0] + "/"
    : String(movie.time ?? "")
)}

</td>

 <td class="itemlist-year">
  ${
    Number(movie.year || 0)
    || "-"
  }
</td>


            <td class="itemlist-genres">
              ${esc(genres)}
            </td>

            <td class="itemlist-number">
              ${Number(movie.count || 0)}
            </td>

           <td class="itemlist-rating rating-number ${ratingClass}"
>
  ${rating || "-"}
</td>

<td class="itemlist-number">
  ${
    movie.entertainment === ""
    || movie.entertainment === null
    || movie.entertainment === undefined
    ? "-"
    : movie.entertainment
  }
</td>

<td class="itemlist-number">
  ${
    movie.discomfort === ""
    || movie.discomfort === null
    || movie.discomfort === undefined
    ? "-"
    : movie.discomfort
  }
</td>

<td class="itemlist-number">
  ${
    movie.abc === ""
    || movie.abc === null
    || movie.abc === undefined
    ? "-"
    : movie.abc
  }
</td>

<td class="itemlist-number">
  ${Number(movie.difficulty || 0) || "-"}
</td>

<td class="itemlist-number">
  ${Number(movie.quality || 0) || "-"}
</td>

<td class="itemlist-dates">
  ${
    dates.length
    ? esc(dates[0])
    : "-"
  }
</td>

<td
  class="itemlist-memo"
  title="${esc((movie.memo || "").trim())}"
>
  ${esc((movie.memo || "").trim()) || "-"}
</td>

          </tr>

        `;

      }
    ).join("");

  body
    .querySelectorAll(
      "[data-edit-id]"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          ()=>{
            editMovie(
              button.dataset.editId
            );
          }
        );

      }
    );

  body
    .querySelectorAll(
      "[data-image-id]"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          event=>{

            event.stopPropagation();

            openMovieImages(
              button.dataset.imageId
            );

          }
        );

      }
    );

  renderFilters();

  updateTableStickyTop();

}

/* =========================================================
   完全新規:一覧から画像表示
========================================================= */

async function openMovieImages(id){

  const movie=
    movies.find(
      m=>m.id===id
    );

  if(!movie)return;

  const images=
    Array.isArray(movie.images)
    ? movie.images.filter(Boolean)
    : [];

  if(!images.length){
    return;
  }

  const imageUrls=
    await Promise.all(
      images.map(
        image=>
          loadMovieImage(image)
      )
    );

  const validImageUrls=
    imageUrls.filter(Boolean);

  if(!validImageUrls.length){
    return;
  }

  $("movieImageModalTitle").textContent=
    movie.title || "画像";

  $("movieImageView").innerHTML=
    validImageUrls.map(
      image=>`

        <img
          src="${esc(image)}"
          alt=""
        >

      `
    ).join("");

  $("movieImageModal")
    .classList.remove(
      "hidden"
    );

}

function closeMovieImageModal(){

  $("movieImageModal")
    .classList.add(
      "hidden"
    );

  $("movieImageView").innerHTML="";

}

/* =========================================================
   カードタイトル行ごとの高さ統一
========================================================= */

function equalizeCardTitleRows(){

  const grid=$("movieGrid");

  if(!grid)return;

  const cards=[
    ...grid.querySelectorAll(".card")
  ];

  const titles=
    cards.map(
      card=>card.querySelector(".cardtitle")
    );

  titles.forEach(
    title=>{
      title.style.minHeight="";
      title.style.height="";
    }
  );

  if(!titles.length)return;

  const gridStyle=
    getComputedStyle(grid);

  const columns=
    parseInt(
      gridStyle.gridTemplateColumns
        .split(" ")
        .length,
      10
    );

  if(!columns || columns<1)return;

  for(
    let start=0;
    start<titles.length;
    start+=columns
  ){

    const row=
      titles.slice(
        start,
        start+columns
      );

    let max=0;

    row.forEach(
      title=>{
        max=Math.max(
          max,
          title.scrollHeight
        );
      }
    );

    row.forEach(
      title=>{
        title.style.height=max+"px";
      }
    );

  }

}

/* =========================================================
   絞り込み
========================================================= */

function renderAttributeFilter(){

  const box =
    $("attributeChoices");

  if(!box){
    return;
  }

  box.innerHTML="";

  const colors = [
    "red",
    "blue",
    "yellow",
    "green",
    "orange",
    "purple",
    "pink",
    "cyan",
    "gray",
    "brown",
    "white",
    "black"
  ];

if(attributeFilterOpen){

  box.style.display="flex";

}else{

  box.style.display="none";

}

  colors.forEach(
    color=>{

      const button =
        document.createElement("button");

      button.type="button";

      button.className=
  "filterButton attribute-filter-button attribute-" +
  color +
  (
    selectedAttribute===color
      ? " selected"
      : ""
  );



      const comment =
        settings.attributeComments &&
        settings.attributeComments[color]
          ? settings.attributeComments[color]
          : "";

      if(selectedAttribute===color){

  button.textContent="👻";
  button.classList.add("attribute-selected-mark");

}else{

  button.textContent=
    comment.slice(0,3);

  button.classList.remove(
    "attribute-selected-mark"
  );

}


button.dataset.color=color;


button.addEventListener(
  "click",
  ()=>{

    if(selectedAttribute===color){

      selectedAttribute=null;

    }else{

      selectedAttribute=color;

    }

    renderList();
    renderItemList();

  }
);

box.appendChild(button);


    }
  );

}


function renderFilters(){

    const ratings=[
    ...new Set(
      movies
        .map(
          m=>Number(m.rating)
        )
        .filter(
          value=>value >= 1
        )
        .map(
          value=>String(value)
        )
    )
  ].sort(
    (a,b)=>
      Number(a)-Number(b)
  );

const entertainments=[
  ...new Set(
    movies
      .map(
        m=>Number(
          m.entertainment
        )
      )
      .filter(
        value=>value>=1
      )
      .map(
        value=>String(value)
      )
  )
].sort(
  (a,b)=>
    Number(a)-Number(b)
);

    const counts=[
    "0",
    "1",
    "2",
    "3",
    "4",
    "5-10",
    "11-"
  ];


  normalizeGenreOrder();

  const genres=
    [...settings.genreOrder];

renderAttributeFilter();

renderTableAttributeFilter();

  renderFilterButtons(
    "ratingChoices",
    ratings,
    selectedRatings,
    renderList
  );

renderFilterButtons(
  "entertainmentChoices",
  entertainments,
  selectedEntertainment,
  renderList
);

  renderFilterButtons(
    "countChoices",
    counts,
    selectedCounts,
    renderList
  );

  renderFilterButtons(
    "genreChoices",
    genres,
    selectedGenres,
    renderList,
    true
  );

  renderFilterButtons(
    "tableRatingChoices",
    ratings,
    selectedRatings,
    renderItemList
  );

renderFilterButtons(
  "tableEntertainmentChoices",
  entertainments,
  selectedEntertainment,
  renderItemList
);

  renderFilterButtons(
    "tableCountChoices",
    counts,
    selectedCounts,
    renderItemList
  );

  renderFilterButtons(
    "tableGenreChoices",
    genres,
    selectedGenres,
    renderItemList,
    true
  );

 $("genreChoices").classList.toggle(
  "open",
  genreFilterOpen
);

$("attributeChoices").classList.toggle(
  "open",
  attributeFilterOpen
);

$("tableGenreChoices").classList.toggle(
  "open",
  tableGenreFilterOpen
);

}

function renderFilterButtons(
  id,
  values,
  selected,
  callback,
  draggable=false
){

  const box=$(id);

  if(!box)return;

  box.innerHTML="";

  let draggedIndex=-1;

  values.forEach(
    (value,index)=>{

      const button=
        document.createElement(
          "button"
        );

      button.type="button";

      button.className=
        "filterButton"+
        (
          selected.has(
            String(value)
          )
          ? " selected"
          : ""
        );

      button.textContent=value;

      if(draggable){

        button.draggable=true;

        button.addEventListener(
          "dragstart",
          event=>{

            draggedIndex=index;

            button.classList.add(
              "dragging"
            );

            event.dataTransfer.effectAllowed=
              "move";

          }
        );

        button.addEventListener(
          "dragend",
          ()=>{

            draggedIndex=-1;

            button.classList.remove(
              "dragging"
            );

            box
              .querySelectorAll(".filterButton")
              .forEach(
                item=>{
                  item.classList.remove(
                    "dragover"
                  );
                }
              );

          }
        );

        button.addEventListener(
          "dragover",
          event=>{

            event.preventDefault();

            if(
              draggedIndex!==index
            ){

              button.classList.add(
                "dragover"
              );

            }

            event.dataTransfer.dropEffect=
              "move";

          }
        );

        button.addEventListener(
          "dragleave",
          ()=>{
            button.classList.remove(
              "dragover"
            );
          }
        );

        button.addEventListener(
          "drop",
          event=>{

            event.preventDefault();

            button.classList.remove(
              "dragover"
            );

            if(
              draggedIndex!==index
            ){

              moveGenreOrder(
                draggedIndex,
                index
              );

            }

          }
        );

      }

      button.addEventListener(
        "click",
        ()=>{

          const v=
            String(value);

          if(
            selected.has(v)
          ){

            selected.delete(v);

          }else{

            selected.add(v);

          }

          callback();

        }
      );

      box.appendChild(button);

    }
  );

}

function moveGenreOrder(fromIndex,toIndex){

  if(
    fromIndex===toIndex ||
    fromIndex<0 ||
    toIndex<0
  ){

    return;

  }

  const order=[
    ...settings.genreOrder
  ];

  const moved=
    order.splice(
      fromIndex,
      1
    )[0];

  if(!moved){
    return;
  }

  order.splice(
    toIndex,
    0,
    moved
  );

  settings.genreOrder=
    order;

  saveSettings();

  renderList();

  renderItemList();

}

function resetRatings(){

  selectedRatings.clear();

  renderList();
  renderItemList();

}

function resetEntertainment(){

  selectedEntertainment.clear();
  renderList();
  renderItemList();

}

function resetCounts(){

  selectedCounts.clear();

  renderList();
  renderItemList();

}

function resetGenres(){

  selectedGenres.clear();

  renderList();
  renderItemList();

}

function resetFilters(){

  selectedRatings.clear();
selectedEntertainment.clear();
selectedCounts.clear();
selectedGenres.clear();


  $("search").value="";

  if($("tableSearch")){
    $("tableSearch").value="";
  }

  renderList();

  renderItemList();

}

/* =========================================================
   目録:表示切り替え
========================================================= */

let showTitle = true;
let showInfo = true;

$("showTitleButton").addEventListener(
  "click",
  ()=>{

    showTitle =
      !showTitle;

    updateListDisplay();

  }
);

$("showInfoButton").addEventListener(
  "click",
  ()=>{

    showInfo =
      !showInfo;

    updateListDisplay();

  }
);

function updateListDisplay(){

  $("showTitleButton")
    .classList.toggle(
      "selected",
      showTitle
    );

  $("showInfoButton")
    .classList.toggle(
      "selected",
      showInfo
    );

  $("movieGrid")
    .classList.toggle(
      "hide-title",
      !showTitle
    );

  $("movieGrid")
    .classList.toggle(
      "hide-info",
      !showInfo
    );

}

function toggleListControls(){

  const box=$("listControls");

  if(!box)return;

  box.classList.toggle(
    "hidden"
  );

  const button =
    box.previousElementSibling
      ?.querySelector(
        'button[onclick="toggleListControls()"]'
      );

  if(button){

    button.textContent =
      box.classList.contains("hidden")
      ? "▼ 検索欄開閉"
      : "▲ 検索欄開閉";

  }

}

function toggleTableControls(){

  const box=$("tableControls");

  if(!box)return;

  box.classList.toggle(
    "hidden"
  );

  const button =
    box.previousElementSibling
      ?.querySelector(
        'button[onclick="toggleTableControls()"]'
      );

  if(button){

    button.textContent =
      box.classList.contains("hidden")
      ? "▼ 検索欄開閉"
      : "▲ 検索欄開閉";

  }

}


function resetTableFilters(){

  selectedRatings.clear();
selectedEntertainment.clear();
selectedCounts.clear();
selectedGenres.clear();

  $("tableSearch").value="";

  renderItemList();

  renderList();

}

function toggleDirection(){

  sortDir*=-1;

  renderList();

}

function toggleTableDirection(){

  tableSortDir*=-1;

  renderItemList();

}

let attributeFilterOpen=false;

/* =========================================================
   ジャンル開閉
========================================================= */

$("attributeToggle").addEventListener(
  "click",
  ()=>{

    attributeFilterOpen=
      !attributeFilterOpen;

    renderFilters();

  }
);


$("genreToggle").addEventListener(
  "click",
  ()=>{

    genreFilterOpen=
      !genreFilterOpen;

    renderFilters();

  }
);

$("tableAttributeToggle").addEventListener(
  "click",
  ()=>{
    tableAttributeFilterOpen=
      !tableAttributeFilterOpen;

    renderFilters();

  }
);

$("tableGenreToggle").addEventListener(
  "click",
  ()=>{

    tableGenreFilterOpen=
      !tableGenreFilterOpen;

    renderFilters();

  }
);

$("ratingClear").addEventListener(
  "click",
  resetRatings
);

$("entertainmentClear").addEventListener(
  "click",
  resetEntertainment
);

$("countClear").addEventListener(
  "click",
  resetCounts
);

$("genreClear").addEventListener(
  "click",
  resetGenres
);

$("attributeClear").addEventListener(
  "click",
  ()=>{
    selectedAttribute=null;

    renderList();
    renderItemList();
  }
);

$("tableRatingClear").addEventListener(
  "click",
  resetRatings
);

$("tableEntertainmentClear").addEventListener(
  "click",
  resetEntertainment
);

$("tableCountClear").addEventListener(
  "click",
  resetCounts
);

$("tableAttributeClear").addEventListener(
  "click",
  ()=>{
    selectedAttribute=null;

    renderFilters();

    renderList();
    renderItemList();

  }
);

$("tableGenreClear").addEventListener(
  "click",
  resetGenres
);

$("search").addEventListener(
  "input",
  renderList
);

$("sort").addEventListener(
  "change",
  renderList
);

$("tableSearch").addEventListener(
  "input",
  renderItemList
);

$("tableSort").addEventListener(
  "change",
  renderItemList
);

/* =========================================================
   ポスター
========================================================= */

async function loadMovieImage(
  fileName
){

  if(!fileName){

    return "";

  }

  if(
    typeof fileName==="string" &&
    fileName.startsWith("data:")
  ){

    return fileName;

  }

  if(!movieFolderHandle){

    return "";

  }

  try{

    const imagesFolder=
      await getMovieImagesFolder();

    if(!imagesFolder){

      return "";

    }

    const fileHandle=
      await imagesFolder.getFileHandle(
        fileName
      );

    const file=
      await fileHandle.getFile();

    return URL.createObjectURL(
      file
    );

  }catch(error){

    console.error(
      "画像の読み込みに失敗しました。",
      error
    );

    return "";

  }

}

async function renderPosters(){

  const imageUrls=
    await Promise.all(
      posters.map(
        image=>
          loadMovieImage(image)
      )
    );

  $("posterBox").innerHTML=
    imageUrls.map(
      (image,index)=>`

        <div class="thumb">

          <img
            src="${esc(image)}"
            alt=""
          >

          <button
            type="button"
            data-index="${index}"
          >
            ×
          </button>

        </div>

      `
    ).join("");

  document
    .querySelectorAll(
      "#posterBox .thumb button"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          event=>{

            event.stopPropagation();

            const index=
              Number(
                button.dataset.index
              );

            posters.splice(
              index,
              1
            );

            renderPosters();

            autoDraft();

          }
        );

      }
    );

}

function fileData(file){

  return new Promise(
    (resolve,reject)=>{

      const reader=
        new FileReader();

      reader.onload=
        ()=>resolve(
          reader.result
        );

      reader.onerror=reject;

      reader.readAsDataURL(file);

    }
  );

}

/* =========================================================
   画像フォルダ
========================================================= */

async function getMovieImagesFolder(){

  if(!movieFolderHandle){

    return null;

  }

  try{

    const permission =
      await movieFolderHandle.queryPermission({
        mode:"readwrite"
      });

    if(permission!=="granted"){

      const requested =
        await movieFolderHandle.requestPermission({
          mode:"readwrite"
        });

      if(requested!=="granted"){

        console.error(
          "保存先フォルダへの書き込み権限がありません。"
        );

        return null;

      }

    }

    const imagesFolder=
      await movieFolderHandle.getDirectoryHandle(
        "images",
        {
          create:true
        }
      );

    return imagesFolder;

  }catch(error){

    console.error(
      "imagesフォルダの取得に失敗しました。",
      error
    );

    return null;

  }

}

async function saveImageFile(
  file,
  movieId,
  index
){

  const imagesFolder=
    await getMovieImagesFolder();

  if(!imagesFolder){

    return null;

  }

  try{

    const extension=
      file.name.includes(".")
      ? file.name
          .split(".")
          .pop()
          .toLowerCase()
      : "jpg";

    const fileName=
      movieId+
      "_"+
      index+
      "."+
      extension;

    const fileHandle=
      await imagesFolder.getFileHandle(
        fileName,
        {
          create:true
        }
      );

    const writable=
      await fileHandle.createWritable();

    await writable.write(file);

    await writable.close();

    return fileName;

  }catch(error){

    console.error(
      "画像ファイルの保存に失敗しました。",
      error
    );

    return null;

  }

}

$("posterFile").addEventListener(
  "change",
  async event=>{

    for(
      const file
      of event.target.files
    ){

      if(
        file.type.startsWith(
          "image/"
        )
      ){

        posters.push(
          await fileData(file)
        );

      }

    }

    renderPosters();

    event.target.value="";

    autoDraft();

  }
);

/* =========================================================
   ネット画像
========================================================= */

function openImageSearch(){

  $("imageModal")
    .classList.remove(
      "hidden"
    );

  $("imageQuery").value=
    $("fTitle").value;

}

function closeImageSearch(){

  $("imageModal")
    .classList.add(
      "hidden"
    );

}

async function searchImages(){

  const query=
    $("imageQuery")
      .value
      .trim();

  if(!query)return;

  $("searchResults").innerHTML=
    "検索中…";

  try{

    const url=
      "https://commons.wikimedia.org/w/api.php"
      +"?origin=*"
      +"&action=query"
      +"&generator=search"
      +"&gsrsearch="
+encodeURIComponent(
  query+" film"
)

      +"&gsrnamespace=6"
      +"&gsrlimit=30"
      +"&prop=imageinfo|categories"
      +"&iiprop=url|mime"
      +"&format=json";

    const response=
      await fetch(url);

    const data=
      await response.json();

    const pages=
      Object.values(
        data.query?.pages || {}
      );

    const images=
      pages.filter(
        page=>
          page.imageinfo?.[0]
            ?.mime
            ?.startsWith(
              "image/"
            )
      );


    if(!images.length){

      $("searchResults").innerHTML=
        "画像が見つかりませんでした。";

      return;

    }

    $("searchResults").innerHTML="";

    images.forEach(
      page=>{

        const url=
          page.imageinfo[0].url;

        const item=
          document.createElement(
            "div"
          );

        item.className=
          "searchimg";

        item.dataset.url=
          url;

        const img=
          document.createElement(
            "img"
          );

        img.src=url;

        img.loading="lazy";

        item.appendChild(img);

        item.addEventListener(
          "click",
          ()=>{
            item.classList.toggle(
              "selected"
            );
          }
        );

        $("searchResults")
          .appendChild(item);

      }
    );

  }catch(error){

    $("searchResults").innerHTML=
      "画像を取得できませんでした。"
      +"ネット接続を確認してください。";

  }

}

async function addSelectedImages(){

  const elements=[

    ...document.querySelectorAll(
      ".searchimg.selected"
    )

  ];

  if(!elements.length){

    closeImageSearch();

    return;

  }

  for(
    const element
    of elements
  ){

    try{

      const response=
        await fetch(
          element.dataset.url
        );

      const blob=
        await response.blob();

      posters.push(
        await fileData(blob)
      );

    }catch(error){

    }

  }

  renderPosters();

  closeImageSearch();

  autoDraft();

}

/* =========================================================
   背景カラー
========================================================= */

function setBackgroundColor(color){

  settings.bg=color;

  saveSettings();

  renderBackground();

}

/* =========================================================
   メインカラー
========================================================= */

function setMainColor(color){

  settings.main=color;

  saveSettings();

  renderSettings();

}

/* =========================================================
   カラー丸
========================================================= */

function moveColorOrder(fromIndex,toIndex){

  if(
    fromIndex===toIndex ||
    fromIndex<0 ||
    toIndex<0
  ){

    return;

  }

  const order=[
    ...settings.colorOrder
  ];

  const moved=
    order.splice(
      fromIndex,
      1
    )[0];

  if(!moved){
    return;
  }

  order.splice(
    toIndex,
    0,
    moved
  );

  settings.colorOrder=
    order;

  saveSettings();

  renderSettings();

  renderBackground();

}

function renderColors(
  id,
  current,
  callback
){

  const box=$(id);

  box.innerHTML="";

  const order=
    Array.isArray(settings.colorOrder)
    ? settings.colorOrder
    : [...COLORS];

  let draggedIndex=-1;

  order.forEach(
    (color,index)=>{

      const span=
        document.createElement(
          "span"
        );

      let colorClass="";

if(color==="#ffffff"){
  colorClass=" color-white";
}

if(color==="#f7f7f7"){
  colorClass=" color-offwhite";
}

if(color==="#111827"){
  colorClass=" color-black";
}

span.className=
  "color"+
  colorClass+
  (
    color===current
    ? " selected"
    : ""
  );

      span.style.background=
        color;

      span.draggable=true;

      span.title=
        "クリックで選択・ドラッグで並び替え";

      span.addEventListener(
        "click",
        ()=>{
          callback(color);
        }
      );

      span.addEventListener(
        "dragstart",
        event=>{

          draggedIndex=index;

          span.classList.add(
            "dragging"
          );

          event.dataTransfer.effectAllowed=
            "move";

        }
      );

      span.addEventListener(
        "dragend",
        ()=>{

          draggedIndex=-1;

          span.classList.remove(
            "dragging"
          );

          box
            .querySelectorAll(".color")
            .forEach(
              item=>{
                item.classList.remove(
                  "dragover"
                );
              }
            );

        }
      );

      span.addEventListener(
        "dragover",
        event=>{

          event.preventDefault();

          if(
            draggedIndex!==index
          ){

            span.classList.add(
              "dragover"
            );

          }

          event.dataTransfer.dropEffect=
            "move";

        }
      );

      span.addEventListener(
        "dragleave",
        ()=>{
          span.classList.remove(
            "dragover"
          );
        }
      );

      span.addEventListener(
        "drop",
        event=>{

          event.preventDefault();

          span.classList.remove(
            "dragover"
          );

          if(
            draggedIndex!==index
          ){

            moveColorOrder(
              draggedIndex,
              index
            );

          }

        }
      );

      box.appendChild(span);

    }
  );

}

/* =========================================================
   背景画像
========================================================= */

async function setBackgroundImage(file){

  if(
    !file ||
    !file.type.startsWith("image/")
  ){
    return;
  }


  /*
    保存先フォルダを確認する。
  */

  if(
    !await ensureMovieFolder()
  ){
    return;
  }


  /*
    imagesフォルダを取得する。
  */

  const imagesFolder=
    await getMovieImagesFolder();

  if(!imagesFolder){

    alert(
      "画像保存先フォルダを取得できませんでした。"
    );

    return;

  }


  try{

    /*
      以前の背景画像があれば削除する。
    */

    if(
      settings.backgroundFileName
    ){

      try{

        await imagesFolder.removeEntry(
          settings.backgroundFileName
        );

      }catch(error){

        if(
          error &&
          error.name!=="NotFoundError"
        ){

          console.warn(
            "以前の背景画像を削除できませんでした。",
            error
          );

        }

      }

    }


    /*
      元の拡張子を使用する。
    */

    const extension=
      file.name.includes(".")
      ? file.name
          .split(".")
          .pop()
          .toLowerCase()
      : "jpg";


    const fileName=
      "background."+
      extension;


    /*
      images/background.xxx として保存する。
    */

    const fileHandle=
      await imagesFolder.getFileHandle(
        fileName,
        {
          create:true
        }
      );


    const writable=
      await fileHandle.createWritable();

    await writable.write(file);

    await writable.close();


    /*
      設定ファイルには、
      背景画像ファイル名だけを記録する。
    */

    settings.backgroundFileName=
      fileName;


    await saveSettings();


    /*
      画面表示用には現在選択した画像を使用する。
      localStorageには保存しない。
    */

    const data=
      await fileData(file);


    $("backgroundLayer")
      .style.backgroundImage=
        `url("${data}")`;

    $("backgroundPreview").src=
      data;

    $("backgroundPreview")
      .classList.remove(
        "hidden"
      );

    applyBackgroundStrength();

    renderBackground();

  }catch(error){

    console.error(
      "背景画像の保存に失敗しました。",
      error
    );

    alert(
      "背景画像の保存に失敗しました。\n\n"+
      error.name+
      "\n"+
      error.message
    );

  }

}

$("backgroundFile").addEventListener(
      "change",
      async event=>{
        const file=event.target.files[0];

        if(file){
          await setBackgroundImage(file);
        }

        event.target.value="";
      }
    );

async function clearBackground(){

      if(
        movieFolderHandle &&
        settings.backgroundFileName
      ){
        try{
          const imagesFolder=
            await getMovieImagesFolder();

          if(imagesFolder){
            await imagesFolder.removeEntry(
              settings.backgroundFileName
            );
          }
        }catch(error){
          if(
            error &&
            error.name!=="NotFoundError"
          ){
            console.error(
              "背景画像ファイルの削除に失敗しました。",
              error
            );
          }
        }
      }

      settings.backgroundFileName="";
      settings.backgroundImageHidden=false;

      await saveSettings();

      $("backgroundLayer").style.backgroundImage="none";
      $("backgroundPreview").src="";
      $("backgroundPreview").classList.add("hidden");

      applyBackgroundStrength();
      renderBackground();
    }

    async function toggleBackgroundVisibility(){

      if(!settings.backgroundFileName)return;

      const oldHidden=!!settings.backgroundImageHidden;

      settings.backgroundImageHidden=!oldHidden;

      await saveSettings();

      await loadBackground();
      renderBackground();
    }

/* =========================================================
   背景ドラッグ
========================================================= */

const backgroundDrop=
  $("backgroundDrop");

backgroundDrop.addEventListener(
  "dragover",
  event=>{

    event.preventDefault();

    backgroundDrop
      .classList.add(
        "dragover"
      );

  }
);

backgroundDrop.addEventListener(
  "dragleave",
  ()=>{

    backgroundDrop
      .classList.remove(
        "dragover"
      );

  }
);

backgroundDrop.addEventListener(
  "drop",
  async event=>{

    event.preventDefault();

    backgroundDrop
      .classList.remove(
        "dragover"
      );

    const file=
      event.dataTransfer.files[0];

    if(
      file &&
      file.type.startsWith(
        "image/"
      )
    ){

      await setBackgroundImage(
  file
);


    }

  }
);

/* =========================================================
   背景透過
========================================================= */

function setStrength(value){

  if(!hasBackground()){
    return;
  }

  settings.strength=
    Number(value);

  saveSettings();

  renderBackground();

}

function renderStrength(){

  const box=
    $("backgroundStrength");

  const enabled=
    hasBackground();

  box.innerHTML="";

  for(let i=1;i<=5;i++){

    const button=
      document.createElement(
        "button"
      );

    button.type="button";

    button.className=
      "choice"+
      (
        Number(
          settings.strength
        )===i
        ? " selected"
        : ""
      )+
      (
        !enabled
        ? " disabled"
        : ""
      );

    button.textContent=i;

    button.addEventListener(
      "click",
      ()=>{

        if(enabled){

          setStrength(i);

        }

      }
    );

    box.appendChild(button);

  }

  $("strengthHint").textContent=
    enabled
    ?
    "1=ほぼ不透明、5=背景画像が大きく透けます。"
    :
    "背景画像がないため現在は無効です。";

}

function renderBackground(){

      renderColors(
        "backgroundColors",
        settings.bg,
        setBackgroundColor
      );

      renderStrength();

      const hasImage=!!(
        settings &&
        settings.backgroundFileName
      );

      const preview=$("backgroundPreview");

      if(hasImage){
        preview.classList.remove("hidden");
      }else{
        preview.classList.add("hidden");
      }

      const toggleButton=$("toggleBackground");

      if(toggleButton){
        toggleButton.textContent=
          settings.backgroundImageHidden
            ? "背景画像を表示"
            : "背景画像を非表示";

        toggleButton.disabled=!hasImage;
      }

      applyBackgroundStrength();

    }

/* =========================================================
   目録の列数
========================================================= */

function setCols(value){

  settings.cols=
    Number(value);

  saveSettings();

  renderSettings();

  renderList();

}

function renderColChoices(){

  const values=[
    10,
    8,
    7,
    6,
    5,
    4
  ];

  $("colChoices").innerHTML=
    values.map(
      value=>`

        <button
          type="button"
          class="choice ${
            Number(
              settings.cols
            )===value
            ? "selected"
            : ""
          }"
          data-cols="${value}"
        >
          ${value}
        </button>

      `
    ).join("");

  document
    .querySelectorAll(
      "#colChoices .choice"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          ()=>{

            setCols(
              button.dataset.cols
            );

          }
        );

      }
    );

}

/* =========================================================
   一覧サイズ
========================================================= */

function setTableSize(value){

  settings.tableSize=
    Math.max(
      1,
      Math.min(
        5,
        Number(value)
      )
    );

  saveSettings();

  renderSettings();

  renderItemList();

}

function renderTableSizeChoices(){

  const box=
    $("tableSizeChoices");

  box.innerHTML="";

  for(let i=1;i<=5;i++){

    const button=
      document.createElement(
        "button"
      );

    button.type="button";

    button.className=
      "choice"+
      (
        Number(settings.tableSize)===i
        ? " selected"
        : ""
      );

    button.textContent=i;

    button.title=
      i===1
      ? "極限まで詰める"
      : i===5
        ? "最もゆったり"
        : "一覧サイズ "+i;

    button.addEventListener(
      "click",
      ()=>{
        setTableSize(i);
      }
    );

    box.appendChild(button);

  }


  const titleWidthBox=
    $("titleWidthChoices");

  if(!titleWidthBox){
    return;
  }

  titleWidthBox.innerHTML="";

  for(let i=1;i<=5;i++){

    const button=
      document.createElement(
        "button"
      );

    button.type="button";

    button.className=
      "choice"+
      (
        Number(settings.titleWidth)===i
        ? " selected"
        : ""
      );

    button.textContent=i;

    button.title=
      "タイトル枠 "+i;

    button.addEventListener(
      "click",
      ()=>{

        settings.titleWidth=i;

        saveSettings();

        applySettings();

        renderSettings();

        renderItemList();

      }
    );

    titleWidthBox.appendChild(
      button
    );

  }

}

/* =========================================================
   ダークモード
========================================================= */

function setDarkMode(value){

  settings.dark=
    value==="on";

  saveSettings();

  renderSettings();

}

function renderDarkModeChoices(){

  $("darkModeChoices").innerHTML=`

    <button
      type="button"
      class="choice ${
        !settings.dark
        ? "selected"
        : ""
      }"
      data-dark="off"
    >
      OFF
    </button>

    <button
      type="button"
      class="choice ${
        settings.dark
        ? "selected"
        : ""
      }"
      data-dark="on"
    >
      ON
    </button>

  `;

  document
    .querySelectorAll(
      "#darkModeChoices [data-dark]"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          ()=>{
            setDarkMode(
              button.dataset.dark
            );
          }
        );

      }
    );

}

/* =========================================================
   フォント
========================================================= */

const FONT_TARGETS=[

 [
    "設定",
    "setting",
    "検索欄・設定・背景"
  ],

  [
    "上部バー",
    "header",
    "上部バー"
  ],

  [
    "一覧",
    "table",
    "一覧の文字<br> "
  ],

  [
    "タイトル",
    "title",
    "目録カードの<br>タイトルのみ"
  ],

  [
    "目録情報",
    "meta",
    "目録カードの<br>数字のみ"
  ],

  [
    "編集",
    "form",
    "編集画面の<br>メモ欄以外"
  ],

  [
    "編集メモ",
    "memo",
    "編集画面の<br>メモ本文のみ"
  ]

];

function setFontSize(
  key,
  size
){

  getFontSetting(key).size=
    Number(size);

  saveSettings();

  renderSettings();

  renderList();

  renderItemList();

}

function setFont(
  key,
  font
){

  getFontSetting(key).font=
    Number(font);

  saveSettings();

  renderSettings();

  renderList();

  renderItemList();

}

function renderFontSettings(){

  $("fontSettings").innerHTML=
    FONT_TARGETS.map(
      ([label,key,description])=>{

        const s=
          getFontSetting(key);

        return `

          <div class="font-setting">

            <div>

              <div class="font-setting-label">
                ${label}
              </div>

              <div
                class="hint"
                style="margin-top:3px"
              >
                ${description}
              </div>

            </div>

            <div class="font-control">

              <div class="font-size-options">

                ${[0,1,2,3,4].map(
                  size=>`

                    <button
                      type="button"
                      class="choice ${
                        s.size===size
                        ? "selected"
                        : ""
                      }"
                      data-key="${key}"
                      data-size="${size}"
                      title="サイズ ${size+1}(${FONT_SIZES[size]})"
                    >
                      ${size+1}
                    </button>

                  `
                ).join("")}

              </div>

              <div class="font-options">

                ${FONTS.map(
                  (font,index)=>`

                    <button
                      type="button"
                      class="font-option ${
                        s.font===index
                        ? "selected"
                        : ""
                      }"
                      data-key="${key}"
                      data-font="${index}"
                      title="${esc(font.name)}"
                    >

                      <span
                        class="font-sample"
                        style="font-family:${font.css}"
                      >
                        ${String.fromCharCode(65+index)}
                      </span>

                    </button>

                  `
                ).join("")}

              </div>

            </div>

          </div>

        `;

      }
    ).join("");

  document
    .querySelectorAll(
      "#fontSettings [data-size]"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          ()=>{

            setFontSize(
              button.dataset.key,
              button.dataset.size
            );

          }
        );

      }
    );

  document
    .querySelectorAll(
      "#fontSettings [data-font]"
    )
    .forEach(
      button=>{

        button.addEventListener(
          "click",
          ()=>{

            setFont(
              button.dataset.key,
              button.dataset.font
            );

          }
        );

      }
    );

}

/* =========================================================
   設定
========================================================= */

function renderSettings(){

  renderColors(
    "mainColors",
    settings.main,
    setMainColor
  );

  renderColChoices();

  renderTableSizeChoices();

  renderDarkModeChoices();

  renderFontSettings();

}

/* =========================================================
   下書き
========================================================= */

function getDraft(){

  return {

  id:
    editId || "",

  title:
    $("fTitle").value,

  reading:
    $("fReading").value,

    time:
      $("fTime").value,

    year:
      $("fYear").value,

    count:
      $("fCount").value,

    genre:
      $("fGenre").value,

    maker:
      $("fMaker").value,

    country:
      $("fCountry").value,

    director:
      $("fDirector").value,

    cast:
      $("fCast").value,

    memo:
      $("fMemo").value,

    dates:[

      $("date1").value,
      $("date2").value,
      $("date3").value

    ],

    rating:
  ratingValue(
    "ratingInput"
  ),

entertainment:
  ratingValue(
    "entertainmentInput"
  ),

discomfort:
  ratingValue(
    "discomfortInput"
  ),

abc:
  ratingValue(
    "abcInput"
  ),

    difficulty:
      ratingValue(
        "difficultyInput"
      ),

    quality:
      ratingValue(
        "qualityInput"
      ),

    images:[
      ...posters
    ]

  };

}

let draftTimer=null;

function autoDraft(){

  clearTimeout(
    draftTimer
  );

  draftTimer=
    setTimeout(
      async ()=>{

        try{

          if(
            !movieFolderHandle
          ){
            return;
          }

          const draft=
            getDraft();

          const fileHandle=
            await movieFolderHandle.getFileHandle(
              "draft.json",
              {
                create:true
              }
            );

          const writable=
            await fileHandle.createWritable();

          await writable.write(
            JSON.stringify(
              draft,
              null,
              2
            )
          );

          await writable.close();

        }catch(error){

          console.error(
            "draft.json の保存に失敗しました。",
            error
          );

        }

      },
      200
    );

}

document.addEventListener(
  "input",
  event=>{

    if(
      event.target.closest(
        "#pageEdit"
      )
    ){

      autoDraft();

    }

  }
);

window.addEventListener(
  "beforeunload",
  ()=>{

    /*
      下書きはautoDraft()で
      draft.jsonへ保存するため、
      localStorageには保存しない。
    */

  }
);


/* =========================================================
   編集画面 キーボード操作
========================================================= */

document.addEventListener(
  "keydown",
  event=>{

    const pageEdit =
      $("pageEdit");

    if(!pageEdit){
      return;
    }

    if(
      pageEdit.classList.contains("hidden")
    ){
      return;
    }

    const target =
      event.target;

    if(
      target.matches(
        "input, textarea, select"
      )
    ){
      return;
    }

    if(event.key==="ArrowLeft"){

      event.preventDefault();

      editPreviousMovie();

    }

    if(event.key==="ArrowRight"){

      event.preventDefault();

      editNextMovie();

    }

  }
);


 /* =========================================================
   下書き復元
========================================================= */

async function restoreDraft(){

  if(editId){
    return;
  }

  if(!movieFolderHandle){
    return;
  }

  let draft;

  try{

    const fileHandle=
      await movieFolderHandle.getFileHandle(
        "draft.json"
      );

    const file=
      await fileHandle.getFile();

    const raw=
      await file.text();

    if(!raw){
      return;
    }

    draft=
      JSON.parse(raw);

  }catch(error){

    if(
      error &&
      error.name==="NotFoundError"
    ){
      return;
    }

    console.error(
      "draft.json の読み込みに失敗しました。",
      error
    );

    return;

  }

  const hasData=
    draft.title ||
    draft.reading ||
    draft.memo ||
    draft.images?.length;

  if(!hasData){
    return;
  }


  /*
    下書き確認
    「復元」または「消去」を選択する。
  */

  const overlay=
    document.createElement("div");

  overlay.style.position="fixed";
  overlay.style.inset="0";
  overlay.style.zIndex="9999";
  overlay.style.background="rgba(0,0,0,.55)";
  overlay.style.display="flex";
  overlay.style.alignItems="center";
  overlay.style.justifyContent="center";

  overlay.innerHTML=`

    <div
      style="
        width:min(420px,90vw);
        padding:24px;
        background:var(--panel-bg);
        color:var(--text);
        border-radius:12px;
        box-shadow:0 10px 35px rgba(0,0,0,.25);
        text-align:center;
      "
    >

      <div
        style="
          font-size:18px;
          font-weight:700;
          margin-bottom:18px;
        "
      >
        前回の編集中データがあります
      </div>

      <div
        style="
          display:flex;
          justify-content:center;
          gap:10px;
        "
      >

        <button
          id="restoreDraftButton"
          type="button"
        >
          復元
        </button>

        <button
          id="deleteDraftButton"
          type="button"
          class="danger"
        >
          消去
        </button>

      </div>

    </div>

  `;

  document.body.appendChild(
    overlay
  );


  /*
    復元
  */

  const restoreButton=
    document.getElementById(
      "restoreDraftButton"
    );

  const deleteButton=
    document.getElementById(
      "deleteDraftButton"
    );


  restoreButton.addEventListener(
    "click",
    ()=>{

      overlay.remove();

editId =
  draft.id || "";

$("fTitle").value=
  draft.title || "";

      $("fReading").value=
        draft.reading || "";

      $("fTime").value=
        draft.time || 0;

      $("fYear").value=
        draft.year || "";

      $("fCount").value=
        draft.count || 0;

      $("fGenre").value=
        draft.genre || "";

      $("fMaker").value=
        draft.maker || "";

      $("fCountry").value=
        draft.country || "";

      $("fDirector").value=
        draft.director || "";

      $("fCast").value=
        draft.cast || "";

      $("fMemo").value=
        draft.memo || "";

      putDates(
        draft.dates || []
      );

      posters=
        Array.isArray(draft.images)
        ? draft.images
        : [];

      setRating(
  "ratingInput",
  draft.rating
);

setRating(
  "entertainmentInput",
  draft.entertainment
);

setRating(
  "discomfortInput",
  draft.discomfort
);

      setRating(
        "abcInput",
        draft.abc
      );

      setRating(
        "difficultyInput",
        draft.difficulty
      );

      setRating(
        "qualityInput",
        draft.quality
      );

      renderPosters();

    }
  );


  /*
    消去
  */

  deleteButton.addEventListener(
    "click",
    async ()=>{

      try{

        clearTimeout(
          draftTimer
        );

        await movieFolderHandle.removeEntry(
          "draft.json"
        );

      }catch(error){

        if(
          !error ||
          error.name!=="NotFoundError"
        ){

          console.error(
            "draft.json の消去に失敗しました。",
            error
          );

        }

      }

      overlay.remove();

    }
  );

}



/* =========================================================
   全削除
========================================================= */

function clearAll(){

  if(
    !confirm(
      "映画データをすべて削除します。\nこの操作は元に戻せません。"
    )
  ){

    return;

  }

  movies=[];

  settings.genreOrder=[];

  saveMovies();
  saveSettings();

  renderList();

  renderItemList();

}

/* =========================================================
   背景読み込み
========================================================= */

async function loadBackground(){

  /*
    フォルダ側に保存されている
    背景画像ファイル名を確認する。
  */

  const fileName=
    settings.backgroundFileName;

  if(!fileName){

    $("backgroundLayer")
      .style.backgroundImage=
        "none";

    $("backgroundPreview").src="";

    $("backgroundPreview")
      .classList.add(
        "hidden"
      );

    return;

  }


  if(!movieFolderHandle){

    $("backgroundLayer")
      .style.backgroundImage=
        "none";

    return;

  }


  try{

    const imagesFolder=
      await getMovieImagesFolder();

    if(!imagesFolder){

      return;

    }


    const fileHandle=
      await imagesFolder.getFileHandle(
        fileName
      );


    const file=
      await fileHandle.getFile();


    const url=
      URL.createObjectURL(file);


    $("backgroundLayer")
          .style.backgroundImage=
            settings.backgroundImageHidden
              ? "none"
              : `url("${url}")`;

    $("backgroundPreview").src=
      url;

    $("backgroundPreview")
      .classList.remove(
        "hidden"
      );

    applyBackgroundStrength();

  }catch(error){

    console.error(
      "フォルダから背景画像の読み込みに失敗しました。",
      error
    );

    $("backgroundLayer")
      .style.backgroundImage=
        "none";

    $("backgroundPreview").src="";

    $("backgroundPreview")
      .classList.add(
        "hidden"
      );

  }

}

/* =========================================================
   ウィンドウサイズ変更時
========================================================= */

window.addEventListener(
  "resize",
  ()=>{
    requestAnimationFrame(
      ()=>{
        equalizeCardTitleRows();
        updateTableStickyTop();
      }
    );
  }
);

/* =========================================================
   初期化
========================================================= */

async function init(){

  /*
    まず現在の基本設定を初期化する。
  */

  applySettings();

  renderAttributeFilter();

  renderSettings();

  renderBackground();

  [
    "ratingInput",
    "discomfortInput",
    "abcInput",
    "difficultyInput",
    "qualityInput"
  ].forEach(
    id=>
      setRating(
        id,
        ""
      )
  );


  /*
    IndexedDBから、以前このブラウザで使用した
    保存先FolderHandleを復元する。
  */

  await loadMovieFolderHandle();


  /*
    起動時に保存先フォルダを確認する。
    
    ここで、
    
    ・FolderHandleがない
    ・アクセス許可が必要
    ・FolderHandleが無効
    
    のいずれかなら、
    ユーザー操作で保存先を確定してもらう。
  */

 const startupOverlay =
  document.createElement("div");

startupOverlay.style.position="fixed";
startupOverlay.style.inset="0";
startupOverlay.style.zIndex="9999";

startupOverlay.style.setProperty(
  "background",
  `
    radial-gradient(
      circle at 20% 20%,
      rgba(79,134,198,.55),
      transparent 35%
    ),
    radial-gradient(
      circle at 80% 80%,
      rgba(112,173,71,.30),
      transparent 35%
    ),
    linear-gradient(
      135deg,
      #171d25,
      #20262e 50%,
      #18211d
    )
  `,
  "important"
);

startupOverlay.style.display="flex";
startupOverlay.style.alignItems="center";
startupOverlay.style.justifyContent="center";

startupOverlay.innerHTML=`
  <div
    style="
      width:min(420px,90vw);
      padding:24px;
      background:rgba(30,36,45,.88);
      color:#eef2f7;
      border:1px solid rgba(255,255,255,.12);
      border-radius:12px;
      box-shadow:0 10px 35px rgba(0,0,0,.35);
      text-align:center;
      backdrop-filter:blur(8px);
    "
  >
    <div
      style="
        font-size:18px;
        font-weight:700;
        margin-bottom:12px;
      "
    >
      保存先フォルダを確認しています
    </div>

    <div
      style="
        line-height:1.7;
        margin-bottom:18px;
        color:#d7dee8;
      "
    >
      映画データを読み込むため、
      保存先フォルダへのアクセスを確認します。
    </div>

    <button
      id="startupFolderButton"
      type="button"
    >
      保存先フォルダを確認
    </button>
  </div>
`;

document.body.appendChild(
  startupOverlay
);


  const startupFolderButton =
    document.getElementById(
      "startupFolderButton"
    );


  startupFolderButton.addEventListener(
    "click",
    async ()=>{
      
      startupFolderButton.disabled=true;

      startupFolderButton.textContent=
        "確認中…";


      const ok=
        await ensureMovieFolder();


      if(!ok){

        startupFolderButton.disabled=false;

        startupFolderButton.textContent=
          "保存先フォルダを確認";

        return;

      }


      /*
        保存先が確定したので、
        フォルダ内の映画データと設定を読む。
      */

await loadSettingsFromFolder();

await loadMoviesFromFolder();

await loadBackground();



      /*
        読み込んだデータを画面へ反映する。
      */

      applySettings();

      renderAttributeFilter();

      renderSettings();

      renderBackground();

      renderList();

      renderItemList();

      showPage("table");

      updateTableStickyTop();


      /*
        起動処理完了。
        保存先確認画面を消す。
      */

      startupOverlay.remove();

    }
  );

}


init();

</script>

</body>
</html>

188,990 chars · codepastes.com