/* ============================================================
   MUIY 2.0 — Install/reminders & caregiver sharing
   Flows, in the app's own visual language:
     · GetAppSheet        (type 'getApp')       — real PWA install + real notifications
     · CaregiversSheet    (type 'caregivers')   — invite a parent / doctor, scoped access
     · InviteCaregiverSheet (type 'inviteCaregiver')
   Backup & restore now lives in one place: the "Your data" hub (DataBackupSheet
   in me.jsx), the single source of truth for storage, saving and backups.
   ============================================================ */

/* ---------- small shared bits ---------- */
function tcStandalone() {
  try {
    return (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches) ||
      window.navigator.standalone === true;
  } catch (e) { return false; }
}
function tcOS() {
  if (typeof navigator === 'undefined') return 'web';
  const ua = (navigator.userAgent || '').toLowerCase();
  const iOS = /iphone|ipad|ipod/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
  if (iOS) return 'ios';
  if (/android/.test(ua)) return 'android';
  return 'web';
}

/* Platform + browser detection for install guidance. UA sniffing is only used
   to pick which instruction set to show — never to gate functionality. */
function tcInstallEnv() {
  const ua = ((typeof navigator !== 'undefined' && navigator.userAgent) || '').toLowerCase();
  const iPad = /ipad/.test(ua) || (typeof navigator !== 'undefined' && navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
  const iPhone = /iphone|ipod/.test(ua);
  const android = /android/.test(ua);
  const samsung = /samsungbrowser/.test(ua);
  const edge = /edg(e|a|ios)?\//.test(ua);
  const firefox = /firefox|fxios/.test(ua);
  const opera = /opr\/|opera/.test(ua);
  const chrome = /chrome|crios/.test(ua) && !samsung && !edge && !opera;
  const safari = /safari/.test(ua) && !chrome && !samsung && !edge && !firefox && !opera;
  const os = iPhone ? 'iphone' : iPad ? 'ipad' : android ? 'android' : 'desktop';
  const browser = samsung ? 'samsung' : edge ? 'edge' : chrome ? 'chrome' : firefox ? 'firefox' : safari ? 'safari' : 'other';
  const deviceWord = os === 'iphone' ? 'iPhone' : os === 'ipad' ? 'iPad' : os === 'android' ? 'phone' : 'computer';
  return { os, browser, deviceWord, ios: iPhone || iPad, android };
}

/* Manual install steps per platform + browser — shown when the native
   beforeinstallprompt isn't available (iOS Safari never fires it). */
function tcInstallSteps(env) {
  if (env.ios) {
    if (env.browser === 'safari') return [
      env.os === 'ipad' ? 'Tap the Share button (square with an arrow) at the top of Safari' : 'Tap the Share button (square with an arrow) in Safari’s toolbar',
      'Scroll down and choose “Add to Home Screen”',
      'Tap “Add” — MUIY appears with your apps',
    ];
    return [
      'Open muiy.app in Safari (installing works best there)',
      'Tap the Share button → “Add to Home Screen”',
      'Tap “Add” — MUIY appears with your apps',
    ];
  }
  if (env.android) {
    if (env.browser === 'samsung') return [
      'Tap the menu (☰) in the bottom toolbar',
      'Choose “Add page to” → “Home screen”',
      'Confirm — MUIY opens full-screen like an app',
    ];
    return [
      'Open the browser menu (⋮, top right)',
      'Tap “Install app” (or “Add to Home screen”)',
      'Confirm — MUIY opens full-screen like an app',
    ];
  }
  if (env.browser === 'chrome') return [
    'Find the install icon at the right end of the address bar (a screen with a ↓)',
    'Click it, then click “Install”',
    'MUIY opens in its own window, like a desktop app',
  ];
  if (env.browser === 'edge') return [
    'Open the menu (…) in the top-right corner',
    'Choose “Apps” → “Install MUIY”',
    'MUIY opens in its own window, like a desktop app',
  ];
  if (env.browser === 'firefox') return [
    'Firefox can’t install web apps directly',
    'Open muiy.app in Chrome, Edge or Safari',
    'Then install from that browser’s menu',
  ];
  return [
    'Open your browser’s menu',
    'Choose “Install MUIY” / “Add to Home screen”',
    'If you don’t see it, try Chrome, Edge or Safari',
  ];
}

/* Home-screen install entry point. Visible until MUIY is installed or the
   user dismisses it (remembered in settings.installCardDismissed — synced,
   so it never nags again). Install taps the native browser prompt when one
   is available; otherwise the guided Get-the-app sheet opens with steps for
   exactly this device + browser. */
function InstallAppCard({ store }) {
  const [installed, setInstalled] = React.useState(tcStandalone());
  React.useEffect(() => {
    const onInstalled = () => setInstalled(true);
    window.addEventListener('appinstalled', onInstalled);
    return () => window.removeEventListener('appinstalled', onInstalled);
  }, []);
  const dismissed = !!(store.settings && store.settings.installCardDismissed);
  if (installed || dismissed) return null;
  const env = tcInstallEnv();
  const install = () => {
    const dp = window.__deferredInstallPrompt;
    if (dp) {
      dp.prompt();
      dp.userChoice.then((c) => { if (c && c.outcome === 'accepted') store.showToast('Installing…', '🌱'); }).catch(() => {});
      window.__deferredInstallPrompt = null;
    } else {
      store.openModal('getApp', {});
    }
  };
  const dismiss = () => store.mutate((d) => { if (!d.settings) d.settings = {}; d.settings.installCardDismissed = true; });
  return (
    <div className="card" style={{ padding: '14px 15px', marginBottom: 14, position: 'relative' }}>
      <button className="icon-btn" onClick={dismiss} aria-label="Dismiss install suggestion"
        style={{ position: 'absolute', top: 9, right: 9, width: 28, height: 28, flex: 'none', background: 'var(--surface-2)' }}>
        <Icon name="x" size={13} color="var(--ink-3)" />
      </button>
      <div className="row" style={{ gap: 13, alignItems: 'center' }}>
        <div style={{ width: 44, height: 44, flex: 'none', borderRadius: 13, background: 'linear-gradient(135deg,#FF8A2B,#FC6B05)', display: 'grid', placeItems: 'center', boxShadow: '0 8px 18px -9px rgba(252,107,5,.7)' }}>
          <Icon name="download" size={22} color="#fff" />
        </div>
        <div style={{ flex: 1, minWidth: 0, paddingRight: 20 }}>
          <div style={{ fontWeight: 800, fontSize: 14.5 }}>Install MUIY on your {env.deviceWord}</div>
          <div className="body" style={{ fontSize: 12.5, marginTop: 2, lineHeight: 1.4 }}>Faster access and a more app-like experience — tap Install and we’ll guide you through the steps.</div>
        </div>
      </div>
      <button className="btn btn-primary" style={{ width: '100%', marginTop: 12, gap: 8 }} onClick={install}>
        <Icon name="download" size={16} color="#fff" /> Install
      </button>
    </div>
  );
}
function PreviewTag() {
  return <span className="chip-status" style={{ background: 'var(--slate-wash)', color: 'var(--sky-deep)', flex: 'none', fontSize: 10.5, letterSpacing: '.04em' }}>PREVIEW</span>;
}
function CloudCap({ children }) {
  return <div style={{ fontSize: 11, fontWeight: 900, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--ink-3)', margin: '2px 2px 9px' }}>{children}</div>;
}

/* ============================================================
   1 · GET THE APP — install + reminders (both real)
   (Backup & restore consolidated into the "Your data" hub — DataBackupSheet.)
   ============================================================ */
function GetAppSheet({ store, close }) {
  const [installed, setInstalled] = React.useState(tcStandalone());
  const [canPrompt, setCanPrompt] = React.useState(!!window.__deferredInstallPrompt);
  const [perm, setPerm] = React.useState(typeof Notification !== 'undefined' ? Notification.permission : 'unsupported');

  React.useEffect(() => {
    const onAvail = () => setCanPrompt(true);
    const onInstalled = () => { setInstalled(true); setCanPrompt(false); store.showToast('MUIY installed', '🌱'); };
    window.addEventListener('tc-install-available', onAvail);
    window.addEventListener('appinstalled', onInstalled);
    return () => { window.removeEventListener('tc-install-available', onAvail); window.removeEventListener('appinstalled', onInstalled); };
  }, []);

  const doInstall = async () => {
    const dp = window.__deferredInstallPrompt;
    if (dp) {
      dp.prompt();
      const choice = await dp.userChoice.catch(() => null);
      if (choice && choice.outcome === 'accepted') { store.showToast('Installing…', '🌱'); }
      window.__deferredInstallPrompt = null; setCanPrompt(false);
    }
  };

  const enableNotifications = async () => {
    if (typeof Notification === 'undefined') { store.showToast('Notifications not supported here', '⚠️'); return; }
    let p = Notification.permission;
    if (p === 'default') { p = await Notification.requestPermission().catch(() => 'denied'); setPerm(p); }
    if (p === 'granted') {
      store.mutate((d) => { if (!d.settings) d.settings = {}; d.settings.notificationsEnabled = true; });
      // fire a real confirmation reminder so it's tangible
      try {
        const body = 'Reminders are on — we’ll nudge you for doses, rest days and transfusions.';
        if (navigator.serviceWorker && navigator.serviceWorker.ready) {
          const reg = await navigator.serviceWorker.ready;
          reg.showNotification('MUIY', { body, icon: 'assets/icon-192.png', badge: 'assets/icon-192.png', tag: 'tc-welcome' });
        } else { new Notification('MUIY', { body, icon: 'assets/icon-192.png' }); }
      } catch (e) {}
      store.showToast('Reminders on', '🔔');
    } else if (p === 'denied') {
      store.showToast('Blocked — enable in browser settings', '🔕');
    }
  };

  const env = tcInstallEnv();
  const installInstructions = tcInstallSteps(env);

  const permMeta = {
    granted: { label: 'On', color: 'var(--eligible)', wash: 'var(--eligible-wash)' },
    denied: { label: 'Blocked', color: 'var(--orange)', wash: 'var(--orange-wash)' },
    default: { label: 'Off', color: 'var(--ink-3)', wash: 'var(--surface-2)' },
    unsupported: { label: 'N/A', color: 'var(--ink-3)', wash: 'var(--surface-2)' },
  }[perm] || { label: 'Off', color: 'var(--ink-3)', wash: 'var(--surface-2)' };

  return (
    <Sheet title="Get the app & reminders" sub="Put MUIY on your home screen and let it remind you — so a dose or transfusion never slips." onClose={close}>
      {/* INSTALL */}
      <CloudCap>Home-screen app</CloudCap>
      <div className="card-flat" style={{ padding: '15px 16px', marginBottom: 18 }}>
        <div className="row" style={{ gap: 13, alignItems: 'center', marginBottom: installed ? 0 : 13 }}>
          <div style={{ width: 46, height: 46, flex: 'none', borderRadius: 13, background: 'linear-gradient(135deg,#FF8A2B,#FC6B05)', display: 'grid', placeItems: 'center', boxShadow: '0 8px 18px -9px rgba(252,107,5,.7)' }}>
            <Icon name="drop" size={24} color="#fff" fill="#fff" />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 15 }}>{installed ? 'MUIY is installed' : 'Add MUIY to your phone'}</div>
            <div className="body" style={{ fontSize: 12.5, marginTop: 2, lineHeight: 1.4 }}>{installed ? 'Opens full-screen and works offline.' : 'Full-screen, offline-ready, opens in one tap.'}</div>
          </div>
          {installed && <span className="chip-status" style={{ background: 'var(--eligible-wash)', color: 'var(--eligible)', flex: 'none' }}><Icon name="check" size={12} color="var(--eligible)" sw={3} /> Done</span>}
        </div>

        {!installed && canPrompt && (
          <button className="btn btn-primary" style={{ width: '100%', gap: 8 }} onClick={doInstall}><Icon name="download" size={17} color="#fff" /> Add to Home Screen</button>
        )}
        {!installed && !canPrompt && (
          <div style={{ borderTop: '1.5px solid var(--hairline)', paddingTop: 12 }}>
            <div className="body" style={{ fontSize: 12, marginBottom: 9 }}>To install on your {env.deviceWord}:</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
              {installInstructions.map((step, i) => (
                <div key={i} className="row" style={{ gap: 11, alignItems: 'center' }}>
                  <span style={{ width: 22, height: 22, flex: 'none', borderRadius: '50%', background: 'var(--orange-wash)', color: 'var(--orange)', display: 'grid', placeItems: 'center', fontWeight: 800, fontSize: 12 }}>{i + 1}</span>
                  <span className="body" style={{ fontSize: 13, color: 'var(--ink)' }}>{step}</span>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* REMINDERS */}
      <CloudCap>Reminders</CloudCap>
      <div className="card-flat" style={{ padding: '15px 16px' }}>
        <div className="row" style={{ gap: 13, alignItems: 'center', marginBottom: 13 }}>
          <div className="me-ic" style={{ width: 44, height: 44, flex: 'none', background: permMeta.wash, color: permMeta.color }}><Icon name="bell" size={22} color={permMeta.color} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="row" style={{ gap: 7 }}><span style={{ fontWeight: 800, fontSize: 15 }}>Notifications</span><span className="chip-status" style={{ background: permMeta.wash, color: permMeta.color, flex: 'none' }}>{permMeta.label}</span></div>
            <div className="body" style={{ fontSize: 12.5, marginTop: 2, lineHeight: 1.4 }}>Dose times, donor rest-days and upcoming transfusions.</div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 13 }}>
          {[
            ['pill', 'Chelation doses', 'At your scheduled dose times'],
            ['drop', 'Transfusion due', 'A few days before each one'],
            ['users', 'Donors ready', 'When someone in your pool can give again'],
          ].map(([ic, t, d]) => (
            <div key={t} className="row" style={{ gap: 11, alignItems: 'center' }}>
              <div className="me-ic" style={{ width: 30, height: 30, flex: 'none', background: 'var(--surface-2)', color: 'var(--ink-2)' }}><Icon name={ic} size={15} color="var(--ink-2)" /></div>
              <div style={{ minWidth: 0 }}><span style={{ fontWeight: 700, fontSize: 13 }}>{t}</span><span className="body" style={{ fontSize: 12 }}> · {d}</span></div>
            </div>
          ))}
        </div>

        {perm === 'granted'
          ? <div className="row" style={{ gap: 8, padding: '2px', alignItems: 'center' }}><Icon name="checkCircle" size={17} color="var(--eligible)" /><span className="body" style={{ fontSize: 12.5, color: 'var(--ink)' }}>Reminders are on for this device.</span></div>
          : perm === 'denied'
          ? <div className="row" style={{ gap: 8, alignItems: 'flex-start' }}><Icon name="info" size={15} color="var(--orange)" style={{ flex: 'none', marginTop: 1 }} /><span className="body" style={{ fontSize: 12, lineHeight: 1.45 }}>Notifications are blocked in your browser settings. Re-enable them for this site, then come back.</span></div>
          : <button className="btn btn-primary" style={{ width: '100%', gap: 8 }} onClick={enableNotifications}><Icon name="bell" size={17} color="#fff" /> Turn on reminders</button>}
      </div>

      <div className="row" style={{ gap: 8, margin: '14px 2px 2px', alignItems: 'flex-start' }}>
        <Icon name="info" size={14} color="var(--ink-3)" style={{ flex: 'none', marginTop: 1 }} />
        <span className="body" style={{ fontSize: 11.5, lineHeight: 1.45 }}>Reminders work best with MUIY added to your home screen. Scheduled push delivery while the app is closed is rolling out with MUIY Cloud.</span>
      </div>
    </Sheet>
  );
}

/* ============================================================
   3 · CAREGIVERS & SHARING
   ============================================================ */
const TC_RELATIONS = [
  { v: 'parent', label: 'Parent', icon: 'heart' },
  { v: 'family', label: 'Family', icon: 'users' },
  { v: 'caregiver', label: 'Caregiver', icon: 'user' },
  { v: 'doctor', label: 'Doctor', icon: 'clipboard' },
];
const TC_SCOPES = [
  { v: 'full', label: 'Full access', desc: 'View & add records, manage donors and reminders' },
  { v: 'health', label: 'Health only', desc: 'Transfusions, iron, labs & chelation — no donor pool' },
  { v: 'view', label: 'View only', desc: 'Read-only summary and the doctor report' },
];
const relMeta = (v) => TC_RELATIONS.find((r) => r.v === v) || TC_RELATIONS[2];
const scopeMeta = (v) => TC_SCOPES.find((sc) => sc.v === v) || TC_SCOPES[1];
function tcInviteCode() {
  const a = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  const seg = () => Array.from({ length: 4 }, () => a[Math.floor(Math.random() * a.length)]).join('');
  return `TC-${seg()}-${seg()}`;
}

function CaregiversSheet({ store, close }) {
  const list = store.data.caregivers || [];
  const active = list.filter((c) => c.status === 'active');
  const invited = list.filter((c) => c.status !== 'active');

  const revoke = (cg) => store.openModal('confirm', {
    title: `Remove ${cg.name.split(' ')[0]}’s access?`, danger: true, confirmLabel: 'Remove',
    message: `${cg.name} will no longer be able to see or help with your MUIY records.`,
    onConfirm: () => { store.mutate((d) => { d.caregivers = (d.caregivers || []).filter((x) => x.id !== cg.id); }); store.showToast('Access removed', '🤍'); },
  });

  const CgRow = ({ cg }) => {
    const r = relMeta(cg.relation); const sc = scopeMeta(cg.scope);
    return (
      <div className="me-row" style={{ borderBottom: 'none', cursor: 'default', alignItems: 'center' }}>
        <Avatar name={cg.name} size={40} alt />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="row" style={{ gap: 7 }}>
            <span style={{ fontWeight: 800, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{cg.name}</span>
            <span className="chip-status" style={{ background: 'var(--surface-2)', color: 'var(--ink-2)', flex: 'none', fontSize: 10.5 }}>{r.label}</span>
          </div>
          <div className="body" style={{ fontSize: 12, marginTop: 1 }}>{sc.label}{cg.status !== 'active' ? ' · invite sent' : ''}</div>
        </div>
        {cg.status === 'active'
          ? <button className="icon-btn" style={{ width: 34, height: 34, flex: 'none', background: 'var(--surface-2)' }} onClick={() => revoke(cg)} aria-label="Remove access"><Icon name="x" size={15} color="var(--ink-2)" /></button>
          : <button className="link" style={{ fontSize: 12, flex: 'none' }} onClick={() => store.openModal('inviteCaregiver', { resend: cg })}>Resend</button>}
      </div>
    );
  };

  return (
    <Sheet title="Caregivers & doctors" sub="Share your records with someone you trust — a parent who helps you stay on track, or your haematologist." onClose={close}>
      <button className="btn btn-primary" style={{ width: '100%', gap: 8, marginBottom: 18 }} onClick={() => store.openModal('inviteCaregiver', {})}>
        <Icon name="plus" size={17} color="#fff" sw={2.6} /> Invite someone
      </button>

      {active.length > 0 && <React.Fragment>
        <CloudCap>Has access</CloudCap>
        <div className="card" style={{ padding: '4px 14px', marginBottom: 16 }}>
          {active.map((cg, i) => <React.Fragment key={cg.id}>{i > 0 && <div style={{ height: 1.5, background: 'var(--hairline)' }} />}<CgRow cg={cg} /></React.Fragment>)}
        </div>
      </React.Fragment>}

      {invited.length > 0 && <React.Fragment>
        <CloudCap>Invited</CloudCap>
        <div className="card" style={{ padding: '4px 14px', marginBottom: 16 }}>
          {invited.map((cg, i) => <React.Fragment key={cg.id}>{i > 0 && <div style={{ height: 1.5, background: 'var(--hairline)' }} />}<CgRow cg={cg} /></React.Fragment>)}
        </div>
      </React.Fragment>}

      {list.length === 0 && (
        <div className="card-flat" style={{ padding: '22px 18px', textAlign: 'center', marginBottom: 16 }}>
          <div style={{ width: 52, height: 52, margin: '0 auto 10px', borderRadius: 16, background: 'var(--orange-wash)', display: 'grid', placeItems: 'center' }}><Icon name="users" size={26} color="var(--orange)" /></div>
          <div style={{ fontWeight: 800, fontSize: 14.5 }}>No one else has access yet</div>
          <div className="body" style={{ fontSize: 12.5, marginTop: 4, lineHeight: 1.5 }}>Invite a parent to help manage doses and donors, or a doctor to see your trends and reports.</div>
        </div>
      )}

      {/* what they can see */}
      <CloudCap>Access levels</CloudCap>
      <div className="card-flat" style={{ padding: '6px 15px 10px', marginBottom: 14 }}>
        {TC_SCOPES.map((sc, i) => (
          <div key={sc.v} className="row" style={{ gap: 11, padding: '9px 0', borderBottom: i === TC_SCOPES.length - 1 ? 'none' : '1.5px solid var(--hairline)', alignItems: 'flex-start' }}>
            <Icon name={sc.v === 'full' ? 'checkCircle' : sc.v === 'health' ? 'chart' : 'info'} size={17} color="var(--sky-deep)" style={{ flex: 'none', marginTop: 1 }} />
            <div style={{ minWidth: 0 }}><div style={{ fontWeight: 700, fontSize: 13 }}>{sc.label}</div><div className="body" style={{ fontSize: 12, marginTop: 1, lineHeight: 1.4 }}>{sc.desc}</div></div>
          </div>
        ))}
      </div>

      <div className="row" style={{ gap: 8, margin: '0 2px', alignItems: 'flex-start' }}>
        <Icon name="info" size={14} color="var(--ink-3)" style={{ flex: 'none', marginTop: 1 }} />
        <span className="body" style={{ fontSize: 11.5, lineHeight: 1.45 }}>
          <b>Preview.</b> Invites generate a real, shareable join code. Live shared access isn’t connected yet — until then, <button className="link" style={{ fontSize: 11.5 }} onClick={() => { close(); store.goHealth('monitoring', 'report'); }}>send the doctor report</button> for a complete snapshot.
        </span>
      </div>
    </Sheet>
  );
}

function InviteCaregiverSheet({ store, close, resend }) {
  const seed = resend || {};
  const [f, setF] = React.useState({
    name: seed.name || '', relation: seed.relation || 'parent',
    scope: seed.scope || (seed.relation === 'doctor' ? 'view' : 'full'),
    contact: seed.contact || '',
  });
  const [code] = React.useState(seed.code || tcInviteCode());
  const [stage, setStage] = React.useState('form'); // form | share
  const set = (k, v) => setF((s) => {
    const n = { ...s, [k]: v };
    if (k === 'relation') n.scope = v === 'doctor' ? 'view' : v === 'parent' ? 'full' : 'health';
    return n;
  });
  const link = `https://mui.app/join/${code}`;
  const shareText = `${store.patient.name} invited you to help with their MUIY health records.\n\nJoin code: ${code}\n${link}`;

  const commit = () => {
    if (!f.name.trim()) return;
    store.mutate((d) => {
      if (!d.caregivers) d.caregivers = [];
      const existing = resend && d.caregivers.find((x) => x.id === resend.id);
      if (existing) { Object.assign(existing, { name: f.name.trim(), relation: f.relation, scope: f.scope, contact: f.contact.trim(), code, invitedAt: new Date().toISOString() }); }
      else d.caregivers.unshift({ id: TC.uid(), name: f.name.trim(), relation: f.relation, scope: f.scope, contact: f.contact.trim(), code, status: 'invited', invitedAt: new Date().toISOString() });
    });
    setStage('share');
  };

  const shareNow = async () => {
    try {
      if (navigator.share) { await navigator.share({ title: 'MUIY invite', text: shareText }); }
      else if (navigator.clipboard) { await navigator.clipboard.writeText(shareText); store.showToast('Invite copied', '📋'); }
    } catch (e) {}
  };
  const wa = () => { window.open(`https://wa.me/?text=${encodeURIComponent(shareText)}`, '_blank'); store.showToast('Sharing invite', '🟢'); };
  const copy = async () => {
    try {
      if (navigator.clipboard) await navigator.clipboard.writeText(shareText);
      store.showToast('Invite copied', '📋');
    } catch (e) {}
  };

  if (stage === 'share') {
    const r = relMeta(f.relation); const sc = scopeMeta(f.scope);
    return (
      <Sheet title="Invite ready" sub={`Send this to ${f.name.split(' ')[0]} so they can join.`} onClose={close}>
        <div className="card-flat" style={{ padding: '18px 16px', marginBottom: 16, textAlign: 'center', background: 'var(--orange-wash)', border: '1.5px solid var(--orange)' }}>
          <div className="body" style={{ fontSize: 11, fontWeight: 900, letterSpacing: '.08em', textTransform: 'uppercase', color: 'var(--orange)' }}>Join code</div>
          <div className="num" style={{ fontSize: 30, fontWeight: 800, letterSpacing: '.06em', color: 'var(--ink)', margin: '6px 0 4px' }}>{code}</div>
          <div className="body" style={{ fontSize: 12 }}>{r.label} · {sc.label}</div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <button className="btn" style={{ width: '100%', background: '#25D366', color: '#fff', gap: 8 }} onClick={wa}><Icon name="whatsapp" size={18} color="#fff" /> Share via WhatsApp</button>
          <div className="row" style={{ gap: 10 }}>
            <button className="btn btn-ghost" style={{ flex: 1, gap: 7 }} onClick={copy}><Icon name="copy" size={16} /> Copy</button>
            {typeof navigator !== 'undefined' && navigator.share && <button className="btn btn-ghost" style={{ flex: 1, gap: 7 }} onClick={shareNow}><Icon name="share" size={16} /> Share…</button>}
          </div>
        </div>
        <button className="btn btn-primary" style={{ width: '100%', marginTop: 16 }} onClick={() => { store.showToast('Invite saved', '🌱'); close(); }}>Done</button>
      </Sheet>
    );
  }

  return (
    <Sheet title={resend ? 'Edit invite' : 'Invite someone'} onClose={close}>
      <div className="field"><label className="field-label">Their name *</label><input className="input" value={f.name} onChange={(e) => set('name', e.target.value)} placeholder="e.g. Mariyam (mum)" autoFocus /></div>

      <div className="field"><label className="field-label">Relationship</label>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          {TC_RELATIONS.map((r) => {
            const on = f.relation === r.v;
            return (
              <button key={r.v} onClick={() => set('relation', r.v)} className="wf-opt" style={Object.assign({ padding: '11px 12px', gap: 9 }, on ? { borderColor: 'var(--orange)', background: 'var(--orange-wash)' } : null)}>
                <Icon name={r.icon} size={17} color={on ? 'var(--orange)' : 'var(--ink-2)'} />
                <span className="wf-opt-t" style={{ fontSize: 13.5 }}>{r.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="field"><label className="field-label">What they can see</label>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {TC_SCOPES.map((sc) => {
            const on = f.scope === sc.v;
            return (
              <button key={sc.v} onClick={() => set('scope', sc.v)} className="wf-opt" style={Object.assign({ alignItems: 'flex-start', padding: '12px 13px' }, on ? { borderColor: 'var(--orange)', background: 'var(--orange-wash)' } : null)}>
                <span className="wf-opt-tick" style={Object.assign({ marginTop: 1 }, on ? { borderColor: 'var(--orange)', background: 'var(--orange)' } : null)}>{on && <Icon name="check" size={12} color="#fff" sw={3} />}</span>
                <span style={{ flex: 1, minWidth: 0, textAlign: 'left' }}><span className="wf-opt-t" style={{ display: 'block' }}>{sc.label}</span><span className="wf-opt-d" style={{ display: 'block' }}>{sc.desc}</span></span>
              </button>
            );
          })}
        </div>
      </div>

      <div className="field"><label className="field-label">Mobile or email <span style={{ color: 'var(--ink-3)', fontWeight: 700 }}>· optional</span></label><input className="input" value={f.contact} onChange={(e) => set('contact', e.target.value)} placeholder="So we know who you invited" /></div>

      <div className="card-flat row" style={{ padding: '11px 14px', margin: '2px 0 16px', gap: 10, alignItems: 'flex-start' }}>
        <Icon name="shield" size={15} color="var(--sky-deep)" style={{ flex: 'none', marginTop: 1 }} />
        <span className="body" style={{ fontSize: 12, lineHeight: 1.45 }}>You stay in control — you can change what they see or remove their access at any time.</span>
      </div>

      <div className="row" style={{ gap: 10 }}>
        <button className="btn btn-ghost" style={{ flex: 1 }} onClick={close}>Cancel</button>
        <button className="btn btn-primary" style={{ flex: 1.4, opacity: f.name.trim() ? 1 : 0.5 }} onClick={commit}>Create invite</button>
      </div>
    </Sheet>
  );
}

Object.assign(window, { GetAppSheet, CaregiversSheet, InviteCaregiverSheet, InstallAppCard, tcInstallEnv, tcInstallSteps });
