/* global React, Reveal, Check, CustomerCard, PaymentVisual, EcosystemDiagram */

// ====================== STICKY SCROLL-TELLING HIGHLIGHTS ======================
const SHL_ITEMS = [
  {
    key: 'customer', color: 'blue', dotColor: 'var(--brand-blue)', checkColor: '#1a5a6b',
    label: 'HIGHLIGHT 01 · 顧客台帳',
    title: <React.Fragment>顧客を、<br/>宿の一番の資産に。</React.Fragment>,
    body: <React.Fragment>誰が泊まり、何を喜んだか。一人ひとりの記録が積み上がり、再訪へつながります。OTA では決して届かない情報が、宿の中に蓄積されていく。<img src="/tomarin/assets/tomarin-wordmark.png" alt="tomarin" className="tm-inline" /> の顧客台帳が、関係を続ける土台になります。</React.Fragment>,
    checks: [
      '宿泊履歴・好み・要望を、ひとつの顧客台帳に一元化',
      '再訪時は「おかえりなさい」の接客を、スタッフ全員で',
      'タグと会員制度で、常連を見える化する',
    ],
  },
  {
    key: 'payment', color: 'green', dotColor: 'var(--brand-green)', checkColor: '#6FAF2A',
    label: 'HIGHLIGHT 02 · 決済 & 宿泊税',
    title: <React.Fragment>キャンセル料の悩みも、<br/>宿泊税の集計も。</React.Fragment>,
    body: <React.Fragment>予約時のクレジットカード登録が標準。キャンセルはポリシーに沿って自動請求。さらに、複雑な宿泊税（定額・定率・階層）も自治体ごとに設定すれば、徴収・月次集計・申告書出力まで <img src="/tomarin/assets/tomarin-wordmark.png" alt="tomarin" className="tm-inline" /> が引き受けます。</React.Fragment>,
    checks: [
      'キャンセルポリシーに応じた自動請求',
      '宿泊税は自治体方式で自動計算・同時徴収',
      '月次レポート・申告書（eLTAX 含む）を自動出力',
    ],
  },
  {
    key: 'ecosystem', color: 'yellow', dotColor: 'var(--brand-yellow)', checkColor: '#C99C0B',
    label: 'HIGHLIGHT 03 · 地域との循環',
    title: <React.Fragment>宿を、<br/>地域ぐるみで支える。</React.Fragment>,
    body: <React.Fragment>同じ Ramps が運営する ensembles は、地域のイベントや体験を通じてファンを育てるコミュニティ。そこで地域に出会った人が、tomarin を通じて宿に滞在する。出会う → 泊まる → また訪れる。地域の中で価値が循環する仕組みです。</React.Fragment>,
    checks: [
      'ensembles の参加者を、宿のゲストへ自然に',
      '町内の宿に一括導入。観光DMPへデータ連携',
      '地域施策の根拠となる宿泊データを蓄積',
    ],
  },
];

function ShlVisual({ k }) {
  if (k === 'customer') return <CustomerCard />;
  if (k === 'payment') return <PaymentVisual />;
  return <EcosystemDiagram />;
}

function HighlightsSticky() {
  const [active, setActive] = React.useState(0);
  const blockRefs = React.useRef([]);

  React.useEffect(() => {
    const onScroll = () => {
      const mid = window.scrollY + window.innerHeight / 2;
      let best = 0, bestDist = Infinity;
      blockRefs.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const center = window.scrollY + r.top + r.height / 2;
        const d = Math.abs(center - mid);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      setActive(a => (a === best ? a : best));
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll);
    onScroll();
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    <section className="section" id="highlights" style={{ paddingBottom: 40 }}>
      <div className="container">
        <Reveal>
          <div className="section-head">
            <h2 className="section-title"><img src="/tomarin/assets/tomarin-wordmark.png" alt="tomarin" className="sol-logo" /> ならではの、<br/>3つの強み。</h2>
          </div>
        </Reveal>
        <div className="shl-grid">
          <div className="shl-copy">
            {SHL_ITEMS.map((it, i) => (
              <div key={it.key}
                ref={el => blockRefs.current[i] = el}
                className={`shl-block ${active === i ? 'active' : ''}`}>
                <div className="highlight-label">
                  <div className="dot" style={{ background: it.dotColor }}></div>
                  <div className={`text ${it.color}`}>{it.label}</div>
                </div>
                <h2>{it.title}</h2>
                <p className="highlight-body">{it.body}</p>
                <div className="checklist">
                  {it.checks.map((c, j) => (
                    <div className="check-item" key={j}><Check color={it.checkColor} /><span>{c}</span></div>
                  ))}
                </div>
                {/* inline visual for mobile */}
                <div className="shl-inline-visual">
                  <ShlVisual k={it.key} />
                </div>
              </div>
            ))}
          </div>
          <div className="shl-visual-col">
            <div className="shl-sticky">
              {SHL_ITEMS.map((it, i) => (
                <div key={it.key} className={`shl-pane ${active === i ? 'show' : i < active ? 'above' : 'below'}`}>
                  <ShlVisual k={it.key} />
                </div>
              ))}
              <div className="shl-dots">
                {SHL_ITEMS.map((it, i) => (
                  <span key={i} className={`shl-dot ${active === i ? 'on' : ''}`}
                    style={active === i ? { background: it.dotColor } : {}}></span>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ====================== GLOBAL MICRO-INTERACTIONS ======================
function MotionFX() {
  React.useEffect(() => {
    if (!window.matchMedia('(pointer: fine)').matches) return;

    let magnetEl = null;
    let tiltEl = null;

    const motionOff = () => document.documentElement.getAttribute('data-motion') === 'off';

    const onMove = (e) => {
      if (motionOff()) return;

      // magnetic buttons
      const btn = e.target.closest('.btn');
      if (btn !== magnetEl) {
        if (magnetEl) magnetEl.style.transform = '';
        magnetEl = btn;
      }
      if (magnetEl) {
        const r = magnetEl.getBoundingClientRect();
        const dx = (e.clientX - r.left - r.width / 2) / (r.width / 2);
        const dy = (e.clientY - r.top - r.height / 2) / (r.height / 2);
        magnetEl.style.transform = `translate(${dx * 4}px, ${dy * 3}px)`;
      }

      // tilt cards
      const card = e.target.closest('.bento-cell, .strength-card, .pv2-card');
      if (card !== tiltEl) {
        if (tiltEl) tiltEl.style.transform = '';
        tiltEl = card;
      }
      if (tiltEl) {
        const r = tiltEl.getBoundingClientRect();
        const dx = (e.clientX - r.left - r.width / 2) / (r.width / 2);
        const dy = (e.clientY - r.top - r.height / 2) / (r.height / 2);
        tiltEl.style.transform = `perspective(900px) rotateX(${(-dy * 2.5).toFixed(2)}deg) rotateY(${(dx * 2.5).toFixed(2)}deg) translateY(-2px)`;
      }
    };

    const onLeave = () => {
      if (magnetEl) { magnetEl.style.transform = ''; magnetEl = null; }
      if (tiltEl) { tiltEl.style.transform = ''; tiltEl = null; }
    };

    document.addEventListener('mousemove', onMove, { passive: true });
    document.documentElement.addEventListener('mouseleave', onLeave);
    return () => {
      document.removeEventListener('mousemove', onMove);
      document.documentElement.removeEventListener('mouseleave', onLeave);
    };
  }, []);
  return null;
}

Object.assign(window, { HighlightsSticky, MotionFX });
