/* Clear Mint — System pages: Reports, AI Insights, Settings */
const { MetricCard, ChartCard, DonutChart, TrendChart, ProgressBar, Legend } = window;
const { KpiRow, StatusPill, ActivityList, VBars, CMC } = window;
const Is = window.CMIcon;
const { G, PU, AM, BL, SL, RD, TEAL, PINK, INDIGO } = CMC;
const tints = window.tintFor;

/* ============================ REPORTS ============================ */
function PageReports() {
  const reports = [
    {ic:<Is.Investments size={18}/>,c:G,name:'Net Worth Statement',desc:'Full snapshot of assets, liabilities & net worth',period:'Monthly'},
    {ic:<Is.Transactions size={18}/>,c:PU,name:'Income & Expense',desc:'Earnings vs spending by category',period:'Monthly'},
    {ic:<Is.Transfer size={18}/>,c:BL,name:'Cash Flow Report',desc:'Money in and out over time',period:'Quarterly'},
    {ic:<Is.Reports size={18}/>,c:AM,name:'Tax Summary',desc:'Deductions, income & capital gains',period:'Annual'},
    {ic:<Is.Bars size={18}/>,c:TEAL,name:'Investment Performance',desc:'Returns, allocation & dividends',period:'Quarterly'},
  ];
  return (
    <div>
      <KpiRow>
        <MetricCard label="Net Worth" labelColor="var(--green-600)" value="$852,650" delta={{dir:'pos',text:'6.1%'}}/>
        <MetricCard label="Savings Rate" labelColor="var(--green-600)" value="32%" delta={{dir:'pos',text:'4%'}}/>
        <MetricCard label="Income (YTD)" value="$86,400" sub="5 months"/>
        <MetricCard label="Expenses (YTD)" labelColor="var(--red-500)" value="$58,200" sub="5 months"/>
      </KpiRow>
      <div className="cm-grid-2a">
        <ChartCard title="Income vs Expenses"
          action={<div className="cm-seg">{['6M','1Y','All'].map(t=><button key={t} className={t==='6M'?'active':''}>{t}</button>)}</div>}>
          <div style={{display:'flex',gap:24,marginBottom:8}}>
            <span className="t-caption" style={{display:'flex',alignItems:'center',gap:6}}><span style={{width:9,height:9,borderRadius:2,background:G}}/>Income</span>
            <span className="t-caption" style={{display:'flex',alignItems:'center',gap:6}}><span style={{width:9,height:9,borderRadius:2,background:'#FBD0D2'}}/>Expenses</span>
          </div>
          <div className="cm-vbars" style={{height:220}}>
            {[['Dec',17,11],['Jan',17.2,11.6],['Feb',16.8,11.2],['Mar',18,12],['Apr',17.4,11.8],['May',17.2,11.4]].map((m,i)=>(
              <div className="cm-vbar" key={i} style={{justifyContent:'flex-end'}}>
                <div style={{display:'flex',gap:5,alignItems:'flex-end',width:'100%',justifyContent:'center',height:'100%'}}>
                  <div style={{width:16,borderRadius:'6px 6px 3px 3px',background:G,height:`${m[1]/18*100}%`}}/>
                  <div style={{width:16,borderRadius:'6px 6px 3px 3px',background:'#FBD0D2',height:`${m[2]/18*100}%`}}/>
                </div>
                <div className="lbl">{m[0]}</div>
              </div>
            ))}
          </div>
        </ChartCard>
        <ChartCard title="Available Reports">
          <div>
            {reports.map((r,i)=>(
              <div className="cm-act" key={i}>
                <div className="cm-act-ic" style={{background:tints(r.c),color:r.c}}>{r.ic}</div>
                <div className="cm-act-body"><div className="cm-act-title">{r.name}</div><div className="cm-act-sub">{r.desc}</div></div>
                <div className="cm-act-right"><StatusPill tone="slate">{r.period}</StatusPill></div>
              </div>
            ))}
          </div>
          <button className="cm-btn cm-btn-soft" style={{width:'100%',justifyContent:'center',marginTop:14}}>Generate Custom Report</button>
        </ChartCard>
      </div>
    </div>
  );
}
window.PageReports = PageReports;

/* ============================ AI INSIGHTS ============================ */
function PageAI() {
  const insights = [
    {ic:<Is.Spark size={18}/>,c:G,tone:'green',tag:'Opportunity',title:'Refinance your mortgage',body:'Rates dropped to 3.85%. Refinancing could save you an estimated $214/month over your current 4.29% rate.',impact:'+$2,568 / yr'},
    {ic:<Is.Film size={18}/>,c:RD,tone:'red',tag:'Wasted spend',title:'Unused subscription detected',body:'You haven\u2019t used Peloton in 3 months. Cancelling would free up $24/month.',impact:'+$288 / yr'},
    {ic:<Is.Wallet size={18}/>,c:BL,tone:'blue',tag:'Savings',title:'Move idle cash to high-yield',body:'$18,750 is sitting in checking at 0.01%. A 4.5% APY savings account would earn more.',impact:'+$843 / yr'},
    {ic:<Is.Investments size={18}/>,c:PU,tone:'green',tag:'Allocation',title:'Rebalance your portfolio',body:'Your tech allocation drifted to 18%, above your 12% target. Consider rebalancing to manage risk.',impact:'Risk \u2193'},
  ];
  const toneMap = {green:'cm-pill-green',red:'cm-pill-red',blue:'cm-pill-blue'};
  return (
    <div>
      <div className="cm-card cm-card-pad cm-mb-24" style={{background:'linear-gradient(180deg,#F4FBF8,#EAF7F1)',border:'1px solid var(--mint-100)'}}>
        <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:14}}>
          <span className="cm-tile-ic" style={{background:'#fff',color:G}}><Is.Spark size={22}/></span>
          <div>
            <div className="t-h2">Ask Clear AI</div>
            <div className="t-caption">Get instant answers about your loans, assets, budget & net worth.</div>
          </div>
        </div>
        <div className="cm-search" style={{width:'100%',maxWidth:'none',background:'#fff'}}>
          <Is.Spark size={18}/>
          <input placeholder="e.g. How can I pay off my mortgage faster?"/>
          <button className="cm-btn cm-btn-primary" style={{padding:'6px 14px'}}>Ask</button>
        </div>
      </div>
      <KpiRow>
        <MetricCard label="Active Insights" labelColor="var(--green-600)" value="4" sub="2 high priority"/>
        <MetricCard label="Potential Savings" labelColor="var(--green-600)" value="$3,699" sub="per year"/>
        <MetricCard label="Financial Score" value="78 / 100" delta={{dir:'pos',text:'5 pts'}}/>
        <MetricCard label="Goals On Track" value="4 of 6"/>
      </KpiRow>
      <div className="cm-grid-2">
        {insights.map((s,i)=>(
          <div className="cm-tile" key={i}>
            <div className="cm-tile-head" style={{marginBottom:10}}>
              <span className="cm-tile-ic" style={{background:tints(s.c),color:s.c}}>{s.ic}</span>
              <div style={{flex:1}}><span className={`cm-pill ${toneMap[s.tone]}`}>{s.tag}</span></div>
              <span className="num" style={{fontWeight:800,color:s.tone==='red'?G:G,fontSize:15}}>{s.impact}</span>
            </div>
            <div className="t-h2" style={{fontSize:16,marginBottom:6}}>{s.title}</div>
            <div className="t-body" style={{color:'var(--ink-500)',lineHeight:1.5}}>{s.body}</div>
            <div style={{display:'flex',gap:10,marginTop:16}}>
              <button className="cm-btn cm-btn-primary" style={{padding:'8px 14px'}}>Take action</button>
              <button className="cm-btn cm-btn-soft" style={{padding:'8px 14px'}}>Dismiss</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
window.PageAI = PageAI;

/* ============================ SETTINGS ============================ */
function Toggle({ on, onClick }) { return <div className={`cm-toggle ${on?'on':''}`} onClick={onClick}><div className="knob"/></div>; }
function PageSettings() {
  const CM = window.useStore ? window.useStore() : window.CM;
  const [tg, setTg] = React.useState({bills:true, goals:true, ai:false, weekly:true});
  const flip = k => setTg(s=>({...s,[k]:!s[k]}));
  const cu = (CM && CM.S && CM.S.currentUser) || {};
  const fam = (CM && CM.S && CM.S.family) || [];
  const members = fam.length ? fam.map(function(m,i){ return {n:m.name, r:m.role||'Member', c:[G,PU,BL,AM][i%4]}; }) : [];
  const [prof, setProf] = React.useState({ name:cu.name||'', email:cu.email||'', phone:cu.phone||'', currency:cu.currency||'CAD' });
  const [saved, setSaved] = React.useState(false);
  const setF = (k,v)=>{ setProf(p=>Object.assign({},p,{[k]:v})); setSaved(false); };
  const saveProfile = ()=>{
    CM.mutate(function(){
      CM.S.currentUser = Object.assign({}, CM.S.currentUser||{}, { name:(prof.name||'').trim(), email:(prof.email||'').trim().toLowerCase(), phone:(prof.phone||'').trim(), currency:prof.currency });
    });
    // persist identity to the base store so it survives reload / boot
    try { var b=JSON.parse(localStorage.getItem('clearmint_v4')||'{}'); b.currentUser=CM.S.currentUser; localStorage.setItem('clearmint_v4', JSON.stringify(b)); } catch(e){}
    setSaved(true); setTimeout(function(){ setSaved(false); }, 2600);
  };
  const fileRef = React.useRef(null);
  const onPhoto = (e)=>{ const f=e.target.files&&e.target.files[0]; if(!f) return; const rd=new FileReader(); rd.onload=function(){ CM.mutate(function(){ CM.S.currentUser=Object.assign({},CM.S.currentUser||{},{photo:rd.result}); }); try{var b=JSON.parse(localStorage.getItem('clearmint_v4')||'{}');b.currentUser=CM.S.currentUser;localStorage.setItem('clearmint_v4',JSON.stringify(b));}catch(_e){} }; rd.readAsDataURL(f); e.target.value=''; };
  const inviteMember = ()=>{ if(window.CMAccess && !CMAccess.requireWithinLimit('members',(CM.S.family||[]).length,'More family members')) return; const n=window.prompt('Name of the family member to invite'); if(!n) return; const role=window.prompt('Role (Admin / Partner / Teen / Child / Viewer)','Member')||'Member'; const email=window.prompt('Email (optional)','')||''; CM.mutate(function(){ (CM.S.family=CM.S.family||[]).push({name:n,role:role,email:email,_invited:true}); }); };
  const changePassword = ()=>{
    const p=window.prompt('Enter a new password (minimum 8 characters)'); if(p==null) return;
    if((p||'').length<8){ window.alert('Password must be at least 8 characters.'); return; }
    const url=(window.CM_SUPABASE_URL||'').replace(/\/$/,'');
    const anon=window.CM_SUPABASE_ANON_KEY||'';
    let token=''; try{ token=localStorage.getItem('cm_sb_token')||sessionStorage.getItem('cm_sb_token')||''; }catch(e){}
    if(!url || !anon || !token){ window.alert('Changing your password isn’t available right now — sign in to the live deployment to update it.'); return; }
    fetch(url+'/auth/v1/user', {
      method:'PUT',
      headers:{ 'Content-Type':'application/json', apikey:anon, Authorization:'Bearer '+token },
      body:JSON.stringify({ password:p })
    }).then(function(r){
      return r.json().catch(function(){ return {}; }).then(function(j){
        if(r.ok){ window.alert('Your password has been updated.'); }
        else { window.alert('Could not update your password: '+((j&&(j.msg||j.error_description||j.error||j.message))||('HTTP '+r.status))+'.'); }
      });
    }).catch(function(err){ window.alert('Could not update your password: '+((err&&err.message)||'network error')+'.'); });
  };
  // 2FA enrollment isn't wired to a backend yet — surface it as coming soon
  // rather than faking a local toggle.
  const toggle2FA = ()=>{ window.alert('Two-factor authentication is coming soon.'); };
  const signOutAll = ()=>{ if(window.confirm('Sign out of all devices? You\u2019ll need to sign in again.')) window.location.href='Login.html'; };
  const secActions = [
    ['Change password', <Is.Lock size={16}/>, changePassword],
    ['Two-factor authentication (coming soon)', <Is.Shield size={16}/>, toggle2FA],
    ['Connected accounts', <Is.Accounts size={16}/>, ()=>{ location.hash='#/connect'; }],
    ['Sign out of all devices', <Is.User size={16}/>, signOutAll],
  ];
  const inits = ((prof.name||'?').split(' ').map(function(w){return w[0];}).slice(0,2).join('')||'U').toUpperCase();
  /* ── email reports about historical expenses ── */
  const ep = (CM.S && CM.S.emailPrefs) || { monthly:true, weekly:false, billdue:true, subrenew:false };
  const flipE = k => CM.mutate(function(){ CM.S.emailPrefs = Object.assign({}, ep, {[k]:!ep[k]}); });
  // Notification alert types — wired to the email engine's prefs (window.CMEmail): the same store the
  // Email Center uses and that buildAlerts() reads, so toggling here actually controls real alerts.
  const ALERT_DEF = { billReminder:true, lowBalance:true, largeExpense:true, creditUtil:true, subscription:true, budget:true, netWorth:true, investment:false };
  const _E = window.CMEmail;
  const al = (_E && _E.state && _E.state().prefs && _E.state().prefs.alerts) || ALERT_DEF;
  const [, _bumpA] = React.useReducer(function(x){ return x + 1; }, 0);
  const flipA = k => { if(_E && _E.setPrefs){ _E.setPrefs(function(x){ if(!x.alerts) x.alerts = {}; x.alerts[k] = !x.alerts[k]; }); _bumpA(); } };
  const [emailPeriod, setEmailPeriod] = React.useState('30d');
  const [emailSent, setEmailSent] = React.useState(false);
  const [compact, setCompact] = React.useState(window.cmGetCompactTables ? window.cmGetCompactTables() : true);
  const flipCompact = ()=>{ const v=!compact; setCompact(v); try{ window.cmSetCompactTables && window.cmSetCompactTables(v); }catch(e){} };
  const IDLE_PRESETS=[0,1,5,15,30,60];
  const [idleMin, setIdleMin] = React.useState(window.cmGetIdleTimeout ? window.cmGetIdleTimeout() : 15);
  const [idleCustom, setIdleCustom] = React.useState(IDLE_PRESETS.indexOf(window.cmGetIdleTimeout ? window.cmGetIdleTimeout() : 15)<0);
  const applyIdle = (m)=>{ const v=Math.max(0,parseFloat(m)||0); setIdleMin(v); try{ window.cmSetIdleTimeout && window.cmSetIdleTimeout(v); }catch(_){} };
  const changeIdle = (e)=>{ const val=e.target.value; if(val==='custom'){ setIdleCustom(true); } else { setIdleCustom(false); applyIdle(parseFloat(val)); } };
  const sendExpenseEmail = ()=>{
    const inP = d => !window.cmInPeriod || window.cmInPeriod(d, emailPeriod);
    const TRANSFER = {'Transfer':1,'Credit Card Payment':1,'Savings':1};
    const spendTx = (CM.S.bankTx||[]).concat(CM.S.ccTx||[]).filter(r=>r.date && (+r.dr||0)>0 && !TRANSFER[r.cat] && inP(r.date));
    const total = spendTx.reduce((s,r)=>s+(+r.dr||0),0);
    const byCat = {}; spendTx.forEach(r=>{ const c=r.cat||'Other'; byCat[c]=(byCat[c]||0)+(+r.dr||0); });
    const cats = Object.keys(byCat).sort((a,b)=>byCat[b]-byCat[a]);
    const byMo = {}; spendTx.forEach(r=>{ const k=CM.getMonthKey?CM.getMonthKey(r.date):String(r.date).slice(0,7); if(k) byMo[k]=(byMo[k]||0)+(+r.dr||0); });
    const mos = Object.keys(byMo).sort();
    const fmt = CM.M;
    const label = window.cmPeriodLabel ? window.cmPeriodLabel(emailPeriod) : String(emailPeriod);
    const lines = [
      'Clear Mint — Historical Expense Report',
      'Period: '+label+' · Generated: '+new Date().toLocaleDateString('en-CA'),
      '',
      'Total spending: '+fmt(total)+' across '+spendTx.length+' transactions (transfers excluded)',
      '',
      'By month:',
      ...mos.map(k=>'  • '+k+': '+fmt(byMo[k])),
      '',
      'By category:',
      ...cats.map(c=>'  • '+c+': '+fmt(byCat[c])),
      '',
      'Sent from Clear Mint · clearmint.ca',
    ];
    const to = (CM.S.currentUser && CM.S.currentUser.email) || '';
    window.location.href = 'mailto:'+encodeURIComponent(to)
      +'?subject='+encodeURIComponent('Clear Mint — Expense Report ('+label+')')
      +'&body='+encodeURIComponent(lines.join('\n'));
    setEmailSent(true); setTimeout(()=>setEmailSent(false), 3200);
  };
  return (
    <div>
      <div className="cm-grid-2b">
        <div className="cm-stack">
          <ChartCard title="Profile">
            <div style={{display:'flex',alignItems:'center',gap:16,marginBottom:20}}>
              <div className="cm-avatar" style={{width:64,height:64,display:'flex',alignItems:'center',justifyContent:'center',color:G,fontWeight:800,fontSize:22,overflow:'hidden',backgroundSize:'cover',backgroundPosition:'center',backgroundImage:cu.photo?`url(${cu.photo})`:'none'}}>{cu.photo?'':inits}</div>
              <input ref={fileRef} type="file" accept="image/*" style={{display:'none'}} onChange={onPhoto}/>
              <button className="cm-btn cm-btn-soft" onClick={()=>fileRef.current&&fileRef.current.click()}>Change photo</button>
            </div>
            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
              <div className="cm-field"><label>Full name</label><input value={prof.name} onChange={e=>setF('name',e.target.value)} placeholder="Your name"/></div>
              <div className="cm-field"><label>Email</label><input value={prof.email} onChange={e=>setF('email',e.target.value)} placeholder="you@email.com"/></div>
              <div className="cm-field"><label>Phone</label><input value={prof.phone} onChange={e=>setF('phone',e.target.value)} placeholder="(000) 000-0000"/></div>
              <div className="cm-field"><label>Currency</label><select value={prof.currency} onChange={e=>setF('currency',e.target.value)}><option>CAD</option><option>USD</option><option>EUR</option><option>GBP</option></select></div>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:12,marginTop:8}}>
              <button className="cm-btn cm-btn-primary" onClick={saveProfile}>Save changes</button>
              {saved && <span className="t-caption" style={{color:'var(--green-600)',fontWeight:700}}>✓ Saved</span>}
            </div>
          </ChartCard>
          <ChartCard title="Notifications">
            <div className="t-caption" style={{marginBottom:4}}>Choose what Clear Mint alerts you about. Alerts are generated from your real data and delivered through the <a href="#/emails" style={{color:'var(--green-600)',fontWeight:700}}>Email Center</a>.</div>
            {[
              ['billReminder','Bill due reminders','7, 3 and 1 days before each bill or expense is due'],
              ['lowBalance','Low account balance','When an account drops below your safety threshold'],
              ['largeExpense','Large or unusual expense','When a single transaction exceeds your alert amount'],
              ['creditUtil','High credit-card utilization','When a card crosses 30 / 50 / 70% of its limit'],
              ['subscription','Subscription alerts','New subscriptions detected and upcoming renewals'],
              ['budget','Budget overspend','When a category passes its monthly budget'],
              ['netWorth','Net-worth milestones','Celebrate when you cross a net-worth milestone'],
              ['investment','Investment updates','Notable moves in your portfolio']
            ].map((r,i,arr)=>(
              <div key={i} style={{display:'flex',alignItems:'center',gap:12,padding:'12px 0',borderBottom:i<arr.length-1?'1px solid var(--line)':'0'}}>
                <div style={{flex:1}}><div className="t-h3">{r[1]}</div><div className="t-caption">{r[2]}</div></div>
                <Toggle on={!!al[r[0]]} onClick={()=>flipA(r[0])}/>
              </div>
            ))}
          </ChartCard>
          <ChartCard title="Display &amp; Session">
            <div style={{display:'flex',alignItems:'center',gap:12,padding:'12px 0',borderBottom:'1px solid var(--line)'}}>
              <div style={{flex:1}}><div className="t-h3">Compact tables</div><div className="t-caption">Smaller, denser rows in transactions, earnings &amp; bills. Turn off to restore larger text.</div></div>
              <Toggle on={compact} onClick={flipCompact}/>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:12,padding:'12px 0'}}>
              <div style={{flex:1}}><div className="t-h3">Auto sign-out</div><div className="t-caption">Sign out automatically after a period of inactivity{idleMin>0?(' — currently '+(idleMin>=60?(idleMin/60)+' hr':idleMin+' min')):''}.</div></div>
              <div style={{display:'flex',alignItems:'center',gap:8}}>
                {idleCustom && <input type="number" min="0" step="1" value={idleMin||''} onChange={e=>applyIdle(e.target.value)} placeholder="min" style={{width:64,fontFamily:'inherit',fontSize:13,fontWeight:600,color:'var(--ink-700)',border:'1px solid var(--line)',borderRadius:10,padding:'9px 10px',background:'#fff'}}/>}
                {idleCustom && <span className="t-caption">min</span>}
                <select className="cm-select" value={idleCustom?'custom':String(idleMin)} onChange={changeIdle} style={{fontFamily:'inherit',fontSize:13,fontWeight:600,color:'var(--ink-700)',border:'1px solid var(--line)',borderRadius:10,padding:'9px 12px',background:'#fff'}}>
                  <option value="0">Never</option><option value="1">1 minute</option><option value="5">5 minutes</option><option value="15">15 minutes</option><option value="30">30 minutes</option><option value="60">1 hour</option><option value="custom">Custom…</option>
                </select>
              </div>
            </div>
          </ChartCard>
          <ChartCard title="Email Reports">
            <div className="t-caption" style={{marginBottom:4}}>Automatic emails about your historical expenses, sent to <b>{prof.email||'your email'}</b>.</div>
            {[['monthly','Monthly expense summary','Total spending, by category and by month — every 1st'],['weekly','Weekly spending digest','Your week\u2019s expenses every Monday morning'],['billdue','Bill due reminders','3 days before each recurring bill or expense'],['subrenew','Subscription renewal alerts','Before any subscription renews or changes price']].map((r,i)=>(
              <div key={i} style={{display:'flex',alignItems:'center',gap:12,padding:'12px 0',borderBottom:'1px solid var(--line)'}}>
                <div style={{flex:1}}><div className="t-h3">{r[1]}</div><div className="t-caption">{r[2]}</div></div>
                <Toggle on={!!ep[r[0]]} onClick={()=>flipE(r[0])}/>
              </div>
            ))}
            <div style={{display:'flex',alignItems:'center',gap:10,paddingTop:14,flexWrap:'wrap'}}>
              <select className="cm-select" value={emailPeriod} onChange={e=>setEmailPeriod(e.target.value)} style={{fontFamily:'inherit',fontSize:13,fontWeight:600,color:'var(--ink-700)',border:'1px solid var(--line)',borderRadius:10,padding:'9px 12px',background:'#fff'}}>
                <option value="30d">Last 30 days</option><option value="60d">Last 60 days</option><option value="90d">Last 90 days</option><option value="year">This Year</option><option value="all">All Periods</option>
              </select>
              <button className="cm-btn cm-btn-primary" onClick={sendExpenseEmail}>Email expense report now</button>
              {emailSent && <span className="t-caption" style={{color:'var(--green-600)',fontWeight:700}}>✓ Report opened in your mail app</span>}
            </div>
            <div className="t-caption" style={{marginTop:10}}>In this preview the report opens in your mail app; production delivery uses your connected email service. <a href="#/emails" style={{color:'var(--green-600)',fontWeight:700}}>Open the Email Center →</a> for daily/weekly/monthly summaries, alerts and delivery settings.</div>
          </ChartCard>
        </div>
        <div className="cm-stack">
          <ChartCard title="Family Members" action={<button className="cm-btn cm-btn-ghost" onClick={inviteMember}><Is.Plus size={16}/>Invite</button>}>
            {members.map((m,i)=>(
              <div className="cm-act" key={i}>
                <div className="cm-act-ic" style={{background:tints(m.c),color:m.c}}>{m.n.split(' ').map(x=>x[0]).join('')}</div>
                <div className="cm-act-body"><div className="cm-act-title">{m.n}</div><div className="cm-act-sub">{m.r}</div></div>
                <Is.ChevR size={16} className="cm-chev"/>
              </div>
            ))}
          </ChartCard>
          <ChartCard title="Security">
            {secActions.map((r,i)=>(
              <div className="cm-act" key={i} style={{cursor:'pointer'}} onClick={r[2]}>
                <div className="cm-act-ic" style={{background:'var(--mint-50)',color:'var(--ink-500)'}}>{r[1]}</div>
                <div className="cm-act-body"><div className="cm-act-title">{r[0]}</div></div>
                <Is.ChevR size={16} className="cm-chev"/>
              </div>
            ))}
          </ChartCard>
        </div>
      </div>
      {window.DataEraseSection && <window.DataEraseSection/>}
    </div>
  );
}
window.PageSettings = PageSettings;
