import { useEffect, useRef } from "react";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { purchaseSheetModel } from "./pro-view-model.js";

export function ProPurchaseSheet({ open, product, entitlement, outcome, busy, onPurchase, onRestore, onClose, returnFocusRef }) {
  const { language } = useI18n();
  const closeRef = useRef(null);
  const previousFocusRef = useRef(null);
  useEffect(() => {
    if (open) {
      previousFocusRef.current = document.activeElement;
      closeRef.current?.focus();
      return;
    }
    (returnFocusRef?.current ?? previousFocusRef.current)?.focus?.();
  }, [open, returnFocusRef]);
  if (!open) return null;
  const model = purchaseSheetModel({ product, entitlement, outcome, language });
  return <div className="pro-sheet-backdrop" onMouseDown={event => { if (event.target === event.currentTarget) onClose?.(); }}>
    <section className="pro-sheet" role="dialog" aria-modal="true" aria-labelledby="pro-title">
      <button ref={closeRef} onClick={onClose} aria-label={model.closeLabel}>×</button>
      <h2 id="pro-title">{model.title}</h2><p>{model.description}</p>{model.price && <strong>{model.price}</strong>}{model.message && <p role="status">{model.message}</p>}
      <div><button disabled={busy || !model.canPurchase} onClick={onPurchase}>{model.purchaseLabel}</button><button disabled={busy} onClick={onRestore}>{model.restoreLabel}</button></div>
    </section>
  </div>;
}
