import { useState, useEffect } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from './assets/vite.svg'
import heroImg from './assets/hero.png'
import './App.css'

function App() {
  const [count, setCount] = useState(0)
  const [photo, setPhoto] = useState(null)
  const [error, setError] = useState(null)

  const takePhoto = async () => {
    try {
      setError(null)
      // Dynamically import Capacitor plugins so the page still works in browser dev mode
      const { Camera } = await import('@capacitor/camera')
      const image = await Camera.getPhoto({
        quality: 90,
        allowEditing: false,
        resultType: 'DataUrl',
      })
      setPhoto(image.dataUrl)
    } catch (err) {
      console.error('Camera error:', err)
      setError(`Camera error: ${err.message || 'Unknown error'}. Make sure you are running on a real device.`)
    }
  }

  const openBrowser = async () => {
    try {
      // Cordova-style InAppBrowser on global window
      const InAppBrowser = window.InAppBrowser || (await import('@ionic-native/in-app-browser')).InAppBrowser
      // Options must be a comma-separated string (Cordova convention)
      const browser = InAppBrowser.create('https://xiaohong.atomgit.com', '_blank', 'location=yes,toolbar=yes,hidden=no')
      browser.addEventListener('loadstop', () => {
        console.log('Browser page loaded')
        browser.show()
      })
    } catch (err) {
      console.error('InAppBrowser error:', err)
      setError(`InAppBrowser error: ${err.message || 'Unknown error'}. Only available on device.`)
    }
  }

  const [deviceInfo, setDeviceInfo] = useState(null)
  const [deviceRaw, setDeviceRaw] = useState(null)

  // Get device info DIRECTLY from available APIs, no cordova dependency
  useEffect(() => {
    try {
      // Detect platform: hionic registers as "androidBridge" for compat,
      // use TsCapacitorPlugin as real OHOS indicator
      function isHionic() {
        try {
          return !!(window.Capacitor && window.Capacitor.Plugins && window.Capacitor.Plugins.TsCapacitorPlugin);
        } catch(e) { return false; }
      }

      var rawPlatform = ''
      try { if (window.Capacitor) rawPlatform = Capacitor.getPlatform() } catch(e) {}

      var platform = 'unknown'
      if (isHionic() || (navigator.userAgent || '').indexOf('HarmonyOS') >= 0) {
        platform = 'OpenHarmony'
      } else if (rawPlatform) {
        platform = rawPlatform.charAt(0).toUpperCase() + rawPlatform.slice(1)
      }

      var ua = navigator.userAgent || ''
      var modelMatch = ua.match(/; ([^;]+?)(?:;|\))/)
      var model = modelMatch ? modelMatch[1].trim() : 'Unknown'

      var manufacturer = ''
      if (model && model.indexOf(' ') > 0) manufacturer = model.split(' ')[0]

      var info = [
        { label: 'Model', value: model },
        { label: 'Platform', value: platform },
        { label: 'Manufacturer', value: manufacturer || 'unknown' },
      ]

      // Also read window.device if available (set by cordova_plugins.js)
      if (window.device && window.device.available) {
        if (window.device.model) info[0].value = window.device.model
        if (window.device.platform) info[1].value = window.device.platform
        if (window.device.manufacturer) info[2].value = window.device.manufacturer
        if (window.device.uuid) info.push({ label: 'UUID', value: window.device.uuid })
        if (window.device.isVirtual) info.push({ label: 'Virtual', value: window.device.isVirtual ? 'Yes' : 'No' })
      }

      setDeviceInfo(info)
      setDeviceRaw({
        available: true,
        windowDeviceExists: !!window.device,
        windowDeviceAvailable: window.device && window.device.available,
        platform: platform,
        ua: ua.substring(0, 100)
      })
    } catch (e) {
      setDeviceRaw({ error: e.message })
    }
  }, [])
  return (
    <>
      <section id="center">
        <div className="hero">
          <img src={heroImg} className="base" width="170" height="179" alt="" />
          <img src={reactLogo} className="framework" alt="React logo" />
          <img src={viteLogo} className="vite" alt="Vite logo" />
        </div>
        <div>
          <h1>Get started</h1>
          <p>
            Edit <code>src/App.jsx</code> and save to test <code>HMR</code>
          </p>
        </div>
        <button
          type="button"
          className="counter"
          onClick={() => setCount((count) => count + 1)}
        >
          Count is {count}
        </button>
      </section>

      <div className="ticks"></div>

      <section id="camera-demo">
        <h2>📸 Camera Demo</h2>
        <p>Test the <code>@capacitor/camera</code> plugin on your device</p>
        <button type="button" className="camera-btn" onClick={takePhoto}>
          Take Photo
        </button>
        {error && <p className="camera-error">{error}</p>}
        {photo && (
          <div className="photo-preview">
            <img src={photo} alt="Captured" />
          </div>
        )}
      </section>

      <div className="ticks"></div>

      <section id="browser-demo">
        <h2>🌐 InAppBrowser Demo</h2>
        <p>Open a webpage inside the app using <code>@ionic-native/in-app-browser</code></p>
        <button type="button" className="browser-btn" onClick={openBrowser}>
          Open Capacitor Website
        </button>
      </section>

      <div className="ticks"></div>

      <section id="device-demo">
        <h2>📱 Device Info</h2>
        <p>Device information from <code>@ionic-native/device</code></p>
        {deviceInfo ? (
          <table className="device-table">
            <tbody>
              {deviceInfo.map((info) => (
                <tr key={info.label}>
                  <td className="device-label">{info.label}</td>
                  <td className="device-value">{info.value}</td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <>
            <p className="device-unavailable">Device info not available. Run on a real device.</p>
            {deviceRaw && (
              <details>
                <summary>Debug: window.device state</summary>
                <pre style={{ fontSize: 10, textAlign: 'left', maxWidth: 360, overflow: 'auto' }}>
                  {JSON.stringify(deviceRaw, null, 2)}
                </pre>
              </details>
            )}
          </>
        )}
      </section>

      <div className="ticks"></div>

      <section id="next-steps">
        <div id="docs">
          <svg className="icon" role="presentation" aria-hidden="true">
            <use href="/icons.svg#documentation-icon"></use>
          </svg>
          <h2>Documentation</h2>
          <p>Your questions, answered</p>
          <ul>
            <li>
              <a href="https://vite.dev/" target="_blank">
                <img className="logo" src={viteLogo} alt="" />
                Explore Vite
              </a>
            </li>
            <li>
              <a href="https://react.dev/" target="_blank">
                <img className="button-icon" src={reactLogo} alt="" />
                Learn more
              </a>
            </li>
          </ul>
        </div>
        <div id="social">
          <svg className="icon" role="presentation" aria-hidden="true">
            <use href="/icons.svg#social-icon"></use>
          </svg>
          <h2>Connect with us</h2>
          <p>Join the Vite community</p>
          <ul>
            <li>
              <a href="https://github.com/vitejs/vite" target="_blank">
                <svg
                  className="button-icon"
                  role="presentation"
                  aria-hidden="true"
                >
                  <use href="/icons.svg#github-icon"></use>
                </svg>
                GitHub
              </a>
            </li>
            <li>
              <a href="https://chat.vite.dev/" target="_blank">
                <svg
                  className="button-icon"
                  role="presentation"
                  aria-hidden="true"
                >
                  <use href="/icons.svg#discord-icon"></use>
                </svg>
                Discord
              </a>
            </li>
            <li>
              <a href="https://x.com/vite_js" target="_blank">
                <svg
                  className="button-icon"
                  role="presentation"
                  aria-hidden="true"
                >
                  <use href="/icons.svg#x-icon"></use>
                </svg>
                X.com
              </a>
            </li>
            <li>
              <a href="https://bsky.app/profile/vite.dev" target="_blank">
                <svg
                  className="button-icon"
                  role="presentation"
                  aria-hidden="true"
                >
                  <use href="/icons.svg#bluesky-icon"></use>
                </svg>
                Bluesky
              </a>
            </li>
          </ul>
        </div>
      </section>

      <div className="ticks"></div>
      <section id="spacer"></section>
    </>
  )
}

export default App