<?php


/*
PICKNOMICS 일본 LCC 수하물 계산기
WPCode > JavaScript Snippet
삽입 위치: Site Wide Footer

기존 HTML/CSS는 유지
기존 계산용 script는 제거
*/

(function () {
  'use strict';

  const path = location.pathname.replace(/\/+$/, '');

  if (
    path !==
    '/about/calculator/japan-lcc-baggage-calculator'
  ) return;

  function start() {
    const root = document.getElementById('pkbag26');

    if (!root || root.dataset.pkbWpReady === '1') {
      return;
    }

    const $ = id => root.querySelector('#' + id);

    const required = [
      'pkb-options',
      'pkb-date',
      'pkb-outkg',
      'pkb-inkg',
      'pkb-jpy',
      'pkb-count',
      'pkb-low',
      'pkb-best',
      'pkb-results',
      'pkb-message'
    ];

    if (required.some(id => !$(id))) {
      console.error(
        '[PICKNOMICS] 계산기 HTML 필수 요소 누락'
      );
      return;
    }

    const airlines = {
      jeju: [
        '제주항공',
        [
          ['basic', 'BASIC · 0kg', 0],
          ['standard', 'STANDARD · 15kg', 15],
          ['biz', 'BIZ LITE · 30kg', 30]
        ]
      ],
      jin: [
        '진에어',
        [
          ['standard', '일본노선 · 15kg', 15]
        ]
      ],
      trinity: [
        '트리니티(구 티웨이)',
        [
          ['event', '이벤트 · 0kg', 0],
          ['smart', '스마트 · 15kg', 15],
          ['general', '일반 · 20kg', 20],
          ['business', '비즈니스 · 30kg', 30]
        ]
      ],
      airbusan: [
        '에어부산',
        [
          ['special', '특가·이벤트 · 0kg', 0],
          ['regular', '실속·일반 · 15kg', 15]
        ]
      ]
    };

    const examples = [
      {
        id: 'a',
        label: '항공권 A',
        air: 'jeju',
        tier: 'basic',
        fare: 160000
      },
      {
        id: 'b',
        label: '항공권 B',
        air: 'trinity',
        tier: 'smart',
        fare: 185000
      },
      {
        id: 'c',
        label: '항공권 C',
        air: 'airbusan',
        tier: 'regular',
        fare: 195000
      }
    ];

    const money = n =>
      Math.round(n).toLocaleString('ko-KR') + '원';

    const val = id => {
      const el = $(id);

      if (!el || String(el.value).trim() === '') {
        return null;
      }

      const x = Number(el.value);

      return Number.isFinite(x) && x >= 0
        ? x
        : null;
    };

    const option = (value, text) =>
      `<option value="${value}">${text}</option>`;

    const kgOptions = [
      0, 5, 10, 15, 20, 25, 30
    ].map(x => option(x, x + 'kg')).join('');

    const currentDate = () => {
      const d = new Date();

      return new Date(
        d.getTime() - d.getTimezoneOffset() * 60000
      ).toISOString().slice(0, 10);
    };

    function updateTiers(id, wanted) {
      const air = $(`${id}-air`).value;
      const tiers = airlines[air][1];
      const selected = wanted || $(`${id}-tier`).value;

      $(`${id}-tier`).innerHTML = tiers.map(
        t => option(t[0], t[1])
      ).join('');

      $(`${id}-tier`).value = tiers.some(
        t => t[0] === selected
      )
        ? selected
        : tiers[0][0];

      const free = tiers.find(
        t => t[0] === $(`${id}-tier`).value
      )[2];

      $(`${id}-outfree`).value = String(free);
      $(`${id}-infree`).value = String(free);
    }

    function card(p) {
      return `
      <section class="pk-option">
        <h3>${p.label}</h3>

        <div class="pk-fields">
          <div>
            <label for="${p.id}-air">항공사</label>
            <select id="${p.id}-air">
              ${Object.entries(airlines).map(
                ([id, a]) => option(id, a[0])
              ).join('')}
            </select>
          </div>

          <div>
            <label for="${p.id}-tier">운임 등급</label>
            <select id="${p.id}-tier"></select>
          </div>

          <div>
            <label for="${p.id}-fare">
              왕복 항공권 실제 가격 (원)
            </label>
            <input id="${p.id}-fare"
              type="number" min="0" step="1000"
              value="${p.fare}">
          </div>
        </div>

        <div class="pk-fields">
          <div>
            <label for="${p.id}-outfree">
              출국 무료 수하물 (kg)
            </label>
            <select id="${p.id}-outfree">
              ${kgOptions}
            </select>
          </div>

          <div>
            <label for="${p.id}-infree">
              귀국 무료 수하물 (kg)
            </label>
            <select id="${p.id}-infree">
              ${kgOptions}
            </select>
          </div>

          <div>
            <label for="${p.id}-method">
              출국 수하물 구매 방식
            </label>
            <select id="${p.id}-method">
              ${option('pre', '사전 온라인')}
              ${option('airport', '공항 현장')}
              ${option('manual', '실제 견적 직접 입력')}
            </select>
          </div>
        </div>

        <div class="pk-fields">
          <div>
            <label for="${p.id}-outcost">
              출국 추가 수하물 요금 (원)
            </label>
            <input id="${p.id}-outcost"
              type="number" min="0" step="1000"
              placeholder="비우면 참고요금 자동 적용">
          </div>

          <div>
            <label for="${p.id}-incost">
              귀국 추가 수하물 요금
            </label>
            <input id="${p.id}-incost"
              type="number" min="0" step="0.01"
              placeholder="무료량 초과 시 입력">
          </div>

          <div>
            <label for="${p.id}-currency">
              귀국 요금 통화
            </label>
            <select id="${p.id}-currency">
              ${option('krw', '원화(KRW)')}
              ${option('jpy', '엔화(JPY)')}
            </select>
          </div>
        </div>

        <div class="pk-fields">
          <div>
            <label for="${p.id}-extra">
              왕복 좌석·기타 추가금 (원)
            </label>
            <input id="${p.id}-extra"
              type="number" min="0" step="1000"
              value="0">
          </div>

          <div>
            <label for="${p.id}-coupon">
              항공권 할인·쿠폰 (원)
            </label>
            <input id="${p.id}-coupon"
              type="number" min="0" step="1000"
              value="0">
          </div>

          <div>
            <label>현재 후보 요금 안내</label>
            <p class="pk-micro"
               id="${p.id}-note">—</p>
          </div>
        </div>
      </section>`;
    }

    // 기존 계산기의 2026년 10월 참고요금
    // 실제 결제요금이 있으면 직접 입력한 금액을 우선 사용

    function autoFee(
      air, free, weight, method, date
    ) {
      const extra = Math.max(0, weight - free);

      if (!extra) {
        return {
          price: 0,
          note: '무료 포함량 이내'
        };
      }

      if (method === 'manual') {
        return {
          price: null,
          note: '실제 출국 견적 입력 필요'
        };
      }

      if (
        ![0, 15].includes(free) &&
        !(air === 'trinity' && free === 20) &&
        !(air === 'jeju' && free === 30)
      ) {
        return {
          price: null,
          note: '실제 수하물 요금 입력 필요'
        };
      }

      if (air === 'jeju') {
        if (method === 'pre') {
          return {
            price: free === 0
              ? 40000 +
                Math.ceil(
                  Math.max(0, weight - 15) / 5
                ) * 40000
              : Math.ceil(extra / 5) * 40000,
            note: '제주항공 사전구매 참고요금'
          };
        }

        const after = date >= '2026-10-15';

        return {
          price: free === 0
            ? (after ? 75000 : 60000) +
              Math.max(0, weight - 15) *
              (after ? 15000 : 12000)
            : extra * (after ? 15000 : 12000),
          note: '제주항공 공항 구매 참고요금'
        };
      }

      if (air === 'trinity') {
        if (method === 'pre') {
          return {
            price: free === 0
              ? 40000 +
                Math.ceil(
                  Math.max(0, weight - 15) / 5
                ) * 40000
              : Math.ceil(extra / 5) * 40000,
            note: '사전구매 참고요금'
          };
        }

        return {
          price: free === 0
            ? 60000 +
              Math.max(0, weight - 15) * 15000
            : extra * 15000,
          note: '공항 구매 참고요금'
        };
      }

      if (air === 'airbusan' && free >= 15) {
        return {
          price: method === 'pre'
            ? Math.ceil(extra / 5) * 40000
            : extra * 12000,
          note: '에어부산 참고요금'
        };
      }

      return {
        price: null,
        note: '실제 추가 수하물 요금을 입력하세요'
      };
    }

    function calculate() {
      const date = $('pkb-date').value;
      const ow = val('pkb-outkg');
      const iw = val('pkb-inkg');
      const rate = val('pkb-jpy');

      const kgOk =
        ow !== null &&
        iw !== null &&
        Number.isInteger(ow) &&
        Number.isInteger(iw) &&
        ow <= 32 &&
        iw <= 32;

      const rateOk =
        rate !== null &&
        rate > 0 &&
        rate <= 5000;

      const data = examples.map(p => {
        const id = p.id;
        const air = $(`${id}-air`).value;
        const of = Number(
          $(`${id}-outfree`).value
        );
        const inf = Number(
          $(`${id}-infree`).value
        );

        const fare = val(`${id}-fare`);
        const other = val(`${id}-extra`);
        const coupon = val(`${id}-coupon`);

        const manualOut = val(`${id}-outcost`);
        const manualIn = val(`${id}-incost`);

        const est = kgOk
          ? autoFee(
              air, of, ow,
              $(`${id}-method`).value,
              date
            )
          : {
              price: null,
              note: '무게 확인 필요'
            };

        const out =
          kgOk && ow <= of
            ? 0
            : manualOut === null
              ? est.price
              : manualOut;

        const inbound =
          kgOk && iw <= inf
            ? 0
            : manualIn === null
              ? null
              : $(`${id}-currency`).value === 'jpy'
                ? manualIn * rate / 100
                : manualIn;

        const missing = [];

        if (!date) missing.push('출국일');

        if (!kgOk) missing.push('무게');

        if (!rateOk) missing.push('엔화 환율');

        if (
          fare === null ||
          other === null ||
          coupon === null
        ) {
          missing.push('항공권·기타·할인 금액');
        }

        if (
          kgOk &&
          ow > of &&
          out === null
        ) {
          missing.push('출국 수하물료');
        }

        if (
          kgOk &&
          iw > inf &&
          inbound === null
        ) {
          missing.push('귀국 수하물료');
        }

        if (
          fare !== null &&
          other !== null &&
          coupon !== null &&
          coupon > fare + other
        ) {
          missing.push('쿠폰 금액');
        }

        $(`${id}-note`).textContent =
          `출국 무료 ${of}kg / 귀국 무료 ${inf}kg · ` +
          est.note;

        const valid = missing.length === 0;

        return {
          p,
          air,
          fare,
          out,
          inbound,
          missing,
          valid,
          total: valid
            ? fare + other + out + inbound - coupon
            : null
        };
      });

      const ranked = data
        .filter(x => x.valid)
        .sort((a, b) => a.total - b.total);

      $('pkb-count').textContent =
        ranked.length + '/3개';

      $('pkb-low').textContent =
        ranked.length
          ? money(ranked[0].total)
          : '산정 전';

      $('pkb-best').textContent =
        ranked.length
          ? ranked[0].p.label
          : '미확인';

      const tb = $('pkb-results');
      tb.replaceChildren();

      [
        ...ranked,
        ...data.filter(x => !x.valid)
      ].forEach((r, i) => {
        const tr = document.createElement('tr');

        if (r.valid && i === 0) {
          tr.className = 'pk-best';
        }

        const values = [
          r.p.label + ' · ' + airlines[r.air][0],
          r.fare === null
            ? '입력 필요'
            : money(r.fare),
          r.out === null
            ? '입력 필요'
            : money(r.out),
          r.inbound === null
            ? '입력 필요'
            : money(r.inbound),
          r.valid
            ? money(r.total)
            : '계산 보류',
          r.valid
            ? (i === 0 ? '최저가 후보' : '계산 완료')
            : '미입력: ' + r.missing.join('·')
        ];

        values.forEach(v => {
          const td = document.createElement('td');
          td.textContent = v;
          tr.appendChild(td);
        });

        tb.appendChild(tr);
      });

      $('pkb-message').textContent =
        ranked.length === 3
          ? '3개 후보의 수하물 포함 왕복 비용을 비교했습니다.'
          : '일부 후보는 요금이 누락되어 계산을 보류했습니다.';
    }

    try {
      root.dataset.pkbWpReady = '1';

      $('pkb-options').innerHTML =
        examples.map(card).join('');

      examples.forEach(p => {
        $(`${p.id}-air`).value = p.air;
        updateTiers(p.id, p.tier);
      });

      $('pkb-date').value = currentDate();

      root.addEventListener('change', event => {
        const id = event.target.id || '';
        const m = id.match(/^([abc])-(air|tier)$/);

        if (m) {
          updateTiers(m[1]);

          $(`${m[1]}-outcost`).value = '';
          $(`${m[1]}-incost`).value = '';
        }

        calculate();
      });

      root.addEventListener('input', calculate);

      const reset = $('pkb-reset');

      if (reset) {
        reset.addEventListener('click', () => {
          $('pkb-date').value = currentDate();
          $('pkb-outkg').value = '15';
          $('pkb-inkg').value = '15';
          $('pkb-jpy').value = '846.44';

          examples.forEach(p => {
            const id = p.id;

            $(`${id}-air`).value = p.air;
            updateTiers(id, p.tier);

            $(`${id}-fare`).value = p.fare;
            $(`${id}-method`).value = 'pre';
            $(`${id}-outcost`).value = '';
            $(`${id}-incost`).value = '';
            $(`${id}-currency`).value = 'krw';
            $(`${id}-extra`).value = '0';
            $(`${id}-coupon`).value = '0';
          });

          calculate();
        });
      }

      calculate();

      root.dataset.ready = '1';

      const warn = $('pkb-js-status');

      if (warn) warn.remove();

    } catch (err) {
      root.dataset.pkbWpReady = '0';

      console.error(
        '[PICKNOMICS] 계산기 오류:',
        err
      );

      const warn = $('pkb-js-status');

      if (warn) {
        warn.textContent =
          '계산기를 실행하지 못했습니다. 콘솔 오류를 확인해주세요.';
      }
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener(
      'DOMContentLoaded',
      start,
      { once: true }
    );
  } else {
    start();
  }

})();