// Modals — LINE QR + Category detail + Method detail. Shared between mobile and PC.
// Uses a tiny imperative API: window.__openLineQR(), window.__openCategory(enKey), window.__openMethod(methodObj)

function KBModals({ isPC = false }) {
  const K = window.KB;
  const { Line, Sparkle, ArrowRight, Phone, Check, Store, Truck, Chat } = window.KBIcon;

  const [lineOpen, setLineOpen] = React.useState(false);
  const [catKey, setCatKey] = React.useState(null);
  const [methodData, setMethodData] = React.useState(null);

  React.useEffect(() => {
    window.__openLineQR = () => setLineOpen(true);
    window.__closeLineQR = () => setLineOpen(false);
    window.__openCategory = (k) => setCatKey(k);
    window.__closeCategory = () => setCatKey(null);
    window.__openMethod = (m) => setMethodData(m);
    window.__closeMethod = () => setMethodData(null);

    if (!document.getElementById('kb-modal-style')) {
      const s = document.createElement('style');
      s.id = 'kb-modal-style';
      s.textContent = `
        @keyframes kbModalIn {
          from { opacity: 0; transform: translate(-50%, -48%) scale(0.96); }
          to { opacity: 1; transform: translate(-50%, -50%) scale(1); }
        }
      `;
      document.head.appendChild(s);
    }
  }, []);

  const cat = catKey ? window.KBCategoryDetails[catKey] : null;

  // Close on ESC
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') { setLineOpen(false); setCatKey(null); setMethodData(null); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const show = lineOpen || catKey || methodData;

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 999,
      pointerEvents: show ? 'auto' : 'none',
    }}>
      {/* Backdrop */}
      <div
        onClick={() => { setLineOpen(false); setCatKey(null); setMethodData(null); }}
        style={{
          position: 'absolute', inset: 0,
          background: 'rgba(5,11,24,0.72)',
          backdropFilter: 'blur(6px)',
          WebkitBackdropFilter: 'blur(6px)',
          opacity: show ? 1 : 0,
          transition: 'opacity 0.28s ease',
        }}
      />

      {/* LINE QR modal */}
      {lineOpen && <LineQRModal K={K} onClose={() => setLineOpen(false)} Icon={{ Line, Sparkle, ArrowRight, Check }} showAddButton={!isPC} />}

      {/* Category detail modal */}
      {catKey && cat && <CategoryModal K={K} cat={cat} enKey={catKey} onClose={() => setCatKey(null)} Icon={{ ArrowRight, Sparkle, Line, Check }} isPC={isPC} />}

      {/* Method detail modal */}
      {methodData && <MethodModal K={K} method={methodData} onClose={() => setMethodData(null)} Icon={{ Line, Sparkle, ArrowRight, Store, Truck, Chat }} isPC={isPC} />}
    </div>
  );
}

function LineQRModal({ K, onClose, Icon, showAddButton = true }) {
  const { Line, Sparkle, Check } = Icon;
  return (
    <div role="dialog" aria-modal="true" aria-label="LINE査定" style={{
      position: 'absolute', top: '50%', left: '50%',
      transform: 'translate(-50%, -50%)',
      width: 'min(420px, calc(100vw - 32px))',
      animation: 'kbModalIn 0.3s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{
        position: 'relative',
        padding: '36px 28px 28px',
        background: `linear-gradient(160deg, ${K.navy700}, ${K.navy900})`,
        border: `1px solid ${K.gold}`,
        boxShadow: '0 60px 120px rgba(0,0,0,0.6), 0 0 0 1px rgba(201,169,97,0.2)',
      }}>
        {/* Corner dots */}
        {[[0,0],[1,0],[0,1],[1,1]].map(([x,y], i) => (
          <div key={i} style={{
            position: 'absolute',
            [x ? 'right' : 'left']: -4, [y ? 'bottom' : 'top']: -4,
            width: 8, height: 8, background: K.gold,
          }} />
        ))}

        <button onClick={onClose} aria-label="閉じる" style={{
          position: 'absolute', top: 12, right: 12,
          width: 30, height: 30, border: 'none',
          background: 'rgba(255,255,255,0.05)',
          color: K.inkDim, fontSize: 18, cursor: 'pointer',
          display: 'grid', placeItems: 'center',
        }}>×</button>

        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          padding: '6px 12px',
          background: '#06C755',
          fontFamily: K.fontMono, fontSize: 9.5, letterSpacing: '0.25em',
          color: '#fff', fontWeight: 700,
        }}>
          <Line size={12} color="#fff" /> LINE APPRAISAL
        </div>

        <h3 style={{
          margin: '18px 0 0',
          fontFamily: K.fontSerif, fontWeight: 700, fontSize: 24,
          color: K.ink, letterSpacing: '0.04em', lineHeight: 1.3,
        }}>写真を送るだけで<br/>査定できます。</h3>

        <p style={{
          margin: '12px 0 0',
          fontFamily: K.fontSans, fontSize: 12.5, lineHeight: 1.8,
          color: K.inkDim,
        }}>
          下のQRコードを読み取って友だち追加 →<br/>
          お品物の写真を送信いただければ、査定いたします。
        </p>

        {/* QR block */}
        <div style={{
          marginTop: 22,
          display: 'flex', justifyContent: 'center',
        }}>
          <div style={{
            position: 'relative',
            padding: 14, background: '#fff',
            border: `2px solid ${K.gold}`,
          }}>
            <img src="/legacy/assets/line-qr.jpg" alt="LINE QR" style={{
              width: 200, height: 200, display: 'block',
            }} />
            {[[0,0],[1,0],[0,1],[1,1]].map(([x,y], i) => (
              <div key={i} style={{
                position: 'absolute',
                [x ? 'right' : 'left']: 6, [y ? 'bottom' : 'top']: 6,
                width: 16, height: 16,
                borderTop: y ? 'none' : `2px solid ${K.gold}`,
                borderBottom: y ? `2px solid ${K.gold}` : 'none',
                borderLeft: x ? 'none' : `2px solid ${K.gold}`,
                borderRight: x ? `2px solid ${K.gold}` : 'none',
              }} />
            ))}
          </div>
        </div>

        {showAddButton && (
          <a href="https://line.me/ti/p/xWmu96gEhw"
             target="_blank" rel="noopener noreferrer"
             style={{
            marginTop: 20, width: '100%',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            height: 52, border: 'none',
            background: '#06C755', color: '#fff', textDecoration: 'none',
            fontFamily: K.fontSans, fontWeight: 800, fontSize: 14, letterSpacing: '0.06em',
            boxSizing: 'border-box',
          }}>
            <Line size={20} color="#fff" /> LINEで友だち追加
          </a>
        )}

        <div style={{
          marginTop: 14, textAlign: 'center',
          fontFamily: K.fontMono, fontSize: 9, letterSpacing: '0.22em', color: K.inkMute,
        }}>
          24時間受付 · 査定料無料
        </div>
      </div>
    </div>
  );
}

function CategoryModal({ K, cat, enKey, onClose, Icon, isPC = false }) {
  const { ArrowRight, Sparkle, Line, Check } = Icon;
  const closeRef = React.useRef(null);
  React.useEffect(() => {
    const prev = document.activeElement;
    closeRef.current?.focus();
    return () => { if (prev && prev.focus) prev.focus(); };
  }, []);
  return (
    <div role="dialog" aria-modal="true" aria-labelledby="cat-modal-title" style={{
      position: 'absolute', top: '50%', left: '50%',
      transform: 'translate(-50%, -50%)',
      width: 'min(560px, calc(100vw - 32px))',
      maxHeight: 'calc(100vh - 40px)',
      overflowY: 'auto',
      animation: 'kbModalIn 0.3s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{
        position: 'relative',
        background: `linear-gradient(160deg, ${K.navy700}, ${K.navy800})`,
        border: `1px solid ${K.gold}80`,
        boxShadow: '0 60px 120px rgba(0,0,0,0.6)',
      }}>
        {[[0,0],[1,0],[0,1],[1,1]].map(([x,y], i) => (
          <div key={i} style={{
            position: 'absolute',
            [x ? 'right' : 'left']: -4, [y ? 'bottom' : 'top']: -4,
            width: 8, height: 8, background: K.gold, zIndex: 2,
          }} />
        ))}

        <button ref={closeRef} onClick={onClose} aria-label="閉じる" style={{
          position: 'absolute', top: 12, right: 12, zIndex: 3,
          width: 30, height: 30, border: 'none',
          background: 'rgba(255,255,255,0.05)',
          color: K.inkDim, fontSize: 18, cursor: 'pointer',
          display: 'grid', placeItems: 'center',
        }}>×</button>

        {/* Header hero */}
        <div style={{
          padding: '36px 28px 28px',
          background: `
            radial-gradient(ellipse 80% 100% at 50% 0%, rgba(201,169,97,0.18), transparent 60%)
          `,
          borderBottom: `1px solid ${K.gold}30`,
        }}>
          <div style={{
            fontFamily: K.fontMono, fontSize: 10.5, letterSpacing: '0.3em', color: K.goldLight,
          }}>{cat.en.toUpperCase()}</div>
          <h3 id="cat-modal-title" style={{
            margin: '8px 0 0',
            fontFamily: K.fontSerif, fontWeight: 700, fontSize: 32,
            color: K.ink, letterSpacing: '0.04em', lineHeight: 1.2,
          }}>{cat.ja}</h3>
          <div style={{
            marginTop: 10,
            fontFamily: K.fontSerif, fontWeight: 500, fontSize: 14,
            color: K.goldLight, letterSpacing: '0.05em',
          }}>― {cat.tagline}</div>
        </div>

        {/* Body */}
        <div style={{ padding: '24px 28px 8px' }}>
          <p style={{
            margin: 0,
            fontFamily: K.fontSans, fontSize: 13.5, lineHeight: 2,
            color: K.inkDim, letterSpacing: '0.02em',
          }}>{cat.desc}</p>

          <div style={{ marginTop: 24 }}>
            <div style={{
              fontFamily: K.fontMono, fontSize: 9.5, letterSpacing: '0.25em', color: K.gold,
            }}>― 主な買取例 ―</div>
            <div style={{ marginTop: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {cat.examples.map(ex => (
                <div key={ex} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '10px 12px',
                  background: 'rgba(201,169,97,0.06)',
                  border: `1px solid ${K.gold}25`,
                }}>
                  <div style={{
                    width: 18, height: 18, flexShrink: 0,
                    display: 'grid', placeItems: 'center',
                    background: K.gold,
                  }}>
                    <Check size={11} color={K.navy900} />
                  </div>
                  <div style={{
                    fontFamily: K.fontSerif, fontSize: 13, color: K.ink, letterSpacing: '0.03em',
                  }}>{ex}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* CTA footer */}
        <div style={{
          padding: '20px 28px 28px',
          display: 'flex', gap: 10,
        }}>
          <a href="#form" onClick={onClose} style={{
            flex: 1, height: 52,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            background: `linear-gradient(180deg, ${K.goldLight}, ${K.gold}, ${K.goldDeep})`,
            color: K.navy900,
            fontFamily: K.fontSans, fontWeight: 900, fontSize: 13, letterSpacing: '0.12em',
            textDecoration: 'none',
            boxShadow: '0 12px 28px rgba(201,169,97,0.25)',
          }}>
            <Sparkle size={12} color={K.navy900} /> 無料査定 <ArrowRight size={14} color={K.navy900} />
          </a>
          {isPC ? (
            <button onClick={() => { onClose(); window.__openLineQR && window.__openLineQR(); }} style={{
              width: 52, height: 52, border: 'none',
              background: '#06C755', cursor: 'pointer',
              display: 'grid', placeItems: 'center',
            }}>
              <Line size={22} color="#fff" />
            </button>
          ) : (
            <a href="https://line.me/ti/p/xWmu96gEhw" target="_blank" rel="noopener noreferrer" onClick={onClose} style={{
              width: 52, height: 52,
              background: '#06C755',
              display: 'grid', placeItems: 'center',
              textDecoration: 'none',
            }}>
              <Line size={22} color="#fff" />
            </a>
          )}
        </div>
      </div>
    </div>
  );
}

function MethodModal({ K, method, onClose, Icon, isPC = false }) {
  const { Line, Sparkle, ArrowRight } = Icon;
  const closeRef = React.useRef(null);
  React.useEffect(() => {
    const prev = document.activeElement;
    closeRef.current?.focus();
    return () => { if (prev && prev.focus) prev.focus(); };
  }, []);
  return (
    <div role="dialog" aria-modal="true" aria-labelledby="method-modal-title" style={{
      position: 'absolute', top: '50%', left: '50%',
      transform: 'translate(-50%, -50%)',
      width: 'min(480px, calc(100vw - 32px))',
      animation: 'kbModalIn 0.3s cubic-bezier(0.16,1,0.3,1)',
    }}>
      <div style={{
        position: 'relative',
        background: `linear-gradient(160deg, ${K.navy700}, ${K.navy900})`,
        border: `1px solid ${K.gold}80`,
        boxShadow: '0 60px 120px rgba(0,0,0,0.6)',
      }}>
        {[[0,0],[1,0],[0,1],[1,1]].map(([x,y], i) => (
          <div key={i} style={{
            position: 'absolute',
            [x ? 'right' : 'left']: -4, [y ? 'bottom' : 'top']: -4,
            width: 8, height: 8, background: K.gold, zIndex: 2,
          }} />
        ))}

        <button ref={closeRef} onClick={onClose} aria-label="閉じる" style={{
          position: 'absolute', top: 12, right: 12, zIndex: 3,
          width: 30, height: 30, border: 'none',
          background: 'rgba(255,255,255,0.05)',
          color: K.inkDim, fontSize: 18, cursor: 'pointer',
          display: 'grid', placeItems: 'center',
        }}>×</button>

        <div style={{ padding: '36px 28px 24px' }}>
          <div style={{
            fontFamily: K.fontMono, fontSize: 9.5,
            letterSpacing: '0.3em', color: K.goldLight,
          }}>{method.en}</div>
          <h3 id="method-modal-title" style={{
            margin: '10px 0 0',
            fontFamily: K.fontSerif, fontWeight: 700, fontSize: 26,
            color: K.ink, letterSpacing: '0.04em', lineHeight: 1.3,
          }}>{method.ja}</h3>
          <p style={{
            margin: '16px 0 0',
            fontFamily: K.fontSans, fontSize: 13.5, lineHeight: 1.9,
            color: K.inkDim,
          }}>{method.desc}</p>
        </div>

        <div style={{ padding: '0 28px 28px', display: 'flex', gap: 10 }}>
          {method.line ? (
            isPC ? (
              <button onClick={() => { onClose(); window.__openLineQR && window.__openLineQR(); }} style={{
                flex: 1, height: 52, border: 'none',
                background: '#06C755', color: '#fff',
                fontFamily: K.fontSans, fontWeight: 800, fontSize: 14, letterSpacing: '0.06em',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                cursor: 'pointer',
              }}>
                <Line size={20} color="#fff" /> LINEで友だち追加
              </button>
            ) : (
              <a href="https://line.me/ti/p/xWmu96gEhw" target="_blank" rel="noopener noreferrer" onClick={onClose} style={{
                flex: 1, height: 52,
                background: '#06C755', color: '#fff',
                fontFamily: K.fontSans, fontWeight: 800, fontSize: 14, letterSpacing: '0.06em',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                textDecoration: 'none',
              }}>
                <Line size={20} color="#fff" /> LINEで友だち追加
              </a>
            )
          ) : (
            <button type="button" onClick={() => {
              onClose();
              setTimeout(() => {
                const el = document.getElementById('form');
                if (el) el.scrollIntoView({ behavior: 'smooth' });
              }, 60);
            }} style={{
              flex: 1, height: 52, border: 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              background: `linear-gradient(180deg, ${K.goldLight}, ${K.gold}, ${K.goldDeep})`,
              color: K.navy900,
              fontFamily: K.fontSans, fontWeight: 900, fontSize: 13, letterSpacing: '0.12em',
              cursor: 'pointer',
              boxShadow: '0 12px 28px rgba(201,169,97,0.25)',
            }}>
              <Sparkle size={12} color={K.navy900} /> 無料査定を依頼する <ArrowRight size={14} color={K.navy900} />
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { KBModals });
