// install_prompt.jsx — PWAインストール誘導UI
// iOS Safari: ビジュアル図解付きモーダル（共有ボタン → ホーム画面に追加）
// Android/Chrome/Edge: beforeinstallprompt を捕まえてワンタップインストール
// すべて: Settings 画面から再表示できるボタンを提供

// 外部化: グローバルインストールイベントの捕捉（ページロード直後に必要）
(function setupInstallCapture() {
  if (window.__echoInstallSetup) return;
  window.__echoInstallSetup = true;
  window.__echoDeferredInstallPrompt = null;
  window.addEventListener('beforeinstallprompt', (e) => {
    e.preventDefault();
    window.__echoDeferredInstallPrompt = e;
    window.dispatchEvent(new CustomEvent('echo:installAvailable'));
  });
  window.addEventListener('appinstalled', () => {
    window.__echoDeferredInstallPrompt = null;
    try { localStorage.setItem('echo.installed', '1'); } catch (err) {}
    window.dispatchEvent(new CustomEvent('echo:installed'));
  });
})();

// プラットフォーム判定
function getInstallPlatform() {
  const ua = navigator.userAgent;
  if (/iPad|iPhone|iPod/.test(ua) && !window.MSStream) return 'ios';
  if (/Android/.test(ua)) return 'android';
  if (/Macintosh/.test(ua) && 'ontouchend' in document) return 'ios'; // iPadOS 13+
  return 'desktop';
}

// すでにインストール済み？
function isAlreadyInstalled() {
  if (window.matchMedia('(display-mode: standalone)').matches) return true;
  if (window.navigator.standalone === true) return true;
  try { if (localStorage.getItem('echo.installed') === '1') return true; } catch (e) {}
  return false;
}

// インストールヒント（ボトムバナー・初回訪問時のみ）
function InstallBanner({ onDetails, onDismiss }) {
  const t = useT();
  const platform = getInstallPlatform();

  const copy = platform === 'ios'
    ? 'ホーム画面に追加してフルスクリーン起動'
    : 'ワンタップでアプリとしてインストール';

  return (
    <div style={{
      position: 'fixed', bottom: 76, left: 12, right: 12, zIndex: 90,
      background: t.bgCard,
      border: `1px solid ${t.line}`,
      borderRadius: 14,
      boxShadow: '0 12px 40px rgba(0,0,0,0.18), 0 2px 8px rgba(0,0,0,0.08)',
      fontFamily: APP_FONT,
      animation: 'echoSlideUp 0.36s cubic-bezier(.2,.8,.2,1)',
      maxWidth: 460, marginLeft: 'auto', marginRight: 'auto',
    }}>
      <style>{`
        @keyframes echoSlideUp {
          from { transform: translateY(20px); opacity: 0; }
          to   { transform: translateY(0); opacity: 1; }
        }
      `}</style>
      <div style={{ padding: '14px 14px 14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 10, flexShrink: 0,
          background: `linear-gradient(135deg, ${t.primary} 0%, ${t.purple} 100%)`,
          color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: `0 6px 14px ${t.primary}33`,
        }}>
          {Icons.sprout(22)}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 13, fontWeight: 800, color: t.ink,
            letterSpacing: '-0.02em', marginBottom: 2,
          }}>Echo をインストール</div>
          <div style={{
            fontSize: 11, color: t.ink3, letterSpacing: '-0.01em',
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{copy}</div>
        </div>
        <button onClick={onDetails} style={{
          padding: '8px 12px', borderRadius: 8,
          background: t.primary, color: '#fff',
          border: 'none', fontFamily: APP_FONT, fontSize: 12, fontWeight: 700,
          letterSpacing: '-0.01em', cursor: 'pointer', flexShrink: 0,
          minHeight: 36,
          WebkitTapHighlightColor: 'transparent',
        }}>
          追加
        </button>
        <button onClick={onDismiss} aria-label='後で' style={{
          background: 'transparent', border: 'none',
          color: t.ink4, cursor: 'pointer', padding: 6, flexShrink: 0,
          WebkitTapHighlightColor: 'transparent',
          display: 'flex',
        }}>
          {Icons.close(16)}
        </button>
      </div>
    </div>
  );
}

// iOS用 図解モーダル
function InstallModalIOS({ onClose }) {
  const t = useT();
  return (
    <ModalShell onClose={onClose}>
      <div style={{ textAlign: 'center', marginBottom: 20 }}>
        <div style={{
          width: 64, height: 64, borderRadius: 16,
          background: `linear-gradient(135deg, ${t.primary} 0%, ${t.purple} 100%)`,
          color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 14,
          boxShadow: `0 10px 28px ${t.primary}44`,
        }}>
          {Icons.sprout(32)}
        </div>
        <div style={{
          fontSize: 20, fontWeight: 800, color: t.ink,
          letterSpacing: '-0.03em', marginBottom: 6,
        }}>ホーム画面に追加</div>
        <div style={{
          fontSize: 13, color: t.ink3,
          letterSpacing: '-0.01em', lineHeight: 1.5,
        }}>
          Safari のメニューから3ステップ
        </div>
      </div>

      <StepRow
        num='1'
        label='Safari 下の共有ボタンをタップ'
        visual={<SafariShareIcon t={t}/>}
      />
      <StepRow
        num='2'
        label='「ホーム画面に追加」を選択'
        visual={<AddToHomeRow t={t}/>}
      />
      <StepRow
        num='3'
        label='右上「追加」をタップ。完了。'
        visual={<HomeScreenIcon t={t}/>}
      />

      <div style={{
        marginTop: 18,
        padding: '12px 14px',
        background: t.bgSoft,
        borderRadius: 10,
        fontSize: 11, color: t.ink3,
        letterSpacing: '-0.01em', lineHeight: 1.6,
      }}>
        ※ Chrome など他ブラウザでは動作しません。Safari で開き直してください。
      </div>

      <button onClick={onClose} style={{
        marginTop: 18, width: '100%',
        padding: '14px', borderRadius: 10,
        background: t.ink, color: t.bgCard,
        border: 'none', fontFamily: APP_FONT, fontSize: 14, fontWeight: 700,
        letterSpacing: '-0.01em', cursor: 'pointer',
        minHeight: 48,
      }}>
        了解
      </button>
    </ModalShell>
  );
}

// Android/Desktop用 ワンタップインストールモーダル
function InstallModalNative({ onClose }) {
  const t = useT();
  const [state, setState] = React.useState('idle'); // idle | prompting | accepted | dismissed | error

  const handleInstall = async () => {
    const ev = window.__echoDeferredInstallPrompt;
    if (!ev) {
      setState('error');
      return;
    }
    setState('prompting');
    try {
      ev.prompt();
      const choice = await ev.userChoice;
      if (choice.outcome === 'accepted') {
        setState('accepted');
        setTimeout(onClose, 1500);
      } else {
        setState('dismissed');
      }
      window.__echoDeferredInstallPrompt = null;
    } catch (err) {
      setState('error');
    }
  };

  return (
    <ModalShell onClose={onClose}>
      <div style={{ textAlign: 'center', marginBottom: 22 }}>
        <div style={{
          width: 64, height: 64, borderRadius: 16,
          background: `linear-gradient(135deg, ${t.primary} 0%, ${t.purple} 100%)`,
          color: '#fff',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 14,
          boxShadow: `0 10px 28px ${t.primary}44`,
        }}>
          {Icons.sprout(32)}
        </div>
        <div style={{
          fontSize: 20, fontWeight: 800, color: t.ink,
          letterSpacing: '-0.03em', marginBottom: 6,
        }}>
          {state === 'accepted' ? 'インストール完了' : 'Echo をインストール'}
        </div>
        <div style={{
          fontSize: 13, color: t.ink3,
          letterSpacing: '-0.01em', lineHeight: 1.5,
        }}>
          {state === 'accepted'
            ? 'ホーム画面から起動できます'
            : 'ブラウザのアプリとして登録。オフライン対応、フルスクリーン起動。'}
        </div>
      </div>

      {state !== 'accepted' && (
        <div style={{ display: 'grid', gap: 8, marginBottom: 18 }}>
          <BenefitRow t={t} icon='⚡' label='フルスクリーン起動（ブラウザUIなし）'/>
          <BenefitRow t={t} icon='📴' label='オフラインでも動作（キャッシュ済み）'/>
          <BenefitRow t={t} icon='🏠' label='ホーム画面 / デスクトップから1タップ'/>
        </div>
      )}

      {state === 'idle' && (
        <button onClick={handleInstall} style={{
          width: '100%', padding: '14px', borderRadius: 10,
          background: t.primary, color: '#fff',
          border: 'none', fontFamily: APP_FONT, fontSize: 14, fontWeight: 800,
          letterSpacing: '-0.01em', cursor: 'pointer',
          minHeight: 48,
          boxShadow: `0 6px 20px ${t.primary}44`,
        }}>
          インストール
        </button>
      )}
      {state === 'prompting' && (
        <div style={{ textAlign: 'center', padding: 12, color: t.ink3, fontSize: 12 }}>
          ブラウザのダイアログを開いています…
        </div>
      )}
      {state === 'dismissed' && (
        <div style={{
          padding: 12, background: t.bgSoft, borderRadius: 10,
          fontSize: 12, color: t.ink3, textAlign: 'center',
        }}>
          キャンセルされました。あとで Settings から再度実行できます。
        </div>
      )}
      {state === 'error' && (
        <div style={{
          padding: 12, background: '#FEF2F2', borderRadius: 10,
          fontSize: 12, color: '#991B1B', textAlign: 'center',
        }}>
          ブラウザがインストールに対応していないか、すでに追加済みです。
        </div>
      )}

      <button onClick={onClose} style={{
        marginTop: 10, width: '100%',
        padding: '12px', borderRadius: 10,
        background: 'transparent', color: t.ink3,
        border: `1px solid ${t.line}`,
        fontFamily: APP_FONT, fontSize: 13, fontWeight: 600,
        letterSpacing: '-0.01em', cursor: 'pointer',
        minHeight: 44,
      }}>
        {state === 'accepted' ? '閉じる' : '後で'}
      </button>
    </ModalShell>
  );
}

// 共有シェル
function ModalShell({ children, onClose }) {
  const t = useT();
  // ESC で閉じる
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1000,
      background: 'rgba(10,10,11,0.55)',
      backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      animation: 'echoFade 0.2s ease-out',
      paddingBottom: 'env(safe-area-inset-bottom)',
    }}>
      <style>{`
        @keyframes echoFade { from { opacity: 0 } to { opacity: 1 } }
        @keyframes echoSheetUp { from { transform: translateY(40px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }
      `}</style>
      <div onClick={e => e.stopPropagation()} style={{
        background: t.bgCard,
        borderRadius: '18px 18px 0 0',
        width: '100%', maxWidth: 440,
        padding: '24px 20px 28px',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.25)',
        maxHeight: '92vh', overflowY: 'auto',
        animation: 'echoSheetUp 0.34s cubic-bezier(.2,.8,.2,1)',
        fontFamily: APP_FONT,
      }}>
        <div style={{
          width: 36, height: 4, borderRadius: 2,
          background: t.line, margin: '0 auto 18px',
        }}/>
        {children}
      </div>
    </div>
  );
}

function StepRow({ num, label, visual }) {
  const t = useT();
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '10px 12px',
      borderRadius: 10,
      background: t.bgSoft,
      marginBottom: 8,
    }}>
      <div style={{
        width: 24, height: 24, borderRadius: 12,
        background: t.ink, color: t.bgCard,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, fontWeight: 800, flexShrink: 0,
      }}>{num}</div>
      <div style={{
        flex: 1, fontSize: 13, fontWeight: 600, color: t.ink,
        letterSpacing: '-0.01em',
      }}>{label}</div>
      <div style={{ flexShrink: 0 }}>{visual}</div>
    </div>
  );
}

function BenefitRow({ t, icon, label }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: '10px 12px',
      background: t.bgSoft, borderRadius: 10,
    }}>
      <span style={{ fontSize: 18 }}>{icon}</span>
      <span style={{
        fontSize: 12, fontWeight: 600, color: t.ink,
        letterSpacing: '-0.01em',
      }}>{label}</span>
    </div>
  );
}

// Safari 共有ボタンのアイコン（四角+上矢印）
function SafariShareIcon({ t }) {
  return (
    <div style={{
      width: 36, height: 36, borderRadius: 8,
      background: '#007AFF', color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      boxShadow: '0 2px 8px rgba(0,122,255,0.35)',
    }}>
      <svg width='18' height='22' viewBox='0 0 24 28' fill='none' stroke='currentColor' strokeWidth='2.2' strokeLinecap='round' strokeLinejoin='round'>
        <path d='M12 3v16'/>
        <path d='M6 9l6-6 6 6'/>
        <path d='M4 13v11h16V13'/>
      </svg>
    </div>
  );
}

// 「ホーム画面に追加」メニュー行
function AddToHomeRow({ t }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '7px 10px',
      background: t.bgCard, border: `1px solid ${t.line}`,
      borderRadius: 8,
    }}>
      <span style={{
        fontSize: 11, fontWeight: 600, color: t.ink,
        letterSpacing: '-0.01em',
      }}>ホーム画面に追加</span>
      <div style={{
        width: 18, height: 18, borderRadius: 4,
        border: `1.5px solid ${t.ink2}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <svg width='10' height='10' viewBox='0 0 24 24' fill='none' stroke={t.ink2} strokeWidth='2.5'>
          <path d='M12 5v14M5 12h14' strokeLinecap='round'/>
        </svg>
      </div>
    </div>
  );
}

// ホーム画面アイコン風
function HomeScreenIcon({ t }) {
  return (
    <div style={{
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
    }}>
      <div style={{
        width: 34, height: 34, borderRadius: 8,
        background: `linear-gradient(135deg, ${t.primary} 0%, ${t.purple} 100%)`,
        color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 2px 6px rgba(0,0,0,0.15)',
      }}>
        {Icons.sprout(18)}
      </div>
      <div style={{
        fontSize: 8, fontWeight: 600, color: t.ink2,
        letterSpacing: '-0.01em',
      }}>Echo</div>
    </div>
  );
}

// Settings から再表示するためのエントリーポイント（hookを返す）
function useInstallPrompt() {
  const [modal, setModal] = React.useState(null); // null | 'ios' | 'native'
  const [available, setAvailable] = React.useState(!!window.__echoDeferredInstallPrompt);
  const installed = isAlreadyInstalled();

  React.useEffect(() => {
    const onAvail = () => setAvailable(true);
    const onInst  = () => { setAvailable(false); setModal(null); };
    window.addEventListener('echo:installAvailable', onAvail);
    window.addEventListener('echo:installed', onInst);
    return () => {
      window.removeEventListener('echo:installAvailable', onAvail);
      window.removeEventListener('echo:installed', onInst);
    };
  }, []);

  const open = () => {
    const p = getInstallPlatform();
    if (p === 'ios') setModal('ios');
    else setModal('native');
  };
  const close = () => setModal(null);

  const node = modal === 'ios'
    ? <InstallModalIOS onClose={close}/>
    : modal === 'native'
      ? <InstallModalNative onClose={close}/>
      : null;

  return { open, close, node, available, installed, platform: getInstallPlatform() };
}

Object.assign(window, {
  InstallBanner, InstallModalIOS, InstallModalNative,
  useInstallPrompt, getInstallPlatform, isAlreadyInstalled,
});
