/* Clear Mint — Family Wealth Hub (flagship, themed). window.PageFamilyHub
   7-tab family-office experience matching the FWH mockups. Reuses the themed
   FH kit (window.FHCard / FHLine / FHBars / FHRadar / FHDonut / FHSpark …) and
   the CMFamily data engine. Light by default with a dark toggle. */
(function(){
  const I = window.CMIcon;
  const useC = () => React.useContext(window.FHTheme);
  const hexA = window.FHhexA || ((h,a)=>h);
  const money = n => '$' + Math.round(+n||0).toLocaleString();
  const compact = n => { n=+n||0; const a=Math.abs(n); return (n<0?'-':'')+(a>=1e6?'$'+(a/1e6).toFixed(2).replace(/\.?0+$/,'')+'M':a>=1e3?'$'+Math.round(a/1e3)+'K':'$'+Math.round(a)); };

  function Avatar({ name, color, size=38 }){
    const ini = (name||'?').split(' ').map(w=>w[0]).slice(0,2).join('').toUpperCase();
    return <span style={{width:size,height:size,flex:`0 0 ${size}px`,borderRadius:999,background:color||'#16A34A',color:'#fff',fontWeight:800,fontSize:size*0.36,display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{ini}</span>;
  }

  function Kpi({ k }){
    const C = useC(); const { FHCard, FHChip, FHSpark, FHBar } = window;
    const up = k.up, good = (k.good!=null?k.good:up);
    const col = good ? C.emerald : C.red;
    return (
      <FHCard pad={16}>
        <div style={{display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:10}}>
          <div style={{minWidth:0}}>
            <div style={{fontSize:12,color:C.sub,fontWeight:700,display:'flex',alignItems:'center',gap:5}}>{k.label}<I.Info size={12} style={{color:C.mut}}/></div>
            <div style={{fontFamily:'var(--font-serif)',fontSize:26,fontWeight:700,color:k.color||C.ink,marginTop:8,lineHeight:1}}>{k.value}{k.sub&&<span style={{fontSize:14,color:C.mut,fontWeight:600}}>{k.sub}</span>}</div>
            {k.change!=null && <div style={{display:'flex',alignItems:'center',gap:4,marginTop:7,fontSize:12,fontWeight:800,color:col}}>{up?<I.ArrowUp size={12}/>:<I.ArrowDown size={12}/>}{k.abs||(Math.abs(k.change)+'%')}</div>}
            {k.foot && <div style={{fontSize:11.5,color:C.sub,marginTop:7,fontWeight:600}}>{k.foot}</div>}
            {k.sub && k.change==null && !k.foot && <div style={{fontSize:11.5,color:C.sub,marginTop:7}}>{k.sub}</div>}
          </div>
          {k.icon && <FHChip name={k.icon} color={k.color||C.emerald} size={42} radius={12}/>}
        </div>
        {k.bar!=null && <div style={{marginTop:10}}><FHBar pct={k.bar} color={C.emerald} height={7}/></div>}
        {k.series && <div style={{marginTop:8,height:30}}><FHSpark data={k.series} color={col} h={30}/></div>}
      </FHCard>
    );
  }

  /* ============================ OVERVIEW ============================ */
  function FwhOverview({ D }){
    const C = useC(); const { FHCard, FHLine, FHBar, FHChip, FHSelect } = window;
    const o = D.overview;
    const [tf,setTf] = React.useState('1Y');
    return (
      <div style={{display:'flex',flexDirection:'column',gap:18}}>
        <div style={{display:'grid',gridTemplateColumns:'repeat(6,1fr)',gap:14}} className="fh-kpi6">
          {o.kpis.map((k,i)=><Kpi key={i} k={k}/>)}
        </div>
        {/* wealth tree + net worth trend */}
        <div style={{display:'grid',gridTemplateColumns:'1fr 1.15fr',gap:16}} className="fh-2col">
          <FHCard title="Family Wealth Tree" info>
            <div style={{display:'flex',flexDirection:'column',alignItems:'center',gap:14}}>
              <div style={{display:'flex',gap:26}}>
                {o.tree.parents.map((p,i)=>(
                  <div key={i} style={{display:'flex',flexDirection:'column',alignItems:'center',gap:6}}>
                    <Avatar name={p.name} color={p.color} size={48}/>
                    <div style={{fontSize:12,fontWeight:700,color:C.ink}}>{p.name.split(' ')[0]}</div>
                    <div style={{fontSize:11,color:C.sub}}>{compact(p.netWorth)}</div>
                  </div>
                ))}
              </div>
              <div style={{width:1,height:18,background:C.line2}}/>
              <div style={{display:'flex',gap:18}}>
                {o.tree.children.map((p,i)=>(
                  <div key={i} style={{display:'flex',flexDirection:'column',alignItems:'center',gap:6}}>
                    <Avatar name={p.name} color={p.color} size={38}/>
                    <div style={{fontSize:11.5,fontWeight:700,color:C.ink}}>{p.name.split(' ')[0]}</div>
                  </div>
                ))}
              </div>
              <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:9,width:'100%',marginTop:6}}>
                {o.tree.nodes.map((n,i)=>(
                  <div key={i} style={{display:'flex',alignItems:'center',gap:9,padding:'10px 11px',border:'1px solid '+C.line,borderRadius:12,background:C.panel2}}>
                    <FHChip name={n.icon} color={n.color} size={30} radius={9}/>
                    <div style={{minWidth:0}}><div style={{fontSize:11,color:C.sub,fontWeight:600,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis'}}>{n.label}</div><div style={{fontSize:13,fontWeight:800,color:C.ink}}>{n.value}</div></div>
                  </div>
                ))}
              </div>
            </div>
          </FHCard>
          <FHCard title="Family Net Worth Trend" info right={<FHSelect options={['1M','3M','6M','1Y','5Y','All']} value={tf} onChange={setTf}/>}>
            <div style={{display:'flex',gap:16,marginBottom:8,fontSize:12}}>
              <span style={{color:C.sub}}>Net Worth <b style={{color:C.emerald}}>{compact(o.kpis[0].raw)}</b></span>
              <span style={{color:C.sub}}>Assets <b style={{color:C.ink}}>{compact(o.kpis[1].raw)}</b></span>
              <span style={{color:C.sub}}>Liabilities <b style={{color:C.red}}>{compact(o.kpis[2].raw)}</b></span>
            </div>
            <FHLine height={250} money x={o.nwTrend.x} series={[
              { name:'Assets', data:o.nwTrend.assets, color:C.blue, fill:false },
              { name:'Net Worth', data:o.nwTrend.netWorth, color:C.emerald, dots:true },
              { name:'Liabilities', data:o.nwTrend.liabilities, color:C.red, fill:false }
            ]}/>
          </FHCard>
        </div>
        {/* goals + AI insights */}
        <div style={{display:'grid',gridTemplateColumns:'1.3fr 1fr',gap:16}} className="fh-2col">
          <FHCard title="Family Goals" info right={<span style={{fontSize:12,color:C.emerald,fontWeight:700,cursor:'pointer'}} onClick={()=>location.hash='#/goals'}>View all</span>}>
            <div style={{display:'flex',flexDirection:'column',gap:14,marginTop:2}}>
              {o.goals.map((g,i)=>(
                <div key={i} style={{display:'flex',alignItems:'center',gap:13}}>
                  <FHChip name={g.icon} color={g.color} size={36} radius={10}/>
                  <div style={{flex:1,minWidth:0}}>
                    <div style={{display:'flex',justifyContent:'space-between',gap:10,marginBottom:5}}>
                      <span style={{fontSize:13,fontWeight:700,color:C.ink}}>{g.name}</span>
                      <span className="num" style={{fontSize:12.5,color:C.sub,fontWeight:600}}>{compact(g.saved)} / {compact(g.target)}</span>
                    </div>
                    <div style={{display:'flex',alignItems:'center',gap:10}}>
                      <FHBar pct={g.pct} color={g.color} height={7}/>
                      <span style={{fontSize:11.5,fontWeight:800,color:g.color,width:34,textAlign:'right'}}>{g.pct}%</span>
                    </div>
                  </div>
                  <span style={{fontSize:11,color:C.sub,fontWeight:600,width:38,textAlign:'right'}}>{g.eta}</span>
                </div>
              ))}
            </div>
          </FHCard>
          <FHCard title="AI Family Insights" info right={<span style={{fontSize:11,color:C.gold,fontWeight:700,display:'inline-flex',alignItems:'center',gap:4}}><I.Spark size={13}/>Generated</span>}>
            <div style={{display:'flex',flexDirection:'column',gap:4}}>
              {o.insights.map((ins,i)=>{ const cc = ins.type==='good'?C.emerald:ins.type==='warn'?C.amber:C.blue; return (
                <div key={i} style={{display:'flex',gap:12,padding:'12px 0',borderBottom:i<o.insights.length-1?'1px solid '+C.line:'none'}}>
                  <span style={{width:30,height:30,flex:'0 0 30px',borderRadius:9,background:hexA(cc,0.14),color:cc,display:'flex',alignItems:'center',justifyContent:'center'}}>{ins.type==='warn'?<I.Info size={16}/>:<I.Check size={16}/>}</span>
                  <div style={{fontSize:12.5,color:C.ink,lineHeight:1.5,paddingTop:4}}>{ins.text}</div>
                </div>
              ); })}
            </div>
          </FHCard>
        </div>
      </div>
    );
  }

  /* ============================ MEMBERS ============================ */
  function FreedomRing({ score, band, color }){
    const C = useC();
    const r=20, circ=2*Math.PI*r, off=circ*(1-score/100);
    return (
      <div style={{display:'flex',flexDirection:'column',alignItems:'center'}}>
        <div style={{position:'relative',width:50,height:50}}>
          <svg width={50} height={50} viewBox="0 0 50 50">
            <circle cx="25" cy="25" r={r} fill="none" stroke={C.track} strokeWidth="5"/>
            <circle cx="25" cy="25" r={r} fill="none" stroke={color} strokeWidth="5" strokeLinecap="round" strokeDasharray={circ} strokeDashoffset={off} transform="rotate(-90 25 25)"/>
          </svg>
          <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center',fontWeight:800,fontSize:14,color:C.ink}}>{score}</div>
        </div>
        <div style={{fontSize:10.5,color:color,fontWeight:700,marginTop:2}}>{band}</div>
      </div>
    );
  }
  function FwhMembers({ D }){
    const C = useC(); const { FHCard } = window;
    const m = D.membersPage, members = D.members;
    const scoreCol = s => s>=85?C.emerald:s>=70?C.teal:s>=55?C.amber:C.red;
    return (
      <div style={{display:'flex',flexDirection:'column',gap:18}}>
        <div style={{display:'grid',gridTemplateColumns:'repeat(5,1fr)',gap:14}} className="fh-kpi6">
          {m.kpis.map((k,i)=><Kpi key={i} k={k}/>)}
        </div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 320px',gap:16,alignItems:'start'}} className="fh-2col">
          <FHCard title="Family Members" right={<button style={fwhBtn(C,true)}><I.Plus size={15}/>Add Member</button>}>
            <div style={{fontSize:12.5,color:C.sub,marginTop:-6,marginBottom:14}}>Manage your family members and their financial roles.</div>
            <div style={{overflowX:'auto'}}>
              <table style={{width:'100%',borderCollapse:'collapse',minWidth:640}}>
                <thead><tr>{['Member','Role','Access Level','Joined','Net Worth','Financial Freedom Score',''].map((h,i)=><th key={i} style={{textAlign:i>3&&i<6?'center':'left',fontSize:11,fontWeight:800,letterSpacing:'.04em',textTransform:'uppercase',color:C.mut,padding:'0 10px 12px'}}>{h}</th>)}</tr></thead>
                <tbody>
                  {members.map((p,i)=>(
                    <tr key={i} style={{borderTop:'1px solid '+C.line}}>
                      <td style={{padding:'14px 10px'}}>
                        <div style={{display:'flex',alignItems:'center',gap:11}}>
                          <Avatar name={p.name} color={p.color} size={40}/>
                          <div style={{minWidth:0}}>
                            <div style={{fontSize:13.5,fontWeight:700,color:C.ink,display:'flex',alignItems:'center',gap:7}}>{p.name}{p.you&&<span style={{fontSize:10,fontWeight:800,color:C.emerald,background:hexA(C.emerald,0.14),borderRadius:999,padding:'1px 7px'}}>You</span>}</div>
                            <div style={{fontSize:11.5,color:C.sub}}>{p.email}</div>
                          </div>
                        </div>
                      </td>
                      <td style={{padding:'14px 10px'}}><div style={{fontSize:13,fontWeight:600,color:C.ink}}>{p.role}</div><div style={{fontSize:11.5,color:C.sub}}>{p.sub}</div></td>
                      <td style={{padding:'14px 10px'}}><span style={{fontSize:12.5,fontWeight:700,color:p.access==='Full Access'?C.emerald:C.blue}}>{p.access}</span></td>
                      <td style={{padding:'14px 10px',fontSize:12.5,color:C.sub}}>{p.joined}</td>
                      <td style={{padding:'14px 10px'}}><div className="num" style={{fontSize:13.5,fontWeight:800,color:C.ink}}>{money(p.netWorth)}</div><div style={{fontSize:11,color:C.sub}}>{p.share}%</div></td>
                      <td style={{padding:'10px',textAlign:'center'}}><div style={{display:'flex',justifyContent:'center'}}><FreedomRing score={p.score} band={p.band} color={scoreCol(p.score)}/></div></td>
                      <td style={{padding:'14px 10px',textAlign:'right'}}><I.Dots size={16} style={{color:C.mut,cursor:'pointer'}}/></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <div style={{display:'flex',alignItems:'center',gap:10,marginTop:14,padding:'12px 14px',background:C.panel2,border:'1px solid '+C.line,borderRadius:12}}>
              <I.Lock size={15} style={{color:C.sub}}/><span style={{fontSize:12.5,color:C.sub}}>Members with <b style={{color:C.ink}}>View Only</b> access can see financial information but cannot make changes.</span>
            </div>
          </FHCard>
          <div style={{display:'flex',flexDirection:'column',gap:16}}>
            <FHCard title="Access Overview">
              <div style={{display:'flex',alignItems:'center',gap:16}}>
                {window.FHDonut && <window.FHDonut value={50} size={92} label="4" sub="Members" color={C.emerald}/>}
                <div style={{flex:1,display:'flex',flexDirection:'column',gap:9}}>
                  {[['Full Access',m.access.full,C.emerald],['View Only',m.access.view,C.blue],['No Access',m.access.none,C.amber]].map((r,i)=>(
                    <div key={i} style={{display:'flex',alignItems:'center',gap:8,fontSize:12.5}}>
                      <span style={{width:9,height:9,borderRadius:3,background:r[2]}}/>
                      <span style={{flex:1,color:C.sub}}>{r[0]}</span>
                      <span style={{fontWeight:800,color:C.ink}}>{r[1]} ({Math.round(r[1]/4*100)}%)</span>
                    </div>
                  ))}
                </div>
              </div>
            </FHCard>
            <FHCard title="Member Activity" right={<span style={{fontSize:12,color:C.emerald,fontWeight:700,cursor:'pointer'}}>View all</span>}>
              {m.activity.map((a,i)=>(
                <div key={i} style={{display:'flex',gap:11,padding:'10px 0',borderBottom:i<m.activity.length-1?'1px solid '+C.line:'none'}}>
                  <Avatar name={a.who} color={a.color} size={30}/>
                  <div><div style={{fontSize:12.5,color:C.ink,fontWeight:600,lineHeight:1.4}}>{a.text}</div><div style={{fontSize:11,color:C.sub,marginTop:1}}>{a.when}</div></div>
                </div>
              ))}
            </FHCard>
            <FHCard title="Invite Family Member">
              <div style={{fontSize:12.5,color:C.sub,marginBottom:12}}>Invite a family member to join and manage your finances together.</div>
              <button style={{...fwhBtn(C,false),width:'100%',justifyContent:'center'}}><I.User size={15}/>Invite Member</button>
            </FHCard>
          </div>
        </div>
      </div>
    );
  }

  function fwhBtn(C, primary){ return {display:'inline-flex',alignItems:'center',gap:7,fontFamily:'inherit',fontSize:13,fontWeight:700,padding:'9px 15px',borderRadius:11,cursor:'pointer',whiteSpace:'nowrap',border:'1px solid '+(primary?C.emDeep:C.line2),background:primary?C.emDeep:C.panel,color:primary?'#fff':C.ink}; }

  function ComingSoon({ name }){
    const C = useC(); const { FHCard } = window;
    return <FHCard><div style={{padding:'60px 20px',textAlign:'center'}}><div style={{fontFamily:'var(--font-serif)',fontSize:20,fontWeight:700,color:C.ink}}>{name}</div><div style={{fontSize:13,color:C.sub,marginTop:8}}>This tab is being built next — Overview and Members are ready to explore.</div></div></FHCard>;
  }

  /* ============================ SHELL ============================ */
  const TABS = ['Overview','Members','Assets & Liabilities','Children','Shared Expenses','Documents','Permissions'];
  const SUBTITLES = {
    'Overview':"A complete view of your family's finances, today and for generations to come.",
    'Members':"A complete view of your family's finances, today and for the future.",
    'Assets & Liabilities':"A complete view of your family's finances, today and for the future.",
    'Children':"Plan, grow and secure your children's financial future.",
    'Shared Expenses':"A complete view of your family's finances, today and for the future.",
    'Documents':"A complete view of your family's finances, today and for the future.",
    'Permissions':"A complete view of your family's finances, today and for the future."
  };

  function PageFamilyHub(){
    const CM = window.useStore ? window.useStore() : window.CM;
    const D = React.useMemo(()=> window.CMFamily.derive(CM), [CM, CM&&CM.S&&CM.S.accounts]);
    const [tab,setTab] = React.useState('Overview');
    const [theme,setTheme] = React.useState(()=>{ try{ return localStorage.getItem('cm_fwh_theme')||'light'; }catch(e){ return 'light'; } });
    React.useEffect(()=>{ try{ localStorage.setItem('cm_fwh_theme',theme); }catch(e){} },[theme]);
    const PAL = window.FH_PALETTES; const C = theme==='dark'?PAL.dark:PAL.light;
    const FHThemeCtx = window.FHTheme;
    const Page = {
      'Overview':()=> <FwhOverview D={D}/>, 'Members':()=> <FwhMembers D={D}/>,
      'Assets & Liabilities':()=> (window.FwhAssets?<window.FwhAssets D={D}/>:<ComingSoon name="Assets & Liabilities"/>),
      'Children':()=> (window.FwhChildren?<window.FwhChildren D={D}/>:<ComingSoon name="Children"/>),
      'Shared Expenses':()=> (window.FwhExpenses?<window.FwhExpenses D={D}/>:<ComingSoon name="Shared Expenses"/>),
      'Documents':()=> (window.FwhDocuments?<window.FwhDocuments D={D}/>:<ComingSoon name="Documents"/>),
      'Permissions':()=> (window.FwhPermissions?<window.FwhPermissions D={D}/>:<ComingSoon name="Permissions"/>)
    }[tab];
    return (
      <FHThemeCtx.Provider value={C}>
        <div style={{background:C.bg,margin:'-24px -32px',minHeight:'100vh',padding:'0 32px 64px',transition:'background .25s',color:C.ink}} className="fh-shell">
          {/* hero header */}
          <div style={{position:'relative',margin:'0 -32px',padding:'26px 32px 0',overflow:'hidden'}}>
            <img src="assets/illustrations/mountain-peak.png" alt="" aria-hidden="true" style={{position:'absolute',top:6,right:24,width:340,height:'auto',opacity:theme==='dark'?0.32:0.62,pointerEvents:'none',maskImage:'linear-gradient(to right, transparent, #000 40%)',WebkitMaskImage:'linear-gradient(to right, transparent, #000 40%)'}} className="fwh-hero-mtn"/>
            <div style={{position:'relative',display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:20,flexWrap:'wrap'}}>
              <div style={{display:'flex',alignItems:'center',gap:15,minWidth:0}}>
                <span style={{width:54,height:54,borderRadius:16,background:C.emerald,color:'#fff',display:'flex',alignItems:'center',justifyContent:'center',flexShrink:0,boxShadow:'0 8px 20px -8px '+hexA(C.emerald,0.6)}}><I.House size={27}/></span>
                <div style={{minWidth:0}}>
                  <h1 style={{fontFamily:'var(--font-serif)',fontSize:30,fontWeight:700,color:C.ink,margin:0,lineHeight:1.1}}>Family Wealth Hub</h1>
                  <p style={{margin:'5px 0 0',fontSize:13.5,color:C.sub,fontWeight:500}}>{SUBTITLES[tab]}</p>
                </div>
              </div>
              <div style={{display:'flex',alignItems:'center',gap:10,flexShrink:0}}>
                {window.FHThemeToggle && <window.FHThemeToggle value={theme} onChange={setTheme}/>}
                <button style={fwhBtn(C,false)}><I.User size={15}/>Invite Family Member</button>
                <button style={{...fwhBtn(C,false),padding:'9px 11px',position:'relative'}}><I.Bell size={16}/><span style={{position:'absolute',top:-4,right:-4,width:16,height:16,borderRadius:999,background:C.gold,color:'#3A2E12',fontSize:10,fontWeight:800,display:'flex',alignItems:'center',justifyContent:'center'}}>2</span></button>
              </div>
            </div>
            {/* tabs */}
            <div style={{display:'flex',gap:26,borderBottom:'1px solid '+C.line,marginTop:18,overflowX:'auto'}}>
              {TABS.map(t=>{ const on=t===tab; return (
                <button key={t} onClick={()=>setTab(t)} style={{appearance:'none',border:0,background:'none',fontFamily:'inherit',cursor:'pointer',padding:'0 1px 13px',fontSize:14,fontWeight:on?700:600,color:on?C.emerald:C.sub,whiteSpace:'nowrap',borderBottom:'2px solid '+(on?C.emerald:'transparent'),marginBottom:-1}}>{t}</button>); })}
            </div>
          </div>
          <div style={{marginTop:22}}>{Page()}</div>
        </div>
      </FHThemeCtx.Provider>
    );
  }
  window.PageFamilyHub = PageFamilyHub;
  window.FwhKpi = Kpi; window.FwhAvatar = Avatar; window.fwhMoney = money; window.fwhCompact = compact; window.fwhBtnStyle = fwhBtn;
})();
