import { useMemo, useRef } from 'react'
import { useStore } from '../store'
import { pageSrc, resolvePageUrl } from '../utils'
import WebFrame, { type WebFrameHandle } from '../components/WebFrame'

export default function Canvas(): React.JSX.Element {
  const page = useStore((s) => s.pages[s.curIdx])
  const zoom = useStore((s) => s.zoom)
  const setZoom = useStore((s) => s.setZoom)
  const frameRef = useRef<WebFrameHandle>(null)

  const src = useMemo(() => (page ? pageSrc(page) : 'about:blank'), [page])
  const baseUrl = useMemo(() => (page ? resolvePageUrl(page) : ''), [page])
  const isBlank = src === 'about:blank'

  return (
    <>
      <div className="canvas-toolbar">
        <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--c-text-soft)' }}>
          {page ? page.title : '—'}
        </span>
        <div className="ct-url" title={baseUrl}>
          {baseUrl}
        </div>
        <button
          className="icon-btn"
          title="刷新大屏页面"
          disabled={isBlank}
          onClick={() => frameRef.current?.reload()}
        >
          🔄
        </button>
        <button className="icon-btn" title="缩小" onClick={() => setZoom(zoom - 10)}>
          −
        </button>
        <span className="zoom-val">{zoom}%</span>
        <button className="icon-btn" title="放大" onClick={() => setZoom(zoom + 10)}>
          +
        </button>
      </div>
      <div className="canvas-wrap">
        <div className="canvas-stage" style={{ transform: 'scale(' + zoom / 100 + ')' }}>
          {isBlank ? <div className="canvas-empty">空白页（about:blank）</div> : <WebFrame ref={frameRef} src={src} />}
        </div>
      </div>
    </>
  )
}
