// My Room Plus: the upgrade window, with Stripe's pricing table inside an XP window.
//
// Loaded by index.html as <script type="text/babel" src="PremiumPricingModal.jsx"> before
// the main app, so it can use the app's shared pieces (RetroWindow, PLUS_ROWS, PLUS_PRICE,
// DB) once the app runs. The app shows it whenever a free member reaches for a Plus
// feature: creating a chat room, the Big or Huge Room, Plus-only chat rooms, Buddy List colors.
//
// How a payment reaches the right member: the pricing table is given the signed-in
// member's id as client-reference-id. Stripe returns it with the finished checkout, and
// the stripe-webhook server function uses it to switch that member's plan to Plus.

// Stripe's pricing table (live mode: real cards are charged). The publishable key is meant to be public.
const STRIPE_PRICING = {
  tableId: 'prctbl_1ULYZcGYApju6wQeZkxbH2ic',
  publishableKey: 'pk_live_51ULVmIGYApju6wQee3p4749JLJTHYFXq3SpqXzl3R4p21mej7Cjbaf3qYEhfTK2gDSfEsOriJtqRKsgdMuTFAoLo005HZubqmC',
  script: 'https://js.stripe.com/v3/pricing-table.js',
};

// Adds Stripe's pricing-table script to the page the first time it's needed.
function useStripePricingScript() {
  const [ready, setReady] = React.useState(() => !!window.customElements?.get('stripe-pricing-table'));
  React.useEffect(() => {
    if (ready) return undefined;
    let tag = document.querySelector(`script[src="${STRIPE_PRICING.script}"]`);
    if (!tag) {
      tag = document.createElement('script');
      tag.src = STRIPE_PRICING.script;
      tag.async = true;
      document.head.appendChild(tag);
    }
    const done = () => setReady(true);
    const failed = () => setReady('failed');
    tag.addEventListener('load', done);
    tag.addEventListener('error', failed);
    return () => { tag.removeEventListener('load', done); tag.removeEventListener('error', failed); };
  }, [ready]);
  return ready;
}

function StripePricingTable({ clientReferenceId }) {
  const ready = useStripePricingScript();
  if (ready === 'failed') {
    return <p className="plus-reason">Couldn't load secure checkout. Check your connection and try again.</p>;
  }
  return (
    <div className="plus-stripe" aria-busy={!ready}>
      {!ready && <p className="text-[11px]" style={{ color: 'var(--muted)' }}>Loading secure checkout...</p>}
      {/* A web component: React passes these straight through as HTML attributes. */}
      <stripe-pricing-table
        pricing-table-id={STRIPE_PRICING.tableId}
        publishable-key={STRIPE_PRICING.publishableKey}
        client-reference-id={clientReferenceId}
      />
    </div>
  );
}

// isPlus: already a member. reason: what the member just tried to use.
// memberId: the signed-in member's id on the live site (null for guests and the prototype).
function PremiumPricingModal({ isPlus, reason, memberId, onUpgrade, onManageBilling, onClose }) {
  const onCloseRef = React.useRef(onClose);
  onCloseRef.current = onClose;
  React.useEffect(() => {
    const onKey = e => { if (e.key === 'Escape') onCloseRef.current(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);
  const live = DB.live;

  return ReactDOM.createPortal(
    // The scrim covers the whole desktop, so nothing behind it can be clicked until this closes.
    <div className="fixed inset-0 z-[1000] grid place-items-center p-3 modal-scrim catalog-scrim" role="dialog" aria-modal="true" aria-labelledby="plus-title"
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <RetroWindow title="My Room Plus" titleId="plus-title" icon="Star" floating controls={false} onClose={onClose}
        className="w-full max-w-[620px] pop-in" bodyClass="p-0 flex flex-col">
        <header className="plus-cover">
          <div className="min-w-0">
            <div className="plus-kicker">TwoFour Retro Labs presents</div>
            <h2 className="plus-title">My Room <span>Plus</span></h2>
            <p className="plus-price"><b>{PLUS_PRICE}</b> a month</p>
          </div>
          <span className="plus-star" aria-hidden="true">★</span>
        </header>
        <div className="p-3 flex flex-col gap-3 plus-body">
          {isPlus
            ? <p className="plus-reason ok">★ You're a Plus member! Every chat room, your own rooms, Buddy List colors and the Big Room are all yours.</p>
            : reason && <p className="plus-reason">{reason}</p>}
          <table className="plus-table">
            <thead>
              <tr><th scope="col" /><th scope="col">Free</th><th scope="col" className="plus-col">Plus</th></tr>
            </thead>
            <tbody>
              {PLUS_ROWS.map(([what, free, plus]) => (
                <tr key={what}><th scope="row">{what}</th><td>{free}</td><td className="plus-col">{plus}</td></tr>
              ))}
            </tbody>
          </table>

          {isPlus ? (
            <div className="flex flex-wrap items-center justify-end gap-2">
              <button type="button" className="btn mr-auto" onClick={onManageBilling}>{live ? 'Manage Billing' : 'Cancel Plus'}</button>
              <button type="button" className="btn font-bold min-w-[90px]" onClick={onClose}>OK</button>
            </div>
          ) : live && memberId ? (
            <>
              <StripePricingTable clientReferenceId={memberId} />
              <div className="flex flex-wrap items-center justify-between gap-2">
                <span className="text-[10px]" style={{ color: 'var(--muted)' }}>Secure checkout by Stripe. Plus renews monthly; cancel any time from Manage Billing.</span>
                <button type="button" className="btn" onClick={onClose}>Maybe Later</button>
              </div>
            </>
          ) : live ? (
            <>
              <p className="plus-reason">Guests can't get Plus. Sign off and click <b>New Member? Sign Up FREE!</b> to make your own screen name, then come back for Plus.</p>
              <div className="flex justify-end"><button type="button" className="btn" onClick={onClose}>OK</button></div>
            </>
          ) : (
            <>
              <div className="flex flex-wrap items-center justify-end gap-2">
                <button type="button" className="btn" onClick={onClose}>Maybe Later</button>
                <button type="button" className="btn font-bold plus-go" onClick={onUpgrade}>★ Upgrade for {PLUS_PRICE}/month</button>
              </div>
              <p className="text-[10px]" style={{ color: 'var(--muted)' }}>
                Prototype: no payment is taken. Upgrading just switches Plus on for this screen name in this browser.
                On myroomweb.com this opens secure Stripe checkout.
              </p>
            </>
          )}
        </div>
      </RetroWindow>
    </div>,
    document.querySelector('.app') || document.body,
  );
}
