File size: 2,413 Bytes
c0a9bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useEffect } from 'react';
import { getFeatureFlags, markFeatureViewed, type Feature } from '~/lib/api/features';

const VIEWED_FEATURES_KEY = 'bolt_viewed_features';

const getViewedFeatures = (): string[] => {
  try {
    const stored = localStorage.getItem(VIEWED_FEATURES_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch {
    return [];
  }
};

const setViewedFeatures = (featureIds: string[]) => {
  try {
    localStorage.setItem(VIEWED_FEATURES_KEY, JSON.stringify(featureIds));
  } catch (error) {
    console.error('Failed to persist viewed features:', error);
  }
};

export const useFeatures = () => {
  const [hasNewFeatures, setHasNewFeatures] = useState(false);
  const [unviewedFeatures, setUnviewedFeatures] = useState<Feature[]>([]);
  const [viewedFeatureIds, setViewedFeatureIds] = useState<string[]>(() => getViewedFeatures());

  useEffect(() => {
    const checkNewFeatures = async () => {
      try {
        const features = await getFeatureFlags();
        const unviewed = features.filter((feature) => !viewedFeatureIds.includes(feature.id));
        setUnviewedFeatures(unviewed);
        setHasNewFeatures(unviewed.length > 0);
      } catch (error) {
        console.error('Failed to check for new features:', error);
      }
    };

    checkNewFeatures();
  }, [viewedFeatureIds]);

  const acknowledgeFeature = async (featureId: string) => {
    try {
      await markFeatureViewed(featureId);

      const newViewedIds = [...viewedFeatureIds, featureId];
      setViewedFeatureIds(newViewedIds);
      setViewedFeatures(newViewedIds);
      setUnviewedFeatures((prev) => prev.filter((feature) => feature.id !== featureId));
      setHasNewFeatures(unviewedFeatures.length > 1);
    } catch (error) {
      console.error('Failed to acknowledge feature:', error);
    }
  };

  const acknowledgeAllFeatures = async () => {
    try {
      await Promise.all(unviewedFeatures.map((feature) => markFeatureViewed(feature.id)));

      const newViewedIds = [...viewedFeatureIds, ...unviewedFeatures.map((f) => f.id)];
      setViewedFeatureIds(newViewedIds);
      setViewedFeatures(newViewedIds);
      setUnviewedFeatures([]);
      setHasNewFeatures(false);
    } catch (error) {
      console.error('Failed to acknowledge all features:', error);
    }
  };

  return { hasNewFeatures, unviewedFeatures, acknowledgeFeature, acknowledgeAllFeatures };
};