File size: 8,197 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
 * RotNot Native Bridge
 *
 * Wraps Capacitor native plugins behind feature-detection so that:
 * - In a Capacitor app: real native APIs fire (haptics, push notifications, etc.)
 * - In a plain browser (web/PWA): graceful no-ops, no import errors
 *
 * Usage:
 *   import { nativeHaptics, nativePush } from "@/lib/native";
 *   await nativeHaptics.xpGain();          // fires haptic if native, else no-op
 *   await nativePush.requestPermission();  // requests native push if available
 */

// ─── Platform Detection ────────────────────────────────────────────────────

/**
 * Returns true when running inside a Capacitor WebView.
 * Safe to call during SSR (returns false on server).
 */
export function isNative(): boolean {
  if (typeof window === "undefined") return false;
  return !!(window as Window & { Capacitor?: { isNativePlatform?: () => boolean } }).Capacitor?.isNativePlatform?.();
}

// ─── Haptics ──────────────────────────────────────────────────────────────

type HapticStyle = "light" | "medium" | "heavy";

async function triggerHaptic(style: HapticStyle = "medium"): Promise<void> {
  if (!isNative()) return;
  try {
    const { Haptics, ImpactStyle } = await import("@capacitor/haptics");
    const styleMap: Record<HapticStyle, typeof ImpactStyle[keyof typeof ImpactStyle]> = {
      light: ImpactStyle.Light,
      medium: ImpactStyle.Medium,
      heavy: ImpactStyle.Heavy,
    };
    await Haptics.impact({ style: styleMap[style] });
  } catch {
    // Plugin not available β€” silent no-op
  }
}

async function triggerNotificationHaptic(): Promise<void> {
  if (!isNative()) return;
  try {
    const { Haptics, NotificationType } = await import("@capacitor/haptics");
    await Haptics.notification({ type: NotificationType.Success });
  } catch {
    // Plugin not available β€” silent no-op
  }
}

async function triggerErrorHaptic(): Promise<void> {
  if (!isNative()) return;
  try {
    const { Haptics, NotificationType } = await import("@capacitor/haptics");
    await Haptics.notification({ type: NotificationType.Error });
  } catch {
    // Plugin not available β€” silent no-op
  }
}

export const nativeHaptics = {
  /** Light tap β€” button presses, selection changes */
  tap: () => triggerHaptic("light"),
  /** Medium impact β€” XP gained, exercise completed */
  xpGain: () => triggerHaptic("medium"),
  /** Heavy impact β€” level up, major unlock */
  levelUp: () => triggerHaptic("heavy"),
  /** Success notification pattern β€” correct answer */
  correct: () => triggerNotificationHaptic(),
  /** Error notification pattern β€” wrong answer, streak break */
  error: () => triggerErrorHaptic(),
};

// ─── Push Notifications ───────────────────────────────────────────────────

export interface PushPermissionResult {
  granted: boolean;
  token?: string;
}

export const nativePush = {
  /**
   * Request push notification permission and return the device token.
   * Returns { granted: false } in web/PWA context.
   */
  async requestPermission(): Promise<PushPermissionResult> {
    if (!isNative()) return { granted: false };
    try {
      const { PushNotifications } = await import("@capacitor/push-notifications");
      const permission = await PushNotifications.requestPermissions();
      if (permission.receive !== "granted") return { granted: false };

      await PushNotifications.register();

      return new Promise<PushPermissionResult>((resolve) => {
        const timeout = setTimeout(() => resolve({ granted: true }), 5000);

        PushNotifications.addListener("registration", (token) => {
          clearTimeout(timeout);
          resolve({ granted: true, token: token.value });
        });

        PushNotifications.addListener("registrationError", () => {
          clearTimeout(timeout);
          resolve({ granted: false });
        });
      });
    } catch {
      return { granted: false };
    }
  },
};

// ─── Local Notifications ──────────────────────────────────────────────────

export interface StreakReminderOptions {
  /** Minutes from now to fire the reminder. Default: next day at 9am. */
  delayMinutes?: number;
  streakDays: number;
}

export const nativeNotifications = {
  /**
   * Schedule a local notification reminding the user to maintain their streak.
   * No-op in web/PWA context.
   */
  async scheduleStreakReminder(opts: StreakReminderOptions): Promise<void> {
    if (!isNative()) return;
    try {
      const { LocalNotifications } = await import("@capacitor/local-notifications");
      const permission = await LocalNotifications.requestPermissions();
      if (permission.display !== "granted") return;

      const fireAt = new Date();
      if (opts.delayMinutes) {
        fireAt.setMinutes(fireAt.getMinutes() + opts.delayMinutes);
      } else {
        // Default: tomorrow at 9am
        fireAt.setDate(fireAt.getDate() + 1);
        fireAt.setHours(9, 0, 0, 0);
      }

      await LocalNotifications.schedule({
        notifications: [
          {
            id: 1001, // Fixed ID β€” overwrites previous streak reminder
            title: "πŸ”₯ Keep your streak alive!",
            body:
              opts.streakDays > 0
                ? `You're on a ${opts.streakDays}-day streak. Don't break it now!`
                : "Complete an exercise today to start a new streak.",
            schedule: { at: fireAt },
            sound: undefined,
            smallIcon: "ic_stat_icon_config_sample",
          },
        ],
      });
    } catch {
      // Plugin not available β€” silent no-op
    }
  },

  /**
   * Schedule a local notification for a spaced repetition review due.
   * No-op in web/PWA context.
   */
  async scheduleReviewReminder(dueCount: number, dueAt: Date): Promise<void> {
    if (!isNative()) return;
    try {
      const { LocalNotifications } = await import("@capacitor/local-notifications");
      const permission = await LocalNotifications.requestPermissions();
      if (permission.display !== "granted") return;

      await LocalNotifications.schedule({
        notifications: [
          {
            id: 1002, // Fixed ID β€” overwrites previous review reminder
            title: "🧠 Reviews waiting for you",
            body:
              dueCount === 1
                ? "1 Feynman topic is due for review."
                : `${dueCount} Feynman topics are due for review.`,
            schedule: { at: dueAt },
            sound: undefined,
            smallIcon: "ic_stat_icon_config_sample",
          },
        ],
      });
    } catch {
      // Plugin not available β€” silent no-op
    }
  },

  /** Cancel all scheduled reminders. */
  async cancelAll(): Promise<void> {
    if (!isNative()) return;
    try {
      const { LocalNotifications } = await import("@capacitor/local-notifications");
      await LocalNotifications.cancel({ notifications: [{ id: 1001 }, { id: 1002 }] });
    } catch {
      // Plugin not available β€” silent no-op
    }
  },
};

// ─── Status Bar ───────────────────────────────────────────────────────────

export const nativeStatusBar = {
  /**
   * Set the status bar to dark content (light background) or light (dark background).
   * RotNot uses a dark theme, so we want light text in the status bar.
   */
  async setDark(): Promise<void> {
    if (!isNative()) return;
    try {
      const { StatusBar, Style } = await import("@capacitor/status-bar");
      await StatusBar.setStyle({ style: Style.Dark });
      // Match the RotNot navy background
      await StatusBar.setBackgroundColor({ color: "#0f172a" });
    } catch {
      // Plugin not available β€” silent no-op
    }
  },
};