import { useEffect } from 'react';

import { type ReactNativeWebViewType } from 'src/types/login';

const STYLE_ELEMENT_ID = 'webview-native-overrides';

const VIEWPORT_CONTENT =
  'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';

/**
 * Injects native-feeling CSS overrides and a locked viewport meta tag while
 * the host page is rendered inside the React Native WebView. Disables text
 * selection, callouts, tap highlights, scrollbars, overscroll bounce, iOS
 * text-size auto-adjust and pinch-to-zoom so the module behaves closer to a
 * native screen.
 *
 * No-ops outside the WebView so desktop/browser usage keeps native selection
 * and scrolling behavior.
 */
const useWebViewStyles = () => {
  useEffect(() => {
    const isWebView = !!(window as ReactNativeWebViewType).ReactNativeWebView;
    if (!isWebView) return;

    // Avoid double-injection if the hook somehow mounts twice (StrictMode,
    // overlapping route transitions, etc.).
    if (document.getElementById(STYLE_ELEMENT_ID)) return;

    // Lock the viewport so the WebView can't be pinch-zoomed.
    let meta = document.querySelector<HTMLMetaElement>('meta[name="viewport"]');
    const createdMeta = !meta;
    if (!meta) {
      meta = document.createElement('meta');
      meta.setAttribute('name', 'viewport');
      document.head.appendChild(meta);
    }
    const prevViewportContent = meta.getAttribute('content');
    meta.setAttribute('content', VIEWPORT_CONTENT);

    const style = document.createElement('style');
    style.id = STYLE_ELEMENT_ID;
    style.textContent = `
      * {
        -webkit-user-select: none;
        user-select: none;
        -webkit-touch-callout: none;
        -webkit-tap-highlight-color: transparent;
      }
      html {
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
      }
      html, body {
        overscroll-behavior: none;
        -webkit-text-size-adjust: 100%;
      }
      input, textarea {
        -webkit-user-select: text;
        user-select: text;
      }
      /* Prevent iOS Safari auto-zoom on input focus */
      input, select, textarea {
        font-size: 16px;
      }
      img {
        -webkit-user-drag: none;
        user-drag: none;
      }
      ::-webkit-scrollbar { display: none; }
    `;
    document.head.appendChild(style);

    return () => {
      style.remove();
      if (createdMeta) {
        meta.remove();
      } else if (prevViewportContent) {
        meta.setAttribute('content', prevViewportContent);
      }
    };
  }, []);
};

export default useWebViewStyles;
