// PRIVACY POLICY — long-form, same editorial layout as Terms.
// Sticky TOC left, cream document card right. Shares .tos__ styles via
// the className="tos priv" wrapper — we add .priv for the few overrides.

const PRIVACY_SECTIONS = [
  {
    id: "overview",
    num: "01",
    title: "Overview",
    body: [
      "This Privacy Policy describes how [INSERT LEGAL ENTITY NAME, e.g., Mahjong Matchmaker LLC] (\u201cMahjong Matchmaker,\u201d \u201cwe,\u201d \u201cus,\u201d or \u201cour\u201d) collects, uses, shares, and protects personal information in connection with the Mahjong Matchmaker mobile application, the [INSERT WEBSITE URL] website, and any related features or services (collectively, the \u201cService\u201d).",
      "Mahjong Matchmaker is based in Rhode Island. The Service is currently intended for use by residents of the United States who are at least 18 years of age. If you do not agree with this Privacy Policy, please do not use the Service.",
      { kind: "lead", label: "Important context.", text: "Mahjong Matchmaker is a matching utility. It helps willing adult players locate other willing adult players to complete a Mahjong table. We do not conduct background checks, identity verification, or any other vetting of users. Please see our Terms of Service for a full description of what the Service is and is not." }
    ]
  },
  {
    id: "what-we-collect",
    num: "02",
    title: "Information We Collect",
    body: [
      "The table below summarizes the categories of personal information we collect, the purposes for which we collect them, and the sources.",
      { kind: "table", rows: [
        ["Account data",
         "Display name, email address, phone number (if provided), password (hashed), account preferences.",
         "Create and secure your account, authenticate you, send service communications."],
        ["Profile data",
         "Profile photo, bio, stated skill level, variants played, availability, preferred play times.",
         "Present you to potential matches and show you to other users who fit your preferences."],
        ["Approximate location",
         "City or ZIP derived from IP address or user input.",
         "Match you with players in the same general area when precise location is not available."],
        ["Precise location",
         "Latitude and longitude from your device, only if you grant the system permission.",
         "Show nearby players and table openings. You can revoke this permission at any time in your device settings."],
        ["Messages & interactions",
         "In-app messages you send, match requests, RSVPs, reviews or ratings, reports of other users.",
         "Deliver messages, keep a record of who agreed to what, and enforce our Terms."],
        ["Device & technical data",
         "Device model, operating system, app version, language, time zone, unique app install ID, IP address, push notification tokens, approximate diagnostics.",
         "Operate and secure the Service, deliver push notifications, and diagnose problems."],
        ["Usage data",
         "Screens viewed, actions taken in the app, referring page on the website, session duration.",
         "Understand how the Service is used so we can improve it."],
        ["Crash & diagnostics",
         "Stack traces, device state at time of crash, anonymized diagnostic identifiers (via Sentry or Crashlytics).",
         "Identify and fix bugs."],
        ["Support correspondence",
         "The content of emails or forms you send us, and any attachments.",
         "Respond to requests, fulfill state-law privacy rights, and keep a record of the exchange."],
        ["Advertising identifiers",
         "Apple\u2019s Identifier for Advertisers (IDFA) and Google\u2019s Advertising ID (GAID), if you permit their use through the system prompt (App Tracking Transparency on iOS).",
         "Deliver in-app ads and limit how often you see the same ad (frequency capping). We do not use these identifiers to track you across other apps or websites."]
      ] },
      { kind: "lead", label: "Sources.", text: "We collect this information (a) directly from you when you sign up, fill in your profile, or use the Service; (b) automatically from your device or browser when you interact with the Service; and (c) from service providers that help us run the Service (for example, Supabase for authentication and database services, Apple Push Notification service or Firebase Cloud Messaging for push delivery, and Sentry or Crashlytics for crash reporting)." },
      { kind: "lead", label: "What we do not collect.", text: "We do not collect government identifiers (such as Social Security numbers), financial account numbers, health information, or information about children under 13. We do not purchase personal information from data brokers." }
    ]
  },
  {
    id: "how-we-use",
    num: "03",
    title: "How We Use Personal Information",
    body: [
      "We use personal information to:",
      { kind: "list", items: [
        "Provide the Service, including creating and maintaining your account, matching you with other users, delivering messages, and operating the website;",
        "Authenticate you and protect your account (including through Supabase, which acts as our authentication and database provider);",
        "Send push notifications via Apple Push Notification service (APNs) or Firebase Cloud Messaging (FCM) for match requests, messages, and service updates. You can disable push notifications at any time in your device settings;",
        "Personalize the Service, such as ranking potential matches by proximity or overlap in availability;",
        "Respond to requests, provide support, and fulfill privacy rights requests;",
        "Maintain security, prevent fraud, enforce our Terms of Service, and investigate reports of misuse;",
        "Diagnose and fix crashes and bugs using crash-reporting providers (Sentry or Crashlytics);",
        "Display advertisements in the app and on the website, including ads delivered by third-party ad networks, as described in Section 4;",
        "Understand how the Service is used in aggregate so we can improve it;",
        "Send service communications, including Privacy Policy updates, security alerts, and policy notices;",
        "Comply with applicable law, court orders, and lawful government requests."
      ] }
    ]
  },
  {
    id: "sharing",
    num: "04",
    title: "How We Share Personal Information",
    body: [
      "We share personal information only as described below.",
      { kind: "subhead", text: "With other users" },
      "When you make yourself available to match, information from your profile (such as display name, profile photo, approximate or precise location if you have enabled it, stated skill level, and availability) is shown to other users of the Service. Messages you send through the Service are shown to the recipient. Do not include in your profile or messages any information you are not comfortable sharing with other users.",
      { kind: "subhead", text: "With service providers" },
      "We share personal information with vendors that help us operate the Service, under contractual obligations that restrict their use of the information to providing services to us. These currently include:",
      { kind: "list", items: [
        "Supabase \u2014 authentication, database, storage, and real-time messaging backend.",
        "Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM) \u2014 push notification delivery.",
        "Sentry and/or Crashlytics \u2014 crash and diagnostic reporting.",
        "Email service provider \u2014 transactional email (account confirmation, password reset, policy notices).",
        "Hosting and content delivery \u2014 cloud providers that host our website and deliver images."
      ] },
      { kind: "subhead", text: "With law enforcement and to protect rights" },
      "We may disclose personal information if we believe in good faith that disclosure is necessary to comply with applicable law, a subpoena, a court order, or a lawful government request; to enforce our Terms of Service; to detect, investigate, prevent, or respond to fraud, security, or technical issues; or to protect the rights, property, or safety of Mahjong Matchmaker, our users, or the public.",
      { kind: "subhead", text: "In a corporate transaction" },
      "If Mahjong Matchmaker is involved in a merger, acquisition, financing, reorganization, bankruptcy, or sale of all or part of its assets, personal information may be transferred as part of that transaction, subject to the commitments in this Privacy Policy or a notice of material change.",
      { kind: "subhead", text: "With advertisers, sponsors, and ad networks" },
      "The Service displays advertisements and sponsored content, including in the app and, where applicable, on the website. Ads may be served by us directly or through a third-party advertising network such as [INSERT AD NETWORK(S), e.g., Google AdMob, Meta Audience Network].",
      { kind: "lead", label: "What we share.", text: "When ads are served by a third-party ad network, that network may receive a limited set of information needed to deliver ads and measure their performance, such as your device type, operating system, coarse location (derived from IP), app version, a device advertising identifier (if you have permitted its use through the operating system prompt), and ad-view and click events. We do not share your name, email, phone number, profile photo, precise location, messages, or profile content with ad networks." },
      { kind: "lead", label: "Your choices about ads.", text: "On iOS, you control whether apps can access the IDFA through Apple\u2019s App Tracking Transparency (ATT) prompt and through Settings \u2192 Privacy & Security \u2192 Tracking. On Android, you can reset or delete your Advertising ID in Settings \u2192 Google \u2192 Ads. If you opt out of the advertising identifier, you will still see ads, but they will not be personalized using that identifier." },
      { kind: "lead", label: "Cross-context behavioral advertising and California.", text: "Depending on how our ad network uses the information we provide, the delivery of ads on the Service may qualify as \u201csharing\u201d for purposes of the California Consumer Privacy Act (CCPA/CPRA) and as \u201ctargeted advertising\u201d under several other state privacy laws. You can opt out of this sharing/targeted advertising at any time by emailing [INSERT PRIVACY EMAIL] with the subject line \u201cDo Not Share \u2013 Advertising\u201d, by toggling the setting in your account preferences, or by sending us a Global Privacy Control signal from your browser when visiting the website." },
      { kind: "lead", label: "Sponsor links and events.", text: "If you click a sponsor link, visit a sponsor\u2019s website, or attend a sponsored or co-promoted event, the sponsor or event organizer may collect information from you directly. That collection is governed by their own privacy policies, not this one." },
      { kind: "subhead", text: "Aggregated or de-identified information" },
      "We may share information that has been aggregated or de-identified in a manner that cannot reasonably be used to identify you."
    ]
  },
  {
    id: "location",
    num: "05",
    title: "Location Information",
    body: [
      { kind: "lead", label: "Approximate location.", text: "We derive approximate location (such as your city or ZIP) from your IP address or from information you enter in your profile. This helps us show you potential matches in your general area." },
      { kind: "lead", label: "Precise location.", text: "Precise location (latitude and longitude) is collected only if you grant the app permission through your device\u2019s system prompt. If you grant permission, the app uses your precise location to show nearby players and table openings. You can change or revoke this permission at any time in your device\u2019s settings. Revoking permission will not delete precise location previously shared with us; please contact us if you want historical location data deleted." },
      { kind: "lead", label: "Location sharing with other users.", text: "We show other users your approximate location, never your precise coordinates, so that no user can derive your home or workplace address from the Service. Even with approximate location, please use judgment about what to share in your profile or messages." }
    ]
  },
  {
    id: "push",
    num: "06",
    title: "Push Notifications",
    body: [
      "If you opt in, we send push notifications through APNs (on iOS) or FCM (on Android) to alert you to match requests, messages, and service updates. These platforms receive a device token associated with your device. You can disable notifications at any time in your device\u2019s settings."
    ]
  },
  {
    id: "cookies",
    num: "07",
    title: "Cookies and Similar Technologies on the Website",
    body: [
      "Our website uses a limited number of cookies and similar technologies:",
      { kind: "list", items: [
        "Strictly necessary cookies to keep the site running, remember your language preference, and allow you to log in if a web login is offered.",
        "Analytics to understand aggregate traffic to the website. We use [INSERT ANALYTICS PROVIDER, e.g., Plausible, Fathom, or none]. We do not use advertising cookies and do not allow third parties to use cookies on the website to track you across other sites."
      ] },
      "Most browsers let you refuse or delete cookies. Doing so may affect the functioning of the website."
    ]
  },
  {
    id: "retention",
    num: "08",
    title: "How Long We Keep Personal Information",
    body: [
      "We keep personal information for as long as your account is active and as needed to provide the Service. When you delete your account, we delete or de-identify personal information associated with the account within thirty (30) days, except that we may retain limited information longer to: comply with legal obligations, resolve disputes, enforce our Terms, maintain security, investigate fraud, or preserve backups until they expire on their normal rotation. Messages you sent to other users will remain with the recipient unless they also delete them."
    ]
  },
  {
    id: "security",
    num: "09",
    title: "Data Security",
    body: [
      "We maintain a reasonable information security program that is designed to protect personal information against unauthorized access, disclosure, alteration, and destruction, consistent with the Rhode Island Identity Theft Protection Act of 2015 (R.I. Gen. Laws \u00a7 11-49.3 et seq.). Measures include encryption in transit (HTTPS/TLS), encryption at rest for stored personal information, access controls, activity logging, multi-factor authentication on administrative accounts, and periodic review of our security posture.",
      "No system is completely secure. We cannot guarantee that your information will never be accessed, disclosed, altered, or destroyed by a breach. In the event of a security breach affecting Rhode Island residents, we will provide notice as required by R.I. Gen. Laws \u00a7 11-49.3-4 (including, where applicable, notice to the Rhode Island Attorney General and the major consumer reporting agencies). Residents of other states will be notified as required by their state breach-notification laws."
    ]
  },
  {
    id: "children",
    num: "10",
    title: "Children",
    body: [
      "The Service is not directed to, and is not intended for, individuals under 18, and is not directed to children under 13. We do not knowingly collect personal information from children under 13, in compliance with the Children\u2019s Online Privacy Protection Act (COPPA). If we learn that we have collected personal information from a child under 13, we will delete it promptly. If you believe a child under 13 has provided us with personal information, please contact us using the information in Section 15."
    ]
  },
  {
    id: "choices",
    num: "11",
    title: "Your Choices",
    body: [
      { kind: "lead", label: "Profile.", text: "You can review and update most profile information from within your account settings." },
      { kind: "lead", label: "Precise location.", text: "You can enable or disable precise location through your device\u2019s system settings at any time." },
      { kind: "lead", label: "Push notifications.", text: "You can enable or disable push notifications through your device\u2019s system settings." },
      { kind: "lead", label: "Email preferences.", text: "Transactional emails (about your account or security) cannot be disabled while your account is active. Any marketing emails will include a clear unsubscribe link." },
      { kind: "lead", label: "Account deletion.", text: "You can delete your account from within the app or by emailing us. Deletion follows the schedule in Section 8." }
    ]
  },
  {
    id: "us-rights",
    num: "12",
    title: "United States Privacy Rights",
    body: [
      "Depending on your state of residence, you may have some or all of the following rights with respect to personal information we hold about you:",
      { kind: "list", items: [
        "Right to know / access. Request confirmation of whether we process personal information about you and, if so, a copy or summary of that information.",
        "Right to correct. Request correction of inaccurate personal information.",
        "Right to delete. Request deletion of personal information, subject to legal exceptions.",
        "Right to portability. Receive a copy of your personal information in a portable, readily usable format where technically feasible.",
        "Right to opt out. Opt out of the sale or sharing of personal information for cross-context behavioral advertising, or of certain forms of profiling. Note: we do not sell personal information for money. Depending on our ad network configuration, our delivery of in-app advertising may be treated as \u201csharing\u201d for CCPA/CPRA purposes and \u201ctargeted advertising\u201d in other states. You can opt out using the methods described in Section 4 above and under California Disclosures below.",
        "Right to non-discrimination. Exercise these rights without being denied service, charged a different price, or provided a lower quality of service.",
        "Right to appeal. In several states (including Virginia, Colorado, Connecticut, Oregon, Texas, Montana, and others), you may appeal our response to a rights request. Appeal instructions will be included in our response. If your appeal is denied, you may contact your state attorney general."
      ] },
      { kind: "lead", label: "How to exercise these rights.", text: "Email us at [INSERT PRIVACY EMAIL] with the subject line \u201cPrivacy Rights Request\u201d and describe your request. We will verify your identity, typically by confirming control of the email or phone number on your account, and respond within the time required by your state\u2019s law (generally 45 days, with a permitted extension). If we cannot verify your identity we may deny the request." },
      { kind: "lead", label: "Authorized agents.", text: "Where state law permits, you may use an authorized agent to submit a request on your behalf. We will ask the agent to provide proof of authorization and may ask you to confirm the agent\u2019s authority directly." },
      { kind: "lead", label: "California-specific disclosures.", text: "For residents of California under the California Consumer Privacy Act as amended by the California Privacy Rights Act (CCPA/CPRA): in the past 12 months, we have collected the categories of personal information described in Section 2 for the business and commercial purposes described in Section 3 and disclosed those categories to the service providers described in Section 4. We have not sold personal information for money. Depending on how our ad network processes the information we share to deliver in-app ads, that activity may constitute \u201csharing\u201d of personal information for cross-context behavioral advertising under CCPA/CPRA. California residents may opt out of this sharing at any time using the methods described in Section 4 (email, in-app setting, or Global Privacy Control signal on the website). We have not knowingly shared the personal information of consumers under 16 for cross-context behavioral advertising. California residents also have the right to limit use and disclosure of sensitive personal information; precise geolocation is treated as sensitive personal information, and we use it only to provide the Service you request, as permitted by CCPA." },
      { kind: "lead", label: "\u201cDo Not Track\u201d and global privacy controls.", text: "Our website honors the Global Privacy Control (GPC) browser signal as an opt-out of sale/share for users in states that recognize it. We do not respond to legacy \u201cDo Not Track\u201d headers, which have no uniform standard." }
    ]
  },
  {
    id: "international",
    num: "13",
    title: "Users Outside the United States",
    body: [
      "The Service is intended for users in the United States. If you access the Service from outside the United States, you acknowledge that your information will be transferred to and processed in the United States, where data protection laws may differ from those in your jurisdiction."
    ]
  },
  {
    id: "changes",
    num: "14",
    title: "Changes to This Privacy Policy",
    body: [
      "We may update this Privacy Policy from time to time. If we make a material change, we will provide reasonable notice (for example, by in-app notice, email to the address on your account, or a banner on the website) before the change takes effect. The \u201cLast Updated\u201d date at the top of this Privacy Policy shows when it was most recently revised. Your continued use of the Service after the effective date constitutes acceptance of the updated Privacy Policy."
    ]
  },
  {
    id: "contact",
    num: "15",
    title: "Contact Us",
    body: [
      "Questions, concerns, or requests regarding this Privacy Policy can be sent to:",
      { kind: "contact", lines: [
        "[INSERT LEGAL ENTITY NAME]",
        "[INSERT MAILING ADDRESS]",
        "[INSERT CITY], Rhode Island [INSERT ZIP]",
        "Privacy inquiries: [INSERT PRIVACY EMAIL]",
        "General support: [INSERT SUPPORT EMAIL]"
      ] }
    ]
  }
];

const PRIVACY_GLANCE = [
  ["Personal data linked to you", "Name, email, profile, photos, approximate and precise location (opt-in), messages, device identifier, push tokens."],
  ["Data used to track you across other apps or websites", "None from us; third-party ad networks may use the device advertising identifier (IDFA / GAID) only if you allow it through the system prompt."],
  ["Sold for money", "No."],
  ["Shared with ad networks to deliver in-app ads", "Yes (may qualify as \u201csharing\u201d under California law) — opt-out available."],
  ["Third-party processors", "Supabase (backend), APNs / FCM (push), Sentry or Crashlytics (crash reporting), email service provider, cloud hosting, and [INSERT AD NETWORK(S)] for in-app advertising."],
  ["Precise location", "Opt-in only; used to surface nearby players; never shown to other users at coordinate precision and never shared with ad networks."]
];

const PrivacyBodyBlock = ({ block }) => {
  if (typeof block === "string") return <p className="tos__p">{block}</p>;
  if (block.kind === "lead") return (
    <p className="tos__p"><strong className="tos__lead">{block.label}</strong> {block.text}</p>
  );
  if (block.kind === "callout") return (
    <div className="tos__callout" role="note">{block.text}</div>
  );
  if (block.kind === "subhead") return (
    <h4 className="priv__subhead">{block.text}</h4>
  );
  if (block.kind === "list") return (
    <ul className="tos__list">{block.items.map((it, i) => <li key={i}>{it}</li>)}</ul>
  );
  if (block.kind === "contact") return (
    <address className="tos__contact">
      {block.lines.map((l, i) => <div key={i}>{l}</div>)}
    </address>
  );
  if (block.kind === "table") return (
    <div className="priv__tableWrap">
      <table className="priv__table">
        <thead>
          <tr>
            <th>Category</th>
            <th>Examples</th>
            <th>Why we collect it</th>
          </tr>
        </thead>
        <tbody>
          {block.rows.map((r, i) => (
            <tr key={i}>
              <td><strong>{r[0]}</strong></td>
              <td>{r[1]}</td>
              <td>{r[2]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
  return null;
};

const Privacy = () => {
  const [activeId, setActiveId] = React.useState(PRIVACY_SECTIONS[0].id);
  const [tocOpen, setTocOpen] = React.useState(false);

  React.useEffect(() => {
    const ids = PRIVACY_SECTIONS.map(s => s.id);
    const els = ids.map(id => document.getElementById("priv-" + id)).filter(Boolean);
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      const visible = entries
        .filter(e => e.isIntersecting)
        .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top);
      if (visible[0]) {
        const id = visible[0].target.id.replace(/^priv-/, "");
        setActiveId(id);
      }
    }, { rootMargin: "-20% 0px -60% 0px", threshold: 0 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  const jumpTo = (id) => {
    const el = document.getElementById("priv-" + id);
    if (el) {
      const y = el.getBoundingClientRect().top + window.scrollY - 90;
      window.scrollTo({ top: y, behavior: "smooth" });
    }
    setTocOpen(false);
  };

  return (
    <section id="privacy" className="section-pad tos priv" aria-labelledby="priv-title">
      <div className="container">
        <header className="tos__header">
          <div className="eyebrow">What We Keep, What We Share</div>
          <h2 id="priv-title" className="tos__title">Privacy Policy.</h2>
          <p className="tos__intro">
            What we collect, why we collect it, who we share it with, and how you can push back. Written to match the plain-English standard of the Terms — but as specific as privacy law requires.
          </p>
          <dl className="tos__meta">
            <div><dt>Last updated</dt><dd>April 20, 2026</dd></div>
            <div><dt>Effective date</dt><dd>[Insert effective date]</dd></div>
            <div><dt>Applies to</dt><dd>United States residents, 18+</dd></div>
          </dl>
        </header>

        {/* At-a-glance summary card */}
        <div className="priv__glance">
          <div className="priv__glanceHead">
            <div className="eyebrow">At a Glance</div>
            <p>A human summary. The binding policy is the document below.</p>
          </div>
          <dl className="priv__glanceList">
            {PRIVACY_GLANCE.map((row, i) => (
              <div key={i}>
                <dt>{row[0]}</dt>
                <dd>{row[1]}</dd>
              </div>
            ))}
          </dl>
        </div>

        {/* Mobile jump menu */}
        <div className="tos__jump">
          <button
            type="button"
            className="tos__jumpBtn"
            aria-expanded={tocOpen}
            onClick={() => setTocOpen(o => !o)}
          >
            <span>Jump to section</span>
            <span style={{ fontFamily: "var(--mm-font-sans)", fontSize: 12, letterSpacing: "0.1em" }}>{tocOpen ? "CLOSE" : "OPEN"}</span>
          </button>
          {tocOpen && (
            <ol className="tos__jumpList">
              {PRIVACY_SECTIONS.map(s => (
                <li key={s.id}>
                  <button type="button" onClick={() => jumpTo(s.id)}>
                    <span className="tos__jumpNum">{s.num}</span>
                    <span>{s.title}</span>
                  </button>
                </li>
              ))}
            </ol>
          )}
        </div>

        <div className="tos__layout">
          <aside className="tos__toc" aria-label="Table of contents">
            <div className="tos__tocLabel">Contents</div>
            <ol>
              {PRIVACY_SECTIONS.map(s => (
                <li key={s.id} className={activeId === s.id ? "is-active" : ""}>
                  <a href={"#priv-" + s.id} onClick={(e) => { e.preventDefault(); jumpTo(s.id); }}>
                    <span className="tos__tocNum">{s.num}</span>
                    <span className="tos__tocTitle">{s.title}</span>
                  </a>
                </li>
              ))}
            </ol>
            <div className="tos__tocFoot">
              <a href="#terms">Read Terms of Service &rarr;</a>
            </div>
          </aside>

          <article className="tos__doc">
            {PRIVACY_SECTIONS.map(s => (
              <section key={s.id} id={"priv-" + s.id} className="tos__section">
                <div className="tos__sectionHead">
                  <div className="tos__num">{s.num}</div>
                  <h3 className="tos__h">{s.title}</h3>
                </div>
                <div className="tos__body">
                  {s.body.map((b, i) => <PrivacyBodyBlock key={i} block={b} />)}
                </div>
              </section>
            ))}

            <div className="tos__ack">
              <div className="tos__ackRule" aria-hidden="true" />
              <h4>Questions?</h4>
              <p>
                If any part of this policy is unclear, or if you want to exercise one of the privacy rights described in Section 12, email [INSERT PRIVACY EMAIL]. We\u2019d rather answer a small question now than have you wondering.
              </p>
              <div className="tos__ackFooter">
                <span>Mahjong Matchmaker &middot; Providence, Rhode Island</span>
                <a href="#top" className="tos__backTop">Back to top &uarr;</a>
              </div>
            </div>
          </article>
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { Privacy });
