/* Clear Mint — Email Center page (Financial Email Intelligence System UI).
   Preferences, live previews from real data, simulated scheduler/delivery log,
   and provider administration. Depends on cm-email-engine.js + app kit. */
(function(){
const { ChartCard, MetricCard, KpiRow, Tabs, StatusPill, DataTable } = window;
const I = window.CMIcon;
const G='#10915F', GOLD='var(--gold,#D4AF37)', RD='var(--red-500)';

function Tgl({ on, onClick }){ return <div className={`cm-toggle ${on?'on':''}`} onClick={onClick}><div className="knob"></div></div>; }
function Sec({ title, sub, children }){
  return <ChartCard className="cm-mb-24"><div style={{marginBottom:14}}><div className="t-h2" style={{fontSize:17}}>{title}</div>{sub && <div className="t-caption" style={{marginTop:3}}>{sub}</div>}</div>{children}</ChartCard>;
}
function Row({ title, sub, right, last }){
  return (
    <div style={{display:'flex',alignItems:'center',gap:14,padding:'12px 0',borderBottom:last?'none':'1px solid var(--line)'}}>
      <div style={{flex:1,minWidth:0}}><div className="t-h3">{title}</div>{sub && <div className="t-caption">{sub}</div>}</div>
      <div style={{flexShrink:0,display:'flex',alignItems:'center',gap:10}}>{right}</div>
    </div>
  );
}
const inputCss = { fontFamily:'inherit', fontSize:13, fontWeight:600, color:'var(--ink-700)', border:'1px solid var(--line)', borderRadius:10, padding:'8px 11px', background:'#fff', outline:'none' };

const TYPES = [
  { id:'daily',   name:'Daily Financial Summary', img:'hero-daily.png',          desc:'Today\u2019s transactions by account, totals, week & month so far, AI insights.' },
  { id:'weekly',  name:'Weekly Financial Review', img:'family-tablet.png',       desc:'Weekly overview, category breakdown and the AI weekly review.' },
  { id:'monthly', name:'Month-End Financial Report', img:'hero-celebration.png', desc:'Executive summary, health score, spending analysis, wealth building & forecast.' },
  { id:'alerts',  name:'Financial Alerts',        img:'budget-alert.png',        desc:'Budget, large expense, low balance, utilization, bills, subscriptions & milestones.' },
];
const ALERT_CARDS = [
  { img:'budget-alert.png',        name:'Budget & Utilization',   desc:'80/90/100% of budget \u00b7 30/50/75/90% card utilization' },
  { img:'wallet-alert.png',        name:'Large Expense & Low Balance', desc:'User-defined thresholds' },
  { img:'subscription-review.png', name:'Subscription Alerts',    desc:'New, price increases & duplicates' },
  { img:'bill-calendar.png',       name:'Bill Reminders',         desc:'7 / 3 / 1 days before due' },
  { img:'coins-sprout.png',        name:'Net Worth Milestones',   desc:'$50k \u00b7 $100k \u00b7 $250k \u00b7 $500k \u00b7 $1M' },
  { img:'investment-growth.png',   name:'Investment Alerts',      desc:'Portfolio moves & contributions' },
];

function PageEmailCenter(){
  const CM = window.useStore ? window.useStore() : window.CM;
  const E = window.CMEmail;
  const [tab, setTab] = React.useState('Overview');
  const [, force] = React.useState(0);
  const rerender = () => force(n=>n+1);
  if(!E) return <div className="t-body">Email engine not loaded.</div>;
  const st = E.state(), p = st.prefs, stats = E.stats(), logs = st.logs||[];
  const next = E.nextRuns();
  const setP = (fn) => { E.setPrefs(fn); rerender(); };
  const fdT = (d)=> new Date(d).toLocaleString('en-CA',{month:'short',day:'numeric',hour:'numeric',minute:'2-digit'});

  const Overview = (
    <div>
      <KpiRow>
        <MetricCard label="Emails Sent" value={String(stats.sent)} sub={stats.bounces+' bounce'+(stats.bounces===1?'':'s')}/>
        <MetricCard label="Delivery Rate" labelColor="var(--green-600)" value={stats.deliveryRate+'%'} sub={'via '+p.provider.name}/>
        <MetricCard label="Open Rate" value={stats.openRate+'%'} sub="last 300 sends"/>
        <MetricCard label="Click Rate" value={stats.clickRate+'%'} sub={stats.unsubscribes+' unsubscribes'}/>
      </KpiRow>
      <div className="cm-grid-2a cm-mb-24">
        <ChartCard>
          <div style={{display:'flex',gap:20,alignItems:'center',flexWrap:'wrap'}}>
            <img src="assets/email/robot-wave.png" alt="" style={{width:120,height:'auto',flex:'0 0 auto'}}/>
            <div style={{flex:1,minWidth:240}}>
              <div className="t-h2" style={{fontSize:19}}>Your money, in your inbox</div>
              <p className="t-body" style={{color:'var(--ink-500)',margin:'8px 0 14px',lineHeight:1.55}}>
                Mint builds every email from your real ledger — transactions, recurring schedule, budgets and net worth. Nothing is invented; if there’s no data, the section is skipped.</p>
              <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
                {TYPES.slice(0,3).map(t=>(
                  <button key={t.id} className="cm-btn cm-btn-soft" onClick={()=>E.openPreview(t.id)}><I.Reports size={15}/>Preview {t.id}</button>
                ))}
              </div>
            </div>
          </div>
        </ChartCard>
        <ChartCard title="Next Scheduled Sends">
          {next.length ? next.map((n,i)=>(
            <Row key={i} title={E.TITLES[n[0]]||n[0]} sub={'to '+((CM.S.currentUser&&CM.S.currentUser.email)||'you')} last={i===next.length-1}
              right={<span className="cm-pill cm-pill-green" style={{fontWeight:700}}>{fdT(n[1])}</span>}/>
          )) : <div className="t-caption" style={{padding:'20px 0',textAlign:'center'}}>All summary emails are turned off.</div>}
          <div className="t-caption" style={{marginTop:10}}>Timezone: {p.delivery.timezone}</div>
        </ChartCard>
      </div>
      <Sec title="Recent Emails" sub="Simulated delivery — in production these are sent through your configured provider.">
        {logs.length ? <DataTable minWidth={720} columns={[
          { header:'Email', cell:r=><div><div className="cm-cell-primary" style={{maxWidth:320,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{r.subject}</div><div className="cm-cell-sub">{E.TITLES[r.type]||r.type} · {r.to}</div></div> },
          { header:'Sent', cell:r=><span className="num" style={{fontSize:12.5,color:'var(--ink-500)',whiteSpace:'nowrap'}}>{fdT(r.when)}</span> },
          { header:'Provider', cell:r=><span style={{fontSize:12.5,fontWeight:700,color:'var(--ink-700)'}}>{r.provider}</span> },
          { header:'Status', cell:r=><StatusPill tone={r.status==='Bounced'?'red':'green'}>{r.status}</StatusPill> },
          { header:'Engagement', cell:r=><span className="t-caption">{r.opened?'Opened':'—'}{r.clicked?' · Clicked':''}</span> },
        ]} rows={logs.slice(0,8)}/> : <div className="t-caption" style={{textAlign:'center',padding:'24px 0'}}>No emails sent yet — they’ll appear here as the scheduler runs.</div>}
      </Sec>
    </div>
  );

  const Preferences = (
    <div className="cm-grid-2b">
      <div className="cm-stack">
        <Sec title="Summary Emails" sub="Automatic digests built from your live data.">
          <Row title="Daily Summary" sub="How your money moved today" right={<>
            <input type="time" value={p.delivery.dailyTime} style={inputCss} onChange={e=>setP(x=>{x.delivery.dailyTime=e.target.value;})}/>
            <Tgl on={p.summaries.daily} onClick={()=>setP(x=>{x.summaries.daily=!x.summaries.daily;})}/></>}/>
          <Row title="Weekly Summary" sub="Your weekly financial review" right={<>
            <select value={p.delivery.weeklyDay} style={inputCss} onChange={e=>setP(x=>{x.delivery.weeklyDay=e.target.value;})}>
              {['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'].map(d=><option key={d}>{d}</option>)}
            </select>
            <input type="time" value={p.delivery.weeklyTime} style={inputCss} onChange={e=>setP(x=>{x.delivery.weeklyTime=e.target.value;})}/>
            <Tgl on={p.summaries.weekly} onClick={()=>setP(x=>{x.summaries.weekly=!x.summaries.weekly;})}/></>}/>
          <Row title="Monthly Report" sub="Last day of the month" last right={<>
            <input type="time" value={p.delivery.monthlyTime} style={inputCss} onChange={e=>setP(x=>{x.delivery.monthlyTime=e.target.value;})}/>
            <Tgl on={p.summaries.monthly} onClick={()=>setP(x=>{x.summaries.monthly=!x.summaries.monthly;})}/></>}/>
        </Sec>
        <Sec title="Alerts" sub="Event-driven — sent when a trigger occurs.">
          {[['budget','Budget alerts','80% · 90% · 100% of category budget'],
            ['largeExpense','Large expense alerts',null],
            ['lowBalance','Low balance alerts',null],
            ['creditUtil','Credit utilization alerts','30% · 50% · 75% · 90%'],
            ['subscription','Subscription alerts','New, price increases, duplicates'],
            ['billReminder','Bill reminders','7 / 3 / 1 days before due'],
            ['netWorth','Net worth milestones','$50k → $1M+'],
            ['investment','Investment alerts','Portfolio moves'],
          ].map((r,i,arr)=>(
            <Row key={r[0]} title={r[1]}
              sub={r[0]==='largeExpense'?('Over $'+(p.thresholds.largeExpense||500)):r[0]==='lowBalance'?('Below $'+(p.thresholds.lowBalance||200)):r[2]}
              last={i===arr.length-1}
              right={<>
                {r[0]==='largeExpense' && <input type="number" value={p.thresholds.largeExpense} style={{...inputCss,width:84}} onChange={e=>setP(x=>{x.thresholds.largeExpense=+e.target.value||0;})}/>}
                {r[0]==='lowBalance' && <input type="number" value={p.thresholds.lowBalance} style={{...inputCss,width:84}} onChange={e=>setP(x=>{x.thresholds.lowBalance=+e.target.value||0;})}/>}
                <Tgl on={!!p.alerts[r[0]]} onClick={()=>setP(x=>{x.alerts[r[0]]=!x.alerts[r[0]];})}/></>}/>
          ))}
        </Sec>
      </div>
      <div className="cm-stack">
        <Sec title="Delivery">
          <Row title="Timezone" right={
            <select value={p.delivery.timezone} style={inputCss} onChange={e=>setP(x=>{x.delivery.timezone=e.target.value;})}>
              {['America/Toronto','America/Vancouver','America/Edmonton','America/Winnipeg','America/Halifax','America/St_Johns'].concat(p.delivery.timezone&&['America/Toronto','America/Vancouver','America/Edmonton','America/Winnipeg','America/Halifax','America/St_Johns'].indexOf(p.delivery.timezone)<0?[p.delivery.timezone]:[]).map(z=><option key={z}>{z}</option>)}
            </select>}/>
          <Row title="Email format" sub="How much detail each email includes" last right={
            <div className="cm-seg">{['Compact','Detailed','Executive Summary'].map(f=>(
              <button key={f} className={p.delivery.format===f?'active':''} onClick={()=>setP(x=>{x.delivery.format=f;})}>{f.split(' ')[0]}</button>
            ))}</div>}/>
        </Sec>
        <Sec title="Content" sub="Choose what each email may include.">
          {[['transactions','Transactions'],['balances','Balances'],['ai','AI insights'],['forecasts','Forecasts'],['investments','Investment section'],['family','Family section']].map((r,i,arr)=>(
            <Row key={r[0]} title={r[1]} last={i===arr.length-1} right={<Tgl on={!!p.content[r[0]]} onClick={()=>setP(x=>{x.content[r[0]]=!x.content[r[0]];})}/>}/>
          ))}
        </Sec>
        <Sec title="Compliance">
          <div className="t-caption" style={{lineHeight:1.7}}>
            Every email includes one-click unsubscribe and a preference link, honours CASL and Canadian privacy law, and is GDPR-ready. Your address is verified before the first send.</div>
        </Sec>
      </div>
    </div>
  );

  const Templates = (
    <div>
      <Sec title="Summary Templates" sub="Rendered live from your data — open a preview or log a test send.">
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(250px,1fr))',gap:16}}>
          {TYPES.map(t=>(
            <div key={t.id} className="cm-card" style={{padding:16,display:'flex',flexDirection:'column',gap:10}}>
              <div style={{height:120,display:'flex',alignItems:'center',justifyContent:'center',background:'linear-gradient(180deg,#F2F7F3,#fff)',borderRadius:12,overflow:'hidden'}}>
                <img src={'assets/email/'+t.img} alt="" style={{maxWidth:'88%',maxHeight:110,objectFit:'contain'}}/>
              </div>
              <div><div className="t-h3" style={{fontSize:14.5}}>{t.name}</div><div className="t-caption" style={{marginTop:3,lineHeight:1.45}}>{t.desc}</div></div>
              <div style={{display:'flex',gap:8,marginTop:'auto'}}>
                <button className="cm-btn cm-btn-soft" style={{flex:1,justifyContent:'center',padding:'8px'}} onClick={()=>E.openPreview(t.id)}>Preview</button>
                <button className="cm-btn cm-btn-primary" style={{flex:1,justifyContent:'center',padding:'8px'}} onClick={()=>{E.sendTest(t.id); rerender();}}>Send test</button>
              </div>
            </div>
          ))}
        </div>
      </Sec>
      <Sec title="Alert Illustrations" sub="Event-driven alerts use these brand assets.">
        <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fill,minmax(210px,1fr))',gap:16}}>
          {ALERT_CARDS.map((a,i)=>(
            <div key={i} className="cm-card" style={{padding:14,textAlign:'center'}}>
              <img src={'assets/email/'+a.img} alt="" style={{maxWidth:'70%',maxHeight:96,objectFit:'contain'}}/>
              <div className="t-h3" style={{fontSize:13.5,marginTop:8}}>{a.name}</div>
              <div className="t-caption" style={{marginTop:2}}>{a.desc}</div>
            </div>
          ))}
        </div>
      </Sec>
    </div>
  );

  const Admin = (
    <div>
      <div className="cm-grid-2a cm-mb-24">
        <ChartCard title="Email Service Provider">
          <div className="t-caption" style={{marginBottom:12}}>Provider abstraction — switch without code changes. Keys are stored per environment.</div>
          {['Resend','Postmark','SendGrid','Amazon SES'].map((pr,i)=>(
            <Row key={pr} title={pr} sub={i===0?'Primary':'Standby'} last={i===3} right={<>
              {p.provider.name===pr && <StatusPill tone="green">{p.provider.status||'Connected'}</StatusPill>}
              <input type="radio" name="esp" checked={p.provider.name===pr} onChange={()=>setP(x=>{x.provider.name=pr;})}/>
            </>}/>
          ))}
          <div style={{display:'flex',gap:8,marginTop:14}}>
            <input placeholder="API key" type="password" value={p.provider.apiKey} style={{...inputCss,flex:1}} onChange={e=>setP(x=>{x.provider.apiKey=e.target.value;})}/>
            <button className="cm-btn cm-btn-soft" onClick={()=>{setP(x=>{x.provider.status='Connected';}); }}>Verify</button>
          </div>
        </ChartCard>
        <ChartCard title="System">
          <Row title="Email system" sub="Master switch for every send" right={<Tgl on={p.enabled} onClick={()=>setP(x=>{x.enabled=!x.enabled;})}/>}/>
          {TYPES.map((t,i)=>(
            <Row key={t.id} title={t.name} last={i===TYPES.length-1} right={
              t.id==='alerts'
                ? <span className="t-caption">per-alert toggles in Preferences</span>
                : <Tgl on={!!p.summaries[t.id]} onClick={()=>setP(x=>{x.summaries[t.id]=!x.summaries[t.id];})}/>}/>
          ))}
          <div style={{display:'flex',gap:8,marginTop:14,flexWrap:'wrap'}}>
            <button className="cm-btn cm-btn-primary" onClick={()=>{E.sendTest('daily'); rerender();}}>Send test email</button>
            <button className="cm-btn cm-btn-soft" onClick={()=>{const n=E.runScheduler(); rerender(); }}>Run scheduler now</button>
          </div>
        </ChartCard>
      </div>
      <Sec title="Deliverability Log" sub={'Sent '+stats.sent+' · delivered '+stats.deliveryRate+'% · opened '+stats.openRate+'% · clicked '+stats.clickRate+'% · '+stats.bounces+' bounces · '+stats.unsubscribes+' unsubscribes'}>
        {logs.length ? <DataTable minWidth={760} columns={[
          { header:'When', cell:r=><span className="num" style={{fontSize:12.5,color:'var(--ink-500)',whiteSpace:'nowrap'}}>{fdT(r.when)}</span> },
          { header:'Type', cell:r=><span className="cm-pill cm-pill-slate" style={{fontWeight:700,fontSize:11}}>{E.TITLES[r.type]||r.type}</span> },
          { header:'Subject', cell:r=><span style={{fontSize:13,fontWeight:600,color:'var(--ink-900)'}}>{r.subject}</span> },
          { header:'To', cell:r=><span className="t-caption">{r.to}</span> },
          { header:'Status', cell:r=><StatusPill tone={r.status==='Bounced'?'red':'green'}>{r.status}</StatusPill> },
          { header:'Opens / Clicks', cell:r=><span className="t-caption">{(r.opened?'1':'0')+' / '+(r.clicked?'1':'0')}</span> },
        ]} rows={logs.slice(0,25)}/> : <div className="t-caption" style={{textAlign:'center',padding:'24px 0'}}>No log entries yet.</div>}
      </Sec>
    </div>
  );

  return (
    <div>
      <Tabs tabs={['Overview','Preferences','Templates','Admin']} value={tab} onChange={setTab}/>
      <div style={{height:20}}></div>
      {tab==='Overview' && Overview}
      {tab==='Preferences' && Preferences}
      {tab==='Templates' && Templates}
      {tab==='Admin' && Admin}
    </div>
  );
}
window.PageEmailCenter = PageEmailCenter;
})();
