import type { WordInfo } from '../../api/client'
import { speak, speechSupported } from '../../audio/speech'

// WordCard is the right-click popover for any word: its dictionary definition(s)
// on top and tappable synonym pills below. Clicking a synonym replaces the word
// in place. Both datasets are offline, so this opens instantly and fills in as
// the (local) lookup returns. Labels are bilingual (zh-first, en subtitle) to
// match the rest of Petal's chrome — the writer uses Mandarin and English.

interface Props {
  word: string
  info: WordInfo | null
  loading: boolean
  // Whether the word is in the vocabulary garden (auto-saved on lookup). The
  // heart toggles it; `onToggleSave` removes/re-adds it.
  saved: boolean
  onToggleSave: () => void
  style: React.CSSProperties
  onReplace: (synonym: string) => void
}

export function WordCard({ word, info, loading, saved, onToggleSave, style, onReplace }: Props) {
  const definitions = info?.definitions ?? []
  const synonyms = info?.synonyms ?? []
  const gloss = info?.gloss ?? ''
  const phonetic = info?.phonetic ?? ''
  const empty = !loading && !gloss && definitions.length === 0 && synonyms.length === 0

  return (
    <div
      role="dialog"
      aria-label={`Definition and synonyms for ${word}`}
      className="petal-word-card absolute z-20 p-3.5 text-sm"
      style={{
        width: 300,
        maxHeight: 340,
        overflowY: 'auto',
        background: 'var(--color-surface)',
        border: '1px solid var(--color-border)',
        borderRadius: 'var(--radius-card)',
        boxShadow: 'var(--shadow-soft)',
        ...style,
      }}
    >
      <div className="flex items-center gap-1.5">
        <span
          className="inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-bold"
          style={{ background: 'var(--color-lavender)', color: 'var(--color-plum)' }}
        >
          词语 · Word
        </span>
        <span className="font-bold" style={{ color: 'var(--color-plum)' }}>
          {word}
        </span>
        <div className="ml-auto flex items-center gap-1.5">
          {!empty && !loading && (
            <button
              type="button"
              onClick={onToggleSave}
              aria-label={saved ? 'Remove from vocabulary garden' : 'Save to vocabulary garden'}
              aria-pressed={saved}
              title={saved ? '已在词汇花园 · In your garden (tap to remove)' : '加入词汇花园 · Save to garden'}
              className="flex h-7 w-7 items-center justify-center rounded-full text-sm transition-transform"
              style={{
                background: saved ? 'var(--color-accent)' : 'var(--color-surface-alt)',
              }}
            >
              {saved ? '💚' : '🤍'}
            </button>
          )}
          {speechSupported() && (
            <button
              type="button"
              onClick={() => speak(word)}
              aria-label={`Pronounce ${word}`}
              title="朗读 · Read aloud"
              className="flex h-7 w-7 items-center justify-center rounded-full text-sm"
              style={{ background: 'var(--color-surface-alt)', color: 'var(--color-plum)' }}
            >
              🔊
            </button>
          )}
        </div>
      </div>

      {/* How to say it — the pronunciation aid for an English learner, paired
          with the 🔊 button above. */}
      {phonetic && (
        <p className="mt-1.5 text-sm" style={{ color: 'var(--color-muted)' }}>
          /{phonetic}/
        </p>
      )}

      {/* Chinese gloss first — it's what the Mandarin-speaking writer reaches for. */}
      {gloss && (
        <p
          className="mt-2.5 leading-snug"
          style={{
            color: 'var(--color-plum)',
            fontFamily: "'Nunito','PingFang SC','Microsoft YaHei','Noto Sans CJK SC',sans-serif",
          }}
        >
          {gloss}
        </p>
      )}

      {loading && (
        <div className="mt-3 inline-flex items-center gap-1.5" style={{ color: 'var(--color-muted)' }}>
          <span
            className="petal-checkpoint-dot inline-block h-2 w-2 rounded-full"
            style={{ background: 'var(--color-accent)' }}
            aria-hidden
          />
          查找中… · Looking up…
        </div>
      )}

      {definitions.length > 0 && (
        <div className="mt-3 space-y-2">
          <p className="text-xs font-bold" style={{ color: 'var(--color-muted)' }}>
            释义 · Definition
          </p>
          <ol className="space-y-1.5">
            {definitions.map((m, i) => (
              <li key={i} className="leading-snug" style={{ color: 'var(--color-plum)' }}>
                {m.part_of_speech && (
                  <span className="mr-1 italic" style={{ color: 'var(--color-accent-hover)' }}>
                    {m.part_of_speech}
                  </span>
                )}
                {m.definition}
                {m.example && (
                  <span className="mt-0.5 block italic" style={{ color: 'var(--color-muted)' }}>
                    “{m.example}”
                  </span>
                )}
              </li>
            ))}
          </ol>
        </div>
      )}

      {synonyms.length > 0 && (
        <div className="mt-3">
          <p className="mb-1.5 text-xs font-bold" style={{ color: 'var(--color-muted)' }}>
            近义词 · Synonyms <span className="font-normal">(点击替换 · tap to swap)</span>
          </p>
          <div className="flex flex-wrap gap-1.5">
            {synonyms.map((s) => (
              <button
                key={s}
                type="button"
                onClick={() => onReplace(s)}
                className="rounded-full px-3 py-1 text-xs font-semibold"
                style={{ background: 'var(--color-surface-alt)', color: 'var(--color-plum)' }}
                onMouseEnter={(e) => (e.currentTarget.style.background = 'var(--color-accent)')}
                onMouseLeave={(e) => (e.currentTarget.style.background = 'var(--color-surface-alt)')}
              >
                {s}
              </button>
            ))}
          </div>
        </div>
      )}

      {empty && (
        <p className="mt-3 leading-snug" style={{ color: 'var(--color-muted)' }}>
          没有找到这个词 · Nothing found for this word
        </p>
      )}
    </div>
  )
}
