import { useState, useRef, useEffect } from 'react';

const PRICING_TEXT =
  'Claude 3.5 Sonnet: $3/1M input, $15/1M output, $0.30/1M cached. ' +
  'Codex CLI (GPT-4o): $2.50/1M input, $10/1M output. ' +
  'Gemini 2.5 Pro: $1.25/1M input, $10/1M output. ' +
  'Cost = (input_tokens x input_rate) + (output_tokens x output_rate) + (cached_tokens x cached_rate).';

export default function CostInfoTip() {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  return (
    <span className="relative inline-block align-middle ml-1" ref={ref}>
      <button
        onClick={() => setOpen(!open)}
        className="inline-flex items-center justify-center w-3.5 h-3.5 rounded-full bg-text-3/20 text-text-3 text-[9px] font-bold leading-none hover:bg-text-3/30 transition-colors cursor-help"
        aria-label="Cost methodology"
      >
        i
      </button>
      {open && (
        <div className="absolute z-50 bottom-full left-1/2 -translate-x-1/2 mb-2 w-72 bg-[#1a1a2e] border border-white/10 rounded-lg px-3 py-2.5 text-[10px] text-[#e2e8f0] leading-relaxed shadow-2xl">
          {PRICING_TEXT}
          <div className="absolute top-full left-1/2 -translate-x-1/2 w-2 h-2 bg-[#1a1a2e] border-r border-b border-white/10 rotate-45 -mt-1" />
        </div>
      )}
    </span>
  );
}
