/* ============================================================
   MUIY — Terms of Service (full, in-app)
   Plain language with a formal backbone. Mirrors the structure
   and visual language of PrivacyDataSheet (me.jsx): a summary
   banner + numbered, self-contained sections.

   Reflects the REAL app: a free, local-first, informational
   companion for the thalassaemia community (ThalFrndz, Maldives) —
   not a medical device, not medical advice. Governing law: Maldives.

   Loads AFTER me.jsx (uses PrivacyPoint look) and BEFORE shell.jsx,
   which registers it as the `terms` modal. Globals used:
   Sheet, Icon, TC, MedicalDisclaimer, window.MUI_PRIVACY_CONTACT.
   ============================================================ */

/* one numbered clause — same rhythm as PrivacyPoint, with a small
   formal section number so the document reads like real terms */
function TermsPoint({ n, q, children }) {
  return (
    <div style={{ padding: '14px 0', borderBottom: '1.5px solid var(--hairline)' }}>
      <div className="row" style={{ gap: 9, alignItems: 'flex-start', marginBottom: 6 }}>
        <span style={{ flex: 'none', minWidth: 22, height: 22, padding: '0 6px', borderRadius: 7, background: 'var(--surface-2)', color: 'var(--ink-3)', fontSize: 11.5, fontWeight: 800, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontVariantNumeric: 'tabular-nums', marginTop: 1 }}>{n}</span>
        <div style={{ flex: 1, minWidth: 0, fontWeight: 800, fontSize: 14.5, letterSpacing: '-.01em', color: 'var(--ink)', lineHeight: 1.35 }}>{q}</div>
      </div>
      <div className="body" style={{ fontSize: 13.5, lineHeight: 1.6, paddingLeft: 31 }}>{children}</div>
    </div>
  );
}

function TermsSheet({ store, close }) {
  const effective = '25 June 2026';
  const version = 'v1.0';
  const contact = (window.MUI_PRIVACY_CONTACT || '').trim();

  const openPrivacy = () => { close(); store.openModal('privacyData', {}); };
  const openContact = () => {
    if (contact) { window.location.href = `mailto:${contact}?subject=${encodeURIComponent('MUIY — Terms question')}`; return; }
    close(); store.openModal('contactUs', {});
  };

  return (
    <Sheet title="Terms of Service" onClose={close}>
      {/* plain-language summary banner */}
      <div style={{ background: 'var(--orange-wash)', borderRadius: 16, padding: '15px 16px', display: 'flex', gap: 13, alignItems: 'flex-start' }}>
        <div style={{ width: 42, height: 42, flex: 'none', borderRadius: 12, background: 'var(--surface)', display: 'grid', placeItems: 'center', boxShadow: 'var(--sh-sm)' }}>
          <Icon name="clipboard" size={22} color="var(--orange)" />
        </div>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontWeight: 800, fontSize: 15, letterSpacing: '-.01em' }}>MUIY is a companion — not your care team</div>
          <div className="body" style={{ fontSize: 12.5, marginTop: 3, lineHeight: 1.5 }}>
            In short: MUIY is a free tool to help you organise and understand your own thalassaemia care. It’s for information and self-management only — it never replaces your doctor, and it isn’t for emergencies. Using the app means you agree to the terms below.
          </div>
        </div>
      </div>

      {/* the standing medical-advice line, in the app's own voice */}
      {typeof MedicalDisclaimer !== 'undefined' && (
        <div style={{ marginTop: 12 }}><MedicalDisclaimer variant="card" /></div>
      )}

      <div style={{ marginTop: 6 }}>
        <TermsPoint n="1" q="About these terms">
          These Terms of Service (“Terms”) are an agreement between you and MUIY — a community project built by and for people living with thalassaemia, connected to the ThalFrndz community in the Maldives. They cover your use of the MUIY app on any device. By creating a profile or otherwise using MUIY, you confirm that you’ve read, understood and accepted these Terms. If you don’t agree with them, please don’t use the app.
        </TermsPoint>

        <TermsPoint n="2" q="What MUIY is — and what it isn’t">
          MUIY is an <b>informational and self-management companion</b>. It helps you keep your medical profile, transfusions, iron levels, lab results, chelation doses, appointments and blood-donor pool together in one calm place, and it offers gentle insights, reminders and forecasts built from the details you enter.
          <br /><br />
          MUIY is <b>not a medical device</b>, not a diagnostic tool, and not a regulated health service. Its forecasts, target ranges, dose figures and insights are <b>estimates for your information only</b> — helpful for planning and for conversations with your care team, never instructions to act on by themselves.
        </TermsPoint>

        <TermsPoint n="3" q="Not medical advice — and not for emergencies">
          Nothing in MUIY is medical advice, and using it does not create any doctor–patient relationship. Always follow the guidance and prescriptions of your haematologist and care team, who know your full clinical picture. Never start, stop or change a transfusion schedule, chelation medicine or dose because of something the app shows you, without first speaking to your clinician.
          <br /><br />
          <b>MUIY is not for emergencies.</b> If you have urgent symptoms or feel unwell, contact your treatment centre or your local emergency number straight away — do not wait on or rely on the app.
        </TermsPoint>

        <TermsPoint n="4" q="Who can use MUIY (age & eligibility)">
          MUIY is intended for people living with thalassaemia and the family members or caregivers who help manage their care. You should be at least <b>18 years old</b> to accept these Terms and use the app on your own.
          <br /><br />
          A child or young person under 18 may use MUIY only with the involvement and consent of a parent or legal guardian, who accepts these Terms on their behalf and stays responsible for that use. If you’re a caregiver setting up MUIY for someone you look after, you confirm you have the authority to do so.
        </TermsPoint>

        <TermsPoint n="5" q="Your account & sign-in">
          You can use MUIY locally on your device, or sign in with Google to identify yourself. If you sign in, please keep your account and your device secure — anyone who can unlock your device can see the health information stored in the app. Turning on <b>App lock</b> (Me → Privacy &amp; security) adds a passcode or biometric lock and encrypts your data at rest on that device. You’re responsible for activity that happens through your device and account.
        </TermsPoint>

        <TermsPoint n="6" q="Keeping your information accurate">
          MUIY’s insights are only as good as what you put in. You’re responsible for the accuracy of the details you enter — your medical profile, weight, transfusions, lab values, medications and dose times. Keeping them current helps your reminders and forecasts stay meaningful, but it remains your care team’s job, not the app’s, to confirm anything clinical.
        </TermsPoint>

        <TermsPoint n="7" q="Acceptable use">
          MUIY is for your own personal, non-commercial health management. Please don’t:
          <br /><br />
          • use the app for anything unlawful, or in any way that could harm you or others;<br />
          • try to copy, resell, sublicense or commercialise the app or its content;<br />
          • reverse-engineer, tamper with, or attempt to break the app’s security or extract other people’s data;<br />
          • upload content that isn’t yours to share, or that is harmful, abusive or infringing;<br />
          • rely on the app as a substitute for professional medical care.
        </TermsPoint>

        <TermsPoint n="8" q="Other people’s information (donors & caregivers)">
          MUIY lets you store donor contacts and invite a caregiver or doctor. When you add someone else’s details — a donor’s name and phone number, or a person you invite — you confirm you have their agreement to do so. Please use their information only to coordinate your own care, keep it accurate, and remove or archive it if they ask you to. You’re responsible for how you contact and treat the people in your pool.
        </TermsPoint>

        <TermsPoint n="9" q="Your data & privacy">
          MUIY is <b>local-first</b>: your health records live in your device’s storage, not on a MUIY server, and our team holds no copy of them. The only thing that leaves your device is information you deliberately send — such as feedback or a caregiver invite. How we handle all of this is set out in full in the <b>Privacy &amp; data</b> notice, which forms part of these Terms.
          <br /><br />
          Because your data is local, <b>keeping a backup is your responsibility</b> — if you clear your browser, change phones or lose your device, anything you haven’t exported is gone. Use Me → Data → Export a copy to keep a portable backup.
          <div style={{ marginTop: 11 }}>
            <button className="btn btn-ghost" style={{ width: '100%', gap: 8 }} onClick={openPrivacy}>
              <Icon name="shield" size={17} color="var(--sky-deep)" /> Read Privacy &amp; data
            </button>
          </div>
        </TermsPoint>

        <TermsPoint n="10" q="Ownership & intellectual property">
          The MUIY name, design, content and software belong to the MUIY project and its contributors, and are protected by intellectual-property laws. You’re given a personal, limited, non-exclusive, non-transferable licence to use the app for your own care. <b>Your own data is, and remains, yours</b> — these Terms give us no ownership of your health records, and you can export or delete them at any time.
        </TermsPoint>

        <TermsPoint n="11" q="Third-party services">
          MUIY uses a few trusted third-party services to work — for example Google sign-in, and a secure database that receives only the feedback you choose to submit. Your use of those services is also governed by their own terms and privacy policies. MUIY isn’t responsible for third-party services it doesn’t control, and links or tools that lead outside the app are provided for convenience only.
        </TermsPoint>

        <TermsPoint n="12" q="Availability & changes to the app">
          MUIY is offered free of charge and provided <b>“as is”</b> by a small community team. We work to keep it reliable and improve it over time, but we can’t promise it will always be available, error-free or uninterrupted, and features may change, pause or be removed. (If a future version ever introduces a paid option, any charges and their terms would be made clear to you before you opt in.)
        </TermsPoint>

        <TermsPoint n="13" q="Disclaimers & limitation of liability">
          To the fullest extent allowed by law, MUIY is provided without warranties of any kind, whether express or implied — including that it will be accurate, complete, fit for a particular purpose, or suitable for any clinical decision.
          <br /><br />
          MUIY, the ThalFrndz community and the project’s contributors will not be liable for any harm, loss or damage arising from your use of — or inability to use — the app, or from relying on its estimates instead of professional medical advice. You use MUIY as a self-management aid, at your own discretion and responsibility, alongside (never in place of) your care team. Nothing in these Terms limits any liability that cannot be limited under the law of the Maldives.
        </TermsPoint>

        <TermsPoint n="14" q="Suspending or ending your use">
          You can stop using MUIY at any time, and remove everything from your device with Me → Data → Clear all data (this is permanent — export a copy first if you’d like to keep one). We may also suspend or limit access to the app, or to particular features, if needed to protect users, comply with the law, or keep the service working — for example in response to misuse under the acceptable-use section above.
        </TermsPoint>

        <TermsPoint n="15" q="Changes to these terms">
          We may update these Terms from time to time as the app evolves. When we make a meaningful change, we’ll update the date below and, where appropriate, let you know in the app. Continuing to use MUIY after an update means you accept the revised Terms; if you don’t agree with a change, please stop using the app and clear your data.
        </TermsPoint>

        <TermsPoint n="16" q="Governing law & disputes">
          These Terms are governed by the laws of the <b>Republic of Maldives</b>, and any dispute relating to MUIY or these Terms will be subject to the courts of the Maldives. If any part of these Terms is found unenforceable, the rest stays in effect. We’d always prefer to sort out any concern with you directly and kindly first — please reach out before anything formal.
        </TermsPoint>

        <div style={{ padding: '14px 0 2px' }}>
          <div style={{ fontWeight: 800, fontSize: 14, letterSpacing: '-.01em', marginBottom: 5 }}>Questions about these terms?</div>
          <div className="body" style={{ fontSize: 13, lineHeight: 1.55, marginBottom: 11 }}>
            {contact
              ? <>Email us at <b>{contact}</b>, or reach the team through the in-app feedback form — we’re a small community and we read everything you send.</>
              : <>Reach the team through the in-app feedback form — we’re a small community and we read everything you send.</>}
          </div>
          <button className="btn btn-ghost" style={{ width: '100%', gap: 8 }} onClick={openContact}>
            <Icon name="chat" size={17} color="var(--green)" /> {contact ? 'Contact us about the terms' : 'Send a question'}
          </button>
        </div>
      </div>

      <div className="body" style={{ fontSize: 11.5, textAlign: 'center', marginTop: 16, color: 'var(--ink-3)' }}>
        Effective {effective} · {version} · MUIY v{TC.APP_VERSION}
      </div>
    </Sheet>
  );
}

Object.assign(window, { TermsSheet });
