import React, { useEffect } from "react";

interface IPlaceholderProps {
  text: string;
}

export function Placeholder({ text = "Digite seu CEP" }: IPlaceholderProps) {
  function waitForElm(selector: any) {
    return new Promise((resolve) => {
      if (document.querySelector(selector)) {
        return resolve(document.querySelector(selector));
      }

      const observer = new MutationObserver(() => {
        if (document.querySelector(selector)) {
          resolve(document.querySelector(selector));
          observer.disconnect();
        }
      });

      observer.observe(document.body, {
        childList: true,
        subtree: true,
      });
    });
  }

  async function ShippingSimulatorPlaceholder(): Promise<void> {
    const shippingSimulatorInput = (await waitForElm(
      ".vtex-store-components-3-x-shippingContainer .vtex-address-form-4-x-input"
    )) as any;

    if (shippingSimulatorInput !== null || shippingSimulatorInput) {
      shippingSimulatorInput.placeholder = text;
    }
  }

  useEffect(() => {
    ShippingSimulatorPlaceholder();
  }, []);

  return <></>;
}

Placeholder.schema = {
  title: "Placeholder do shipping-simulation",
  type: "object",
  properties: {
    text: {
      type: "string",
    },
  },
};
