/* Clear Mint — Admin Console "Platform Command Center"
   The administrative surface for the app. The signed-in family's row is REAL
   (name, plan, members and net worth come straight from the CM engine), and the
   managed-tenant roster is internally consistent: platform aggregates (AUM,
   active users, MRR, plan mix) are summed from the same roster the table shows.
   Ties the app together: "Exit to App" returns to the dashboard, "Log out"
   returns to Login. window.PageAdmin.
   Depends on cm-charts + cm-components + cm-app-kit + cm-data. */
(function () {
const { ChartCard, DonutChart, Legend } = window;

/* warm palette (matches the other command centers) */
const cG='#10915F', cGold='var(--gold)', cTeal='#0E9F8E', cBlue='#3E7CC4',
      cPlum='#8A6E9E', cPink='#D8688F', cSlate='#9AA7B2', cRed='var(--red-500)', cAmber='#B5740F';

const usd0 = n => '$' + Math.round(Number(n||0)).toLocaleString('en-CA');
const compact = n => { n=Number(n||0); return n>=1e6?('$'+(n/1e6).toFixed(2)+'M'):n>=1e3?('$'+Math.round(n/1e3)+'K'):'$'+Math.round(n); };
const clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v));

/* ---- icons ---- */
const si = (paths) => ({ size=18, ...p }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" {...p}>{paths}</svg>
);
const Si = {
  shield: si(<><path d="M12 3 5 6v5c0 4 3 7.5 7 9 4-1.5 7-5 7-9V6z"/><path d="m9 12 2 2 4-4"/></>),
  users : si(<><circle cx="9" cy="8" r="3.2"/><path d="M3.5 20c0-3.3 2.6-5 5.5-5s5.5 1.7 5.5 5"/><path d="M16 5.5a3 3 0 0 1 0 5.6M17.5 20c0-2.2-.8-3.7-2-4.6"/></>),
  user  : si(<><circle cx="12" cy="8" r="3.6"/><path d="M5 20c0-3.6 3-6 7-6s7 2.4 7 6"/></>),
  dollar: si(<><circle cx="12" cy="12" r="9"/><path d="M12 7v10M9.5 9a2 2 0 0 1 2-1.5h1A2 2 0 0 1 14 11l-3 2a2 2 0 0 0 2 3.5h1a2 2 0 0 0 2-1.5"/></>),
  pulse : si(<path d="M3 12h4l2-6 4 12 2-6h6"/>),
  layers: si(<><path d="M12 3 3 8l9 5 9-5z"/><path d="M3 13l9 5 9-5M3 17l9 5 9-5"/></>),
  server: si(<><rect x="3" y="4" width="18" height="7" rx="2"/><rect x="3" y="13" width="18" height="7" rx="2"/><path d="M7 7.5h.01M7 16.5h.01"/></>),
  search: si(<><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></>),
  chev  : si(<path d="m6 9 6 6 6-6"/>),
  chevR : si(<path d="m9 6 6 6-6 6"/>),
  eye   : si(<><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/></>),
  edit  : si(<><path d="M4 20h4l10.5-10.5a2 2 0 0 0-3-3L5 17z"/><path d="M13.5 6.5l3 3"/></>),
  kebab : si(<><circle cx="12" cy="5" r="1.3" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.3" fill="currentColor" stroke="none"/><circle cx="12" cy="19" r="1.3" fill="currentColor" stroke="none"/></>),
  download: si(<><path d="M12 4v12M8 12l4 4 4-4"/><path d="M5 20h14"/></>),
  filter: si(<path d="M3 5h18l-7 8v6l-4-2v-4z"/>),
  plus  : si(<path d="M12 5v14M5 12h14"/>),
  cal   : si(<><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></>),
  logout: si(<><path d="M15 4h3a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-3"/><path d="M10 17l-5-5 5-5M4 12h11"/></>),
  back  : si(<path d="M15 6l-6 6 6 6"/>),
  gauge : si(<><path d="M12 13l4-3"/><path d="M5 18a8 8 0 1 1 14 0"/><circle cx="12" cy="13" r="1" fill="currentColor" stroke="none"/></>),
  check : si(<path d="M20 6 9 17l-5-5"/>),
  alert : si(<><path d="M12 4 2.5 20h19z"/><path d="M12 10v4M12 17h.01"/></>),
  spark : si(<><path d="M12 3v3M12 18v3M3 12h3M18 12h3M6 6l2 2M16 16l2 2M18 6l-2 2M8 16l-2 2"/><circle cx="12" cy="12" r="2.4"/></>),
  lock  : si(<><rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></>),
  bolt  : si(<path d="M13 2 4 14h7l-2 8 9-12h-7z"/>),
  clock : si(<><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></>),
};

/* plan economics — single source of truth for pricing */
const PLAN = {
  free:        { label:'Free',    price:0,  color:cSlate },
  plus:        { label:'Plus',    price:12, color:cBlue  },
  family_plus: { label:'Family+', price:25, color:cG     },
  business:    { label:'Business',price:49, color:cPlum  },
};
const planOf = k => PLAN[k] || PLAN.free;

function ramp(a,b,n=8){ const o=[]; for(let i=0;i<n;i++){ const t=i/(n-1),e=t*t*(3-2*t); o.push(a+(b-a)*e);} return o; }

/* ============================ DERIVE ============================ */
function deriveAdmin(CM) {
  const cu = CM.S.currentUser || { name:'', email:'guest@clearmint.ca', plan:'trial' };
  const myName = cu.name || 'there';
  const myFamily = (CM.S.family && CM.S.family.length && /family/i.test(myName)) ? myName : (myName.split(' ').slice(-1)[0] + ' Family');
  const myNW = CM.netWorth();
  const myMembers = Math.max(1, (CM.S.family||[]).length);
  const myPlan = cu.plan || 'family_plus';

  // The signed-in tenant is REAL. Other managed tenants would come from the
  // backend; until that's wired the roster is just this family, and every
  // platform aggregate below is summed from THIS list (so it stays consistent).
  const roster = [
    { id:'u-self', family:myFamily, owner:myName, email:cu.email||'demo@clearmint.ca', plan:myPlan, members:myMembers, nw:myNW, status:'active', last:'Just now', joined:'Jan 2026', self:true },
  ];

  const totalFamilies = roster.length;
  const activeUsers   = roster.reduce((s,r)=>s+r.members,0);
  const aum           = roster.reduce((s,r)=>s+r.nw,0);
  const mrr           = roster.filter(r=>r.status!=='suspended').reduce((s,r)=>s+planOf(r.plan).price*1,0);
  const activeCount   = roster.filter(r=>r.status==='active').length;

  // plan distribution (counts)
  const planMap = {};
  roster.forEach(r=>{ const p=planOf(r.plan); (planMap[r.plan]=planMap[r.plan]||{label:p.label,color:p.color,count:0,key:r.plan}).count++; });
  const planDist = Object.values(planMap).sort((a,b)=>b.count-a.count);

  // signups trend (synthetic ramp toward current family count)
  const signups = ramp(Math.max(1,totalFamilies-5), totalFamilies, 8).map(v=>Math.round(v));

  // platform/system health (static, operational)
  const systems = [
    { name:'API & Engine',     ic:Si.server, status:'Operational', up:'99.98%', tone:'green' },
    { name:'Market Data Feed', ic:Si.bolt,   status:'Operational', up:'99.9%',  tone:'green' },
    { name:'Auth & Sessions',  ic:Si.lock,   status:'Operational', up:'100%',   tone:'green' },
    { name:'Quote / Pricing',  ic:Si.gauge,  status:'Degraded',    up:'97.4%',  tone:'amber' },
  ];

  // recent admin activity — driven by the real activity log; empty otherwise
  const realLog = (CM.S.activityLog||CM.S.auditLog||[]);
  const activity = realLog.slice(0,6).map(a=>({
    who:(a.user||a.who||'System'), what:(a.action||a.what||a.msg||'Activity'), when:(a.when||a.date||'')
  }));

  return { cu, myName, totalFamilies, activeUsers, aum, mrr, activeCount, roster, planDist, signups, systems, activity };
}

/* ============================ TOOLBAR ============================ */
function goApp(){ location.hash = '#/dashboard'; }
function logout(){
  try { if (window.CM && CM.S) CM.S.currentUser = CM.S.currentUser; } catch(e){}
  window.location.href = 'Login.html';
}

function Toolbar({ D }) {
  return (
    <div className="st-toolbar">
      <div className="left">
        <span className="cm-pill" style={{background:'var(--mint-100)', color:cG, fontWeight:800, gap:6, padding:'7px 12px'}}>
          <Si.shield size={14}/> Admin Console
        </span>
        <span className="st-control" style={{cursor:'default'}}><Si.server size={14}/> Production · ClearMint Cloud</span>
      </div>
      <div className="right">
        <span className="st-control"><Si.download size={15}/>Export</span>
        <span className="st-control" onClick={goApp}><Si.back size={15}/>Exit to App</span>
        <button className="cm-btn cm-btn-primary" onClick={logout}><Si.logout size={16}/>Log out</button>
      </div>
    </div>
  );
}

/* ============================ KPI STRIP ============================ */
function Tile({ icon, tint, color, label, value, foot, footColor }) {
  return (
    <div className="st-tile">
      <div className="st-tile-head">
        <span className="st-tile-ic" style={{background:tint, color}}>{icon}</span>
        <span className="st-tile-label">{label}</span>
      </div>
      <div className="st-tile-val num">{value}</div>
      <div className="st-tile-foot" style={footColor?{color:footColor}:null}>{foot}</div>
    </div>
  );
}
function KpiStrip({ D }) {
  return (
    <ChartCard pad={false}>
      <div style={{padding:'18px 22px 4px'}} className="cm-row">
        <span className="st-mini-title">Platform Overview</span>
        <span className="st-mini-sub" style={{marginTop:0, marginLeft:8}}>· {D.totalFamilies} families · {D.activeUsers} members</span>
      </div>
      <div className="st-summary">
        <Tile icon={<Si.users size={16}/>}  tint="var(--mint-100)" color={cG}    label="Total Families" value={String(D.totalFamilies)} foot={<span style={{color:cG}}>{D.activeCount} active</span>}/>
        <Tile icon={<Si.user size={16}/>}   tint="#E7EEFE"         color={cBlue}  label="Active Members" value={String(D.activeUsers)} foot="Across all tenants" footColor="var(--ink-400)"/>
        <Tile icon={<Si.dollar size={16}/>} tint="#FEF1DD"         color={cAmber} label="Assets Under Mgmt" value={compact(D.aum)} foot="Combined net worth" footColor="var(--ink-400)"/>
        <Tile icon={<Si.pulse size={16}/>}  tint="#EDE7F9"         color={cPlum}  label="Monthly Recurring" value={usd0(D.mrr)} foot="MRR · paid plans" footColor="var(--ink-400)"/>
        <Tile icon={<Si.layers size={16}/>} tint="#DCF3F0"         color={cTeal}  label="Plan Tiers" value={String(D.planDist.length)} foot="In use" footColor="var(--ink-400)"/>
        <Tile icon={<Si.server size={16}/>} tint="var(--mint-100)" color={cG}     label="System Status" value="Operational" foot="1 service degraded" footColor={cAmber}/>
      </div>
    </ChartCard>
  );
}

/* ============================ ANALYTICS ROW ============================ */
function MiniHead({ title, sub }) {
  return <div style={{marginBottom:16}}><div className="st-mini-title">{title}</div><div className="st-mini-sub">{sub}</div></div>;
}
function SignupTrend({ data }) {
  const W=360, H=150, P={l:8,r:14,t:18,b:24};
  const lo=Math.min(...data)-1, hi=Math.max(...data)+1;
  const X=i=>P.l+(i/(data.length-1))*(W-P.l-P.r);
  const Y=v=>P.t+(1-(v-lo)/(hi-lo))*(H-P.t-P.b);
  const line=data.map((v,i)=>`${i?'L':'M'}${X(i)},${Y(v)}`).join(' ');
  const area=`${line} L${X(data.length-1)},${H-P.b} L${X(0)},${H-P.b} Z`;
  const mns=['Oct','Nov','Dec','Jan','Feb','Mar','Apr','May'];
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{display:'block'}}>
      <defs><linearGradient id="admSignFill" x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={cG} stopOpacity=".18"/><stop offset="100%" stopColor={cG} stopOpacity="0"/>
      </linearGradient></defs>
      {[0,1,2].map(i=>{ const y=P.t+i*((H-P.t-P.b)/2); return <line key={i} x1={P.l} y1={y} x2={W-P.r} y2={y} stroke="var(--line)" strokeWidth="1"/>; })}
      <path d={area} fill="url(#admSignFill)"/>
      <path d={line} fill="none" stroke={cG} strokeWidth="2.6" strokeLinejoin="round"/>
      {data.map((v,i)=> i%2===0 && <text key={i} x={X(i)} y={H-5} textAnchor={i===0?'start':'middle'} fontSize="10.5" fontWeight="700" fill="var(--ink-400)">{mns[i]}</text>)}
      <circle cx={X(data.length-1)} cy={Y(data[data.length-1])} r="4.2" fill={cG} stroke="#fff" strokeWidth="2"/>
    </svg>
  );
}
function AnalyticsRow({ D }) {
  const toneClass = { green:'cm-pill-green', amber:'cm-pill-amber', red:'cm-pill-red' };
  return (
    <div className="st-analytics cm-mt-20" style={{gridTemplateColumns:'1.1fr 1fr 1.2fr'}}>
      <ChartCard>
        <MiniHead title="Plan Distribution" sub="Tenants by tier"/>
        <div style={{display:'flex', justifyContent:'center', marginBottom:14}}>
          <DonutChart size={150} thickness={21}
            segments={D.planDist.map(p=>({value:p.count, color:p.color}))}
            center={{value:String(D.totalFamilies), label:'Families'}}/>
        </div>
        <Legend items={D.planDist.map(p=>({ color:p.color, label:p.label, pct:`${Math.round(p.count/D.totalFamilies*100)}%`, value:`${p.count}` }))}/>
      </ChartCard>

      <ChartCard>
        <MiniHead title="Family Signups" sub="Last 8 months"/>
        <SignupTrend data={D.signups}/>
        <div style={{display:'flex', gap:20, marginTop:12, paddingTop:12, borderTop:'1px solid var(--line)'}}>
          <div><div className="t-caption">This month</div><div className="num" style={{fontWeight:800, color:cG, fontSize:17}}>+{D.signups[D.signups.length-1]-D.signups[D.signups.length-2]}</div></div>
          <div><div className="t-caption">Total families</div><div className="num" style={{fontWeight:800, color:'var(--ink-900)', fontSize:17}}>{D.totalFamilies}</div></div>
        </div>
      </ChartCard>

      <ChartCard>
        <MiniHead title="System Health" sub="Core services"/>
        <div>
          {D.systems.map((s,i)=>(
            <div className="cm-row" key={i} style={{gap:11, padding:'10px 0', borderBottom: i<D.systems.length-1?'1px solid var(--line)':'none'}}>
              <span style={{width:34, height:34, flex:'0 0 34px', borderRadius:10, background:'var(--mint-50)', color: s.tone==='amber'?cAmber:cG, display:'flex', alignItems:'center', justifyContent:'center'}}><s.ic size={17}/></span>
              <div style={{flex:1, minWidth:0}}>
                <div className="t-label" style={{color:'var(--ink-900)'}}>{s.name}</div>
                <div className="t-caption num">Uptime {s.up}</div>
              </div>
              <span className={`cm-pill ${toneClass[s.tone]}`}>{s.status}</span>
            </div>
          ))}
        </div>
      </ChartCard>
    </div>
  );
}

/* ============================ TENANT TABLE ============================ */
const STATUS = { active:{cls:'cm-pill-green',label:'Active'}, trial:{cls:'cm-pill-amber',label:'Trial'}, suspended:{cls:'cm-pill-red',label:'Suspended'} };
const initials = n => (n||'').split(' ').map(w=>w[0]).slice(0,2).join('').toUpperCase();
const AV_BG = [cG,cBlue,cPlum,cTeal,cAmber,cPink];

function TenantTable({ D }) {
  const [query, setQuery] = React.useState('');
  const [planF, setPlanF] = React.useState(0);
  const planOpts = ['All Plans', ...D.planDist.map(p=>p.label)];
  const pf = planOpts[planF % planOpts.length];
  const rows = D.roster.filter(r =>
    (r.family+r.owner+r.email).toLowerCase().includes(query.toLowerCase()) &&
    (pf==='All Plans' || planOf(r.plan).label===pf));
  const COLS = ['Family / Tenant','Owner','Plan','Members','Net Worth','Status','Last Active','Actions'];
  return (
    <ChartCard className="cm-mt-20">
      <div className="st-tablehead">
        <div>
          <div className="cm-row" style={{gap:8}}>
            <span className="st-mini-title">Family &amp; User Management</span>
            <span className="cm-pill cm-pill-slate" style={{fontWeight:700}}>{rows.length} of {D.roster.length}</span>
          </div>
          <div className="st-mini-sub">Every tenant on the platform — view, manage, suspend or impersonate</div>
        </div>
        <div className="filters">
          <div className="st-searchbox">
            <Si.search size={15}/>
            <input placeholder="Search family, owner or email…" value={query} onChange={e=>setQuery(e.target.value)}/>
          </div>
          <span className="st-control" onClick={()=>setPlanF(i=>i+1)}>{pf} <Si.chev size={14}/></span>
          <span className="st-control"><Si.filter size={15}/></span>
        </div>
      </div>

      <div style={{overflowX:'auto'}}>
        <table className="st-table" style={{minWidth:980}}>
          <thead><tr>{COLS.map((c,i)=><th key={i} className={c==='Actions'?'r':''}>{c}</th>)}</tr></thead>
          <tbody>
            {rows.map((r,ri)=>{
              const s = STATUS[r.status] || STATUS.active;
              const p = planOf(r.plan);
              return (
                <tr key={r.id} className="subrow">
                  <td>
                    <div className="cm-row" style={{gap:11}}>
                      <span className="st-net" style={{background:AV_BG[ri%AV_BG.length]}}>{initials(r.family.replace(/^The /,''))}</span>
                      <div>
                        <div className="st-cardname" style={{fontSize:14, display:'flex', alignItems:'center', gap:7}}>
                          {r.family}{r.self && <span className="cm-pill cm-pill-green" style={{fontSize:10}}>Your account</span>}
                        </div>
                        <div className="t-caption">Joined {r.joined}</div>
                      </div>
                    </div>
                  </td>
                  <td><div className="st-num">{r.owner}</div><div className="t-caption num">{r.email}</div></td>
                  <td><span className="cm-pill" style={{background:'var(--mint-50)', color:p.color, fontWeight:700}}>{p.label}{p.price?` · $${p.price}/mo`:''}</span></td>
                  <td><span className="st-num">{r.members}</span></td>
                  <td><span className="st-num">{usd0(r.nw)}</span></td>
                  <td><span className={`cm-pill ${s.cls}`}>{s.label}</span></td>
                  <td><span className="st-num mut">{r.last}</span></td>
                  <td style={{textAlign:'right'}}>
                    <div className="st-act" style={{justifyContent:'flex-end'}}>
                      <span className="st-actbtn" onClick={goApp} title="Open this tenant in the app"><Si.eye size={14}/>{r.self?'Open':'View as'}</span>
                      <span className="st-actbtn"><Si.edit size={14}/>Manage</span>
                      <span className="st-kebab"><Si.kebab size={16}/></span>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <div className="st-pager">
        <span className="t-caption">Showing <b style={{color:'var(--ink-700)'}}>{rows.length}</b> of <b style={{color:'var(--ink-700)'}}>{D.roster.length}</b> tenants</span>
        <button className="cm-add-row green" style={{width:'auto', padding:'10px 16px'}}><Si.plus size={16}/>Invite Family</button>
      </div>
    </ChartCard>
  );
}

/* ============================ ACTIVITY + QUICK ACTIONS ============================ */
function BottomRow({ D }) {
  const acts = [
    { ic:Si.users,  t:'Manage Roles & Access', s:'Permissions and ownership', c:cG },
    { ic:Si.dollar, t:'Billing & Plans',        s:'Subscriptions and invoices', c:cAmber },
    { ic:Si.lock,   t:'Security & Audit',       s:'Sessions, 2FA, audit log',  c:cPlum },
    { ic:Si.server, t:'System Settings',        s:'Engine, feeds and limits',  c:cBlue },
  ];
  return (
    <div className="cm-grid-2 cm-mt-20">
      <ChartCard>
        <MiniHead title="Recent Admin Activity" sub="Latest platform events"/>
        <div>
          {D.activity.map((a,i)=>(
            <div className="cm-row" key={i} style={{gap:11, padding:'11px 0', borderBottom: i<D.activity.length-1?'1px solid var(--line)':'none'}}>
              <span style={{width:34, height:34, flex:'0 0 34px', borderRadius:'50%', background:'var(--mint-50)', color:a.tone||cSlate, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:800, fontSize:13}}>{initials(a.who)}</span>
              <div style={{flex:1, minWidth:0}}>
                <div className="t-label" style={{color:'var(--ink-900)'}}>{a.what}</div>
                <div className="t-caption">{a.who}</div>
              </div>
              <span className="t-caption num" style={{whiteSpace:'nowrap'}}>{a.when}</span>
            </div>
          ))}
        </div>
      </ChartCard>
      <ChartCard>
        <MiniHead title="Admin Tools" sub="Common controls"/>
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
          {acts.map((a,i)=>(
            <div key={i} className="cm-tile" style={{display:'flex', alignItems:'center', gap:12, padding:'16px 16px', cursor:'pointer'}}>
              <span style={{width:40, height:40, flex:'0 0 40px', borderRadius:11, background:'var(--mint-50)', color:a.c, display:'flex', alignItems:'center', justifyContent:'center'}}><a.ic size={19}/></span>
              <div><div className="t-label" style={{color:'var(--ink-900)'}}>{a.t}</div><div className="t-caption">{a.s}</div></div>
            </div>
          ))}
        </div>
        <div className="st-banner" style={{margin:'16px 0 0', background:'var(--mint-50)', borderColor:'var(--line)'}}>
          <span className="ic" style={{color:cG}}><Si.shield size={17}/></span>
          <span className="tx" style={{color:'var(--ink-700)'}}>You're signed in as <b>{D.myName}</b> with full administrator access. <a onClick={goApp} style={{cursor:'pointer'}}>Return to the app</a> or <a onClick={logout} style={{cursor:'pointer'}}>log out</a>.</span>
        </div>
      </ChartCard>
    </div>
  );
}

/* ============================ PAGE ============================ */
function PageAdmin() {
  const CM = window.useStore ? window.useStore() : window.CM;
  const D = deriveAdmin(CM);
  return (
    <div>
      <Toolbar D={D}/>
      <KpiStrip D={D}/>
      <AnalyticsRow D={D}/>
      <TenantTable D={D}/>
      <BottomRow D={D}/>
    </div>
  );
}
window.PageAdmin = PageAdmin;
})();
