"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { X, ImageOff } from "lucide-react"

interface StoreMediaTipProps {
  /** Only show when true (e.g. the viewer is the shop owner). */
  enabled: boolean
  /** localStorage key — shows once and never again. */
  storageKey?: string
  /** Where the "Update now" button takes the owner. */
  settingsHref?: string
}

const TOOLTIP_WIDTH = 320
const ESTIMATED_HEIGHT = 170

interface TipPosition {
  left: number
  top?: number
  bottom?: number
  arrowX: number
}

export function StoreMediaTip({
  enabled,
  storageKey = "store-media-tip-v1",
  settingsHref = "/account/shop/settings",
}: StoreMediaTipProps) {
  const [pos, setPos] = useState<TipPosition | null>(null)

  useEffect(() => {
    if (!enabled) return

    try {
      if (localStorage.getItem(storageKey)) return
    } catch {}

    let cancelled = false

    const compute = () => {
      const target = document.querySelector<HTMLElement>("[data-store-media-tip]")
      if (!target) return

      const rect = target.getBoundingClientRect()
      if (rect.width === 0 && rect.height === 0) return

      const cx = rect.left + rect.width / 2
      const gap = 14
      const left = Math.max(
        12,
        Math.min(cx - TOOLTIP_WIDTH / 2, window.innerWidth - TOOLTIP_WIDTH - 12)
      )
      const arrowX = Math.max(24, Math.min(cx, window.innerWidth - 24))

      const spaceBelow = window.innerHeight - rect.bottom - gap
      const above = spaceBelow < ESTIMATED_HEIGHT && rect.top - gap > ESTIMATED_HEIGHT

      setPos({
        left,
        arrowX,
        ...(above
          ? { bottom: window.innerHeight - rect.top + gap }
          : { top: rect.bottom + gap }),
      })
    }

    // Small delay so the page has fully laid out before measuring the target.
    const timer = setTimeout(() => {
      if (cancelled) return
      compute()
    }, 600)

    window.addEventListener("resize", compute)
    window.addEventListener("scroll", compute, { passive: true })

    return () => {
      cancelled = true
      clearTimeout(timer)
      window.removeEventListener("resize", compute)
      window.removeEventListener("scroll", compute)
    }
  }, [enabled, storageKey])

  const dismiss = () => {
    setPos(null)
    try {
      localStorage.setItem(storageKey, "1")
    } catch {}
  }

  if (!pos) return null

  const bubbleStyle: React.CSSProperties = {
    position: "fixed",
    left: pos.left,
    width: TOOLTIP_WIDTH,
    zIndex: 60,
    top: pos.top,
    bottom: pos.bottom,
  }

  const arrowStyle: React.CSSProperties = {
    position: "fixed",
    left: pos.arrowX - 6,
    zIndex: 61,
    ...(pos.top !== undefined
      ? { top: (pos.top as number) - 6 }
      : { bottom: (pos.bottom as number) - 6 }),
  }

  return (
    <>
      {/* Arrow pointing at the banner/logo */}
      <div
        className="h-3 w-3 rotate-45 border border-purple-200 bg-white shadow-md"
        style={arrowStyle}
      />

      {/* Tooltip bubble */}
      <div
        className="fixed rounded-2xl border border-purple-200 bg-white p-4 shadow-2xl animate-in fade-in slide-in-from-bottom-2 duration-200"
        style={bubbleStyle}
        role="dialog"
        aria-label="Store banner and logo tip"
      >
        <div className="flex items-start gap-3">
          <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-purple-100">
            <ImageOff className="h-5 w-5 text-purple-600" />
          </div>
          <div className="min-w-0 flex-1">
            <div className="flex items-center justify-between gap-2">
              <h4 className="text-sm font-semibold text-gray-900">Store owner tip</h4>
              <button
                onClick={dismiss}
                aria-label="Dismiss"
                className="rounded-full p-1 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
            <p className="mt-1 text-xs leading-relaxed text-gray-500">
              If your store banner or logo looks broken or missing, you can update them
              in your shop settings.
            </p>
          </div>
        </div>
        <div className="mt-3 flex items-center justify-end gap-2">
          <button
            onClick={dismiss}
            className="rounded-full px-3 py-1.5 text-xs font-medium text-gray-500 transition-colors hover:bg-gray-100"
          >
            Got it
          </button>
          <Link
            href={settingsHref}
            onClick={dismiss}
            className="rounded-full bg-purple-600 px-3 py-1.5 text-xs font-medium text-white transition-colors hover:bg-purple-700"
          >
            Update now
          </Link>
        </div>
      </div>
    </>
  )
}
