/* ==========================================================================
   PrivacyPolicy.jsx | Privacy policy window
   A native <dialog> (focus stays inside, Esc closes, focus returns to the
   link that opened it). Opens from any MCPrivacyLink, or straight away when
   the page is visited at #privacy-policy. Set MC_CONFIG.privacyUrl to link to
   a separate page instead.

   DRAFT WORDING: this describes what the website itself does. Have it
   reviewed and fill in the [placeholders] before going live.
   ========================================================================== */

const MC_PRIVACY_HASH = 'privacy-policy';

function mcOpenPrivacy() {
  window.dispatchEvent(new CustomEvent('mc:open-privacy'));
}

/* A link that opens the privacy policy window (or the external page). */
function MCPrivacyLink({ children = 'Privacy policy', className = '' }) {
  if (MC_CONFIG.privacyUrl) {
    return (
      <a className={className} href={MC_CONFIG.privacyUrl}>
        {children}
      </a>
    );
  }
  return (
    <a
      className={className}
      href={`#${MC_PRIVACY_HASH}`}
      onClick={(event) => {
        event.preventDefault();
        mcOpenPrivacy();
      }}
    >
      {children}
    </a>
  );
}

function MCPrivacyDialog() {
  const dialogRef = React.useRef(null);
  const returnFocusRef = React.useRef(null);
  const contact = MC_CONFIG.contact;

  React.useEffect(() => {
    const dialog = dialogRef.current;
    if (!dialog) return undefined;

    const open = () => {
      if (dialog.open) return;
      returnFocusRef.current = document.activeElement;
      if (typeof dialog.showModal === 'function') dialog.showModal();
      else dialog.setAttribute('open', '');
      document.documentElement.classList.add('mc-dialog-open');
    };
    const handleClose = () => {
      document.documentElement.classList.remove('mc-dialog-open');
      if (window.location.hash === `#${MC_PRIVACY_HASH}`) {
        try {
          window.history.replaceState(null, '', window.location.pathname + window.location.search);
        } catch (err) {
          /* some hosts do not allow it; the hash simply stays */
        }
      }
      const back = returnFocusRef.current;
      if (back && typeof back.focus === 'function') back.focus();
    };
    const handleHash = () => {
      if (window.location.hash === `#${MC_PRIVACY_HASH}`) open();
    };

    window.addEventListener('mc:open-privacy', open);
    window.addEventListener('hashchange', handleHash);
    dialog.addEventListener('close', handleClose);
    handleHash();
    return () => {
      window.removeEventListener('mc:open-privacy', open);
      window.removeEventListener('hashchange', handleHash);
      dialog.removeEventListener('close', handleClose);
    };
  }, []);

  const close = () => {
    if (dialogRef.current) dialogRef.current.close();
  };

  // A click on the backdrop lands on the <dialog> itself.
  const handleBackdrop = (event) => {
    if (event.target === dialogRef.current) close();
  };

  const email = contact.email ? <a href={`mailto:${contact.email}`}>{contact.email}</a> : <MCPh>Email address</MCPh>;
  const phone = contact.phone ? (
    <a href={`tel:${contact.phone.replace(/\s/g, '').replace(/^0/, '+61')}`}>{contact.phone}</a>
  ) : (
    <MCPh>Phone number</MCPh>
  );

  return (
    <dialog ref={dialogRef} className="mc-privacy mc-on-base" aria-labelledby="mc-privacy-title" onClick={handleBackdrop}>
      <div className="mc-privacy__inner">
        <header className="mc-privacy__head">
          <div>
            <p className="mc-eyebrow">
              <MCIcon name="sparkle" className="mc-eyebrow__mark" />
              Dusty Cleaning
            </p>
            <h2 className="mc-privacy__title" id="mc-privacy-title">
              Privacy policy
            </h2>
          </div>
          <button type="button" className="mc-privacy__close" onClick={close} aria-label="Close privacy policy">
            <MCIcon name="close" />
          </button>
        </header>

        <div className="mc-privacy__body">
          <p className="mc-privacy__meta">
            Last updated: <MCPh>Date this policy takes effect</MCPh>
          </p>

          <p>
            Dusty Cleaning respects your privacy. This policy explains what personal information we collect, how we
            use it and how you can contact us about it. We aim to handle personal information in line with the
            Australian Privacy Principles.
          </p>

          <h3>Who we are</h3>
          <p>
            Dusty Cleaning is a cleaning business based in {contact.areas || 'Sydney'}, NSW. You can contact us by
            email at {email} or by phone on {phone}.
          </p>

          <h3>What we collect</h3>
          <p>
            When you ask for a quote or a booking, we collect the details you give us: your name, email address,
            phone number, suburb, the service you need, your property type, your preferred cleaning date and
            anything you add in the additional details.
          </p>
          <p>
            If you book a clean, we may also need your property address and any access instructions so we can do the
            job. <MCPh>If you take payments, explain how, e.g. through a payment provider, and whether you store card details</MCPh>
          </p>

          <h3>How we use it</h3>
          <ul>
            <li>To reply to your enquiry and prepare your quote.</li>
            <li>To arrange, carry out and follow up on your clean.</li>
            <li>To contact you about your booking.</li>
            <li>To keep records of the services we provide.</li>
          </ul>
          <p>
            We don’t sell your personal information. We’ll only send you marketing if you’ve agreed to receive it,
            and you can opt out at any time.
          </p>

          <h3>Who we share it with</h3>
          <p>
            We only share your information with services that help us run the business, such as{' '}
            <MCPh>the tools you use for email, bookings and accounting</MCPh>, or when the law requires us to.
          </p>

          <h3>Our website</h3>
          <p>
            This website doesn’t use advertising or tracking cookies. To display the page, it loads fonts from Adobe
            Fonts and Google Fonts, and code libraries from a content delivery network. These services may receive
            technical information such as your IP address and browser type.{' '}
            <MCPh>Update this section if you add analytics, such as Google Analytics, or advertising pixels</MCPh>
          </p>

          <h3>Keeping your information safe</h3>
          <p>
            We take reasonable steps to protect your personal information from misuse, loss and unauthorised access.{' '}
            <MCPh>Say where enquiries and customer records are stored and how long you keep them</MCPh>
          </p>

          <h3>Seeing or correcting your information</h3>
          <p>
            You can ask to see the personal information we hold about you, or ask us to correct it, by contacting us.
            We’ll respond within a reasonable time.
          </p>

          <h3>Questions and complaints</h3>
          <p>
            If you have a question or a concern about how we’ve handled your personal information, please contact us
            first so we can try to put it right. If you’re not satisfied with our response, you can contact the
            Office of the Australian Information Commissioner (OAIC) at{' '}
            <a href="https://www.oaic.gov.au" target="_blank" rel="noopener noreferrer">
              oaic.gov.au
            </a>
            .
          </p>

          <h3>Changes to this policy</h3>
          <p>We may update this policy from time to time. The latest version will always be available on this website.</p>

          <div className="mc-privacy__foot">
            <button type="button" className="mc-btn mc-btn--sm mc-btn--ghost" onClick={close}>
              Close
            </button>
          </div>
        </div>
      </div>
    </dialog>
  );
}

Object.assign(window, { MCPrivacyDialog, MCPrivacyLink, mcOpenPrivacy, MC_PRIVACY_HASH });
