// Home / Dashboard screen

function HomeScreen({ theme, accent, onNav, onAskHimma, onOpenPaywall }) {
  const [hideBalance, setHideBalance] = React.useState(false);
  const [nwPeriod, setNwPeriod] = React.useState('year'); // 'week' | 'month' | 'year'
  const [allocationView, setAllocationView] = React.useState('assets'); // 'assets' | 'liabilities'
  const total = NET_WORTH;
  const unread = (typeof NOTIFICATIONS !== 'undefined') ? NOTIFICATIONS.filter(n => n.unread).length : 0;
  const period = NW_PERIODS[nwPeriod];

  const allocationData = allocationView === 'assets' ? ASSET_BREAKDOWN : LIABILITY_BREAKDOWN;
  const allocationTotal = allocationView === 'assets' ? ASSETS_TOTAL : LIABILITIES_TOTAL;

  return (
    <Screen theme={theme} padTop={0}>
      {/* Greeting */}
      <div style={{ padding: '10px 22px 10px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <button onClick={() => onNav('settings')} style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background:'transparent', border:'none', padding: 0, cursor:'pointer',
          color: theme.text, textAlign: 'left',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 18,
            background: `linear-gradient(135deg, ${accent}, ${accent}90)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: FONTS.display, fontSize: 16, color: '#fff', fontWeight: 500,
            flexShrink: 0,
          }}>L</div>
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div style={{ fontSize: 9, fontFamily: FONTS.mono, letterSpacing: 1.3, color: theme.textMute, textTransform: 'uppercase', whiteSpace: 'nowrap', lineHeight: 1.2 }}>Good morning</div>
            <div style={{ fontFamily: FONTS.display, fontSize: 17, color: theme.text, lineHeight: 1.1, marginTop: 2 }}>{USER.firstName}</div>
          </div>
        </button>
        <div style={{ display: 'flex', gap: 10 }}>
          <IconBtn icon="eye" theme={theme} onClick={()=>setHideBalance(v=>!v)} active={hideBalance}/>
          <IconBtn icon="bell" theme={theme} onClick={() => onNav('notifications')} badge={unread}/>
        </div>
      </div>

      {/* Net worth hero card */}
      <div style={{ padding: '6px 16px 0' }}>
        <Card theme={theme} padded={false} style={{
          padding: 22,
          background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 90%)`,
          position: 'relative', overflow: 'hidden',
        }}>
          {/* subtle decorative corner */}
          <svg width="180" height="180" style={{ position: 'absolute', top: -40, right: -50, opacity: 0.08 }}>
            <circle cx="90" cy="90" r="88" fill="none" stroke={accent} strokeWidth="0.5"/>
            <circle cx="90" cy="90" r="68" fill="none" stroke={accent} strokeWidth="0.5"/>
            <circle cx="90" cy="90" r="48" fill="none" stroke={accent} strokeWidth="0.5"/>
          </svg>

          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
            <SectionLabel theme={theme}>Total Net Worth</SectionLabel>
            <PeriodToggle value={nwPeriod} onChange={setNwPeriod} theme={theme} accent={accent}/>
          </div>

          <div style={{ marginTop: 8 }}>
            {hideBalance
              ? <div style={{ fontFamily: FONTS.display, fontSize: 44, color: theme.text, letterSpacing: -1, display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <Dh size={26} color={accent}/> ••• •••
                </div>
              : <BigNumber value={total} theme={theme} accent={accent} size={42}/>
            }
          </div>

          {/* Assets / liabilities sub-legend */}
          <button onClick={() => onNav('assets')} style={{
            background: 'transparent', border: 'none', padding: 0, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 10, marginTop: 6,
            fontFamily: FONTS.mono, fontSize: 10.5, letterSpacing: 0.2,
          }}>
            <span style={{ color: theme.textDim }}>
              <span style={{ color: theme.positive }}>+</span> {hideBalance ? '•••' : fmtAED(ASSETS_TOTAL, {compact:true})} <span style={{ color: theme.textMute }}>assets</span>
            </span>
            <span style={{ color: theme.textMute }}>·</span>
            <span style={{ color: theme.textDim }}>
              <span style={{ color: theme.negative }}>−</span> {hideBalance ? '•••' : fmtAED(LIABILITIES_TOTAL, {compact:true})} <span style={{ color: theme.textMute }}>debts</span>
            </span>
          </button>

          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10 }}>
            <Delta value={period.delta} pct={period.pct} theme={theme} size={13}/>
            <span style={{ fontSize: 12, color: theme.textDim }}>+{fmtAED(period.delta)} {period.caption}</span>
          </div>

          {/* Mini trend */}
          <div style={{ marginTop: 18 }}>
            <Spark data={period.trend} width={260} height={38} color={accent} responsive/>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: FONTS.mono, fontSize: 9, color: theme.textMute, marginTop: 4, letterSpacing: 0.5 }}>
              <span>{period.axis[0]}</span><span>{period.axis[1]}</span>
            </div>
          </div>
        </Card>
      </div>

      {/* AI insight strip */}
      <div style={{ padding: '14px 16px 0' }}>
        <button onClick={onAskHimma} style={{
          width: '100%', textAlign: 'left',
          background: 'transparent',
          border: `0.5px solid ${theme.line2}`,
          borderRadius: 16,
          padding: '14px 16px',
          display: 'flex', gap: 12, alignItems: 'flex-start', cursor: 'pointer',
          color: theme.text,
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 14, flexShrink: 0,
            background: `${accent}18`,
            display:'flex', alignItems:'center', justifyContent:'center',
            color: accent,
          }}><Ico.sparkles size={14}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1.4, textTransform: 'uppercase', color: accent, marginBottom: 3 }}>Himma · Morning note</div>
            <div style={{ fontSize: 13.5, lineHeight: 1.45, color: theme.text, fontFamily: FONTS.ui }}>
              Portfolio up <b>4.2%</b> this month — Saxo world-index drove <b><Dh/> 18.4K</b> of gains. Your idle cash is also creeping up.
            </div>
          </div>
          <Ico.chevR size={15} style={{ color: theme.textMute, marginTop: 3 }}/>
        </button>
      </div>

      {/* Peer comparison hook */}
      <div style={{ padding: '14px 16px 0' }}>
        <PeerCompareHook theme={theme} accent={accent} hideValue={hideBalance}
          onOpen={() => SUBSCRIPTION.status === 'active' ? onNav('compare') : onOpenPaywall && onOpenPaywall()}/>
      </div>

      {/* Allocation breakdown — toggle between assets and liabilities */}
      <div style={{ padding: '22px 16px 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding: '0 4px 10px' }}>
          <SectionLabel theme={theme}>Allocation</SectionLabel>
          <button onClick={() => onNav('assets')} style={{ background:'transparent', border:'none', fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, cursor:'pointer', display:'flex', alignItems:'center', gap: 3 }}>
            Details <Ico.chevR size={12}/>
          </button>
        </div>
        <Card theme={theme} padded={false} style={{ padding: 20 }}>
          <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
            {[
              { key: 'assets',      label: 'Assets' },
              { key: 'liabilities', label: 'Liabilities' },
            ].map(opt => {
              const active = allocationView === opt.key;
              return (
                <button key={opt.key} onClick={() => setAllocationView(opt.key)} style={{
                  flex: 1,
                  background: active ? `${accent}18` : 'transparent',
                  color: active ? accent : theme.textMute,
                  border: `0.5px solid ${active ? accent + '55' : theme.line2}`,
                  borderRadius: 999,
                  padding: '6px 10px',
                  fontFamily: FONTS.ui, fontSize: 12,
                  fontWeight: active ? 600 : 500,
                  cursor: 'pointer',
                }}>{opt.label}</button>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
            <Donut segments={allocationData} size={120} stroke={13} theme={theme}/>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 9 }}>
              {allocationData.map(s => {
                const pct = (s.value / allocationTotal * 100);
                return (
                  <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 12 }}>
                    <div style={{ width: 8, height: 8, borderRadius: 2, background: s.color, flexShrink: 0 }}/>
                    <div style={{ flex: 1, color: theme.textDim, fontFamily: FONTS.ui }}>{s.label}</div>
                    <div style={{ fontFamily: FONTS.mono, color: theme.text, fontVariantNumeric: 'tabular-nums' }}>{pct.toFixed(0)}%</div>
                  </div>
                );
              })}
            </div>
          </div>
        </Card>
      </div>

      {/* Cash flow hook → Activity tab */}
      <div style={{ padding: '22px 16px 0' }}>
        <CashFlowHook theme={theme} accent={accent} hideValue={hideBalance} onOpen={() => onNav('tx')}/>
      </div>

      {/* Learn — personalized financial literacy hook tiles */}
      <div style={{ padding: '26px 0 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding: '0 20px 10px' }}>
          <SectionLabel theme={theme}>Learn</SectionLabel>
          <button onClick={() => onNav('learn')} style={{ background:'transparent', border:'none', fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, cursor:'pointer', display:'flex', alignItems:'center', gap: 3 }}>
            See all <Ico.chevR size={12}/>
          </button>
        </div>
        <div style={{
          display: 'flex', gap: 10,
          padding: '2px 16px 4px',
          overflowX: 'auto',
          scrollSnapType: 'x mandatory',
        }}>
          {getRelevantLearnArticles(5).map(a => (
            <LearnTile key={a.id} article={a} theme={theme} accent={accent}
                       onClick={() => onNav('learn_article', { articleId: a.id })}/>
          ))}
        </div>
      </div>

      {/* Recent activity */}
      <div style={{ padding: '22px 16px 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding: '0 4px 10px' }}>
          <SectionLabel theme={theme}>Recent Activity</SectionLabel>
          <button onClick={() => onNav('tx')} style={{ background:'transparent', border:'none', fontFamily: FONTS.ui, fontSize: 12, color: theme.textDim, cursor:'pointer', display:'flex', alignItems:'center', gap: 3 }}>
            See all <Ico.chevR size={12}/>
          </button>
        </div>
        <Card theme={theme} padded={false}>
          {RECENT_ACTIVITY.map((a, i) => (
            <div key={a.id} style={{
              display:'flex', alignItems:'center', gap: 12,
              padding: '12px 16px',
              borderBottom: i < RECENT_ACTIVITY.length - 1 ? `0.5px solid ${theme.line}` : 'none',
            }}>
              <CategoryIcon category={a.icon} theme={theme} accent={accent} size={32}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, color: theme.text, fontWeight: 500, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{a.title}</div>
              </div>
              <div style={{
                fontFamily: FONTS.mono,
                fontSize: 13,
                fontVariantNumeric: 'tabular-nums',
                color: a.amount >= 0 ? theme.positive : theme.text,
                fontWeight: 500,
              }}>{a.amount >= 0 ? '+' : '−'}{fmtAED(Math.abs(a.amount), {decimals: Math.abs(a.amount) < 1000 ? 2 : 0})}</div>
            </div>
          ))}
        </Card>
      </div>

      {/* Footer wordmark */}
      <div style={{ textAlign: 'center', padding: '30px 0 10px', opacity: 0.35 }}>
        <Wordmark color={theme.text} accent={accent} size={14}/>
      </div>
    </Screen>
  );
}

function IconBtn({ icon, theme, onClick, active, badge }) {
  const Icon = Ico[icon];
  return (
    <button onClick={onClick} style={{
      width: 34, height: 34, borderRadius: 17,
      background: active ? theme.surface2 : 'transparent',
      border: `0.5px solid ${theme.line2}`,
      color: theme.text, cursor: 'pointer',
      display:'flex', alignItems:'center', justifyContent:'center',
      position: 'relative',
    }}>
      <Icon size={15}/>
      {badge > 0 && (
        <span style={{
          position: 'absolute', top: -2, right: -2,
          minWidth: 16, height: 16, padding: '0 4px',
          borderRadius: 8, background: theme.negative, color: '#fff',
          fontFamily: FONTS.mono, fontSize: 9.5, fontWeight: 600,
          display:'flex', alignItems:'center', justifyContent:'center',
          border: `1.5px solid ${theme.bg}`,
          letterSpacing: 0,
        }}>{badge}</span>
      )}
    </button>
  );
}

function LearnTile({ article, theme, accent, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: '0 0 auto',
      width: 158,
      scrollSnapAlign: 'start',
      background: theme.surface,
      border: `0.5px solid ${theme.line}`,
      borderRadius: 16,
      padding: 14,
      display: 'flex', flexDirection: 'column', gap: 10,
      textAlign: 'left',
      cursor: 'pointer',
      color: theme.text,
    }}>
      <Tag theme={theme} color={theme.textDim}>{article.category}</Tag>
      <div style={{
        fontFamily: FONTS.display, fontSize: 14.5, lineHeight: 1.25,
        color: theme.text, letterSpacing: -0.2,
        minHeight: 54,
      }}>{article.title}</div>
      <div style={{
        fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute,
        letterSpacing: 0.5, marginTop: 'auto',
      }}>{article.readMinutes} min read</div>
    </button>
  );
}

// Compact 3-segment toggle for the net-worth period (W / M / Y).
function PeriodToggle({ value, onChange, theme, accent }) {
  const opts = [
    { key: 'week',  label: 'W' },
    { key: 'month', label: 'M' },
    { key: 'year',  label: 'Y' },
  ];
  return (
    <div style={{
      display: 'inline-flex',
      border: `0.5px solid ${theme.line2}`,
      borderRadius: 999,
      padding: 2,
      background: theme.surface,
    }}>
      {opts.map(o => {
        const active = value === o.key;
        return (
          <button key={o.key} onClick={() => onChange(o.key)} style={{
            background: active ? `${accent}18` : 'transparent',
            color: active ? accent : theme.textMute,
            border: 'none', cursor: 'pointer',
            fontFamily: FONTS.mono, fontSize: 10, letterSpacing: 1,
            fontWeight: active ? 600 : 500,
            padding: '3px 9px',
            borderRadius: 999,
            transition: 'all 120ms',
          }}>{o.label}</button>
        );
      })}
    </div>
  );
}

// Home hook tile → links to the Activity tab.
function CashFlowHook({ theme, accent, hideValue, onOpen }) {
  const inTotal  = CASH_FLOW.in.reduce((s, x) => s + x.value, 0);
  const outOnly  = CASH_FLOW.out.filter(o => o.key !== 'saved').reduce((s, x) => s + x.value, 0);
  const saved    = CASH_FLOW.out.find(o => o.key === 'saved')?.value || 0;
  const netPct   = (saved / inTotal) * 100;

  const H = 6;
  const outPct = (outOnly / inTotal) * 100;

  return (
    <button onClick={onOpen} style={{
      width: '100%', textAlign: 'left',
      background: theme.surface,
      border: `0.5px solid ${theme.line2}`,
      borderRadius: 20,
      padding: '16px 18px',
      cursor: 'pointer',
      color: theme.text,
      display: 'block',
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap: 10 }}>
        <SectionLabel theme={theme}>Cash flow</SectionLabel>
        <div style={{
          display:'flex', alignItems:'center', gap: 4,
          fontFamily: FONTS.mono, fontSize: 9.5, letterSpacing: 1,
          color: theme.textDim, textTransform: 'uppercase', whiteSpace: 'nowrap',
        }}>
          Last month <Ico.chevR size={11}/>
        </div>
      </div>

      <div style={{
        marginTop: 10,
        fontFamily: FONTS.display, fontSize: 20, lineHeight: 1.2, letterSpacing: -0.4,
      }}>
        {hideValue ? (
          <>You saved <span style={{ color: theme.textMute }}>•••</span> of income last month</>
        ) : (
          <>You saved <span style={{ color: accent }}>{netPct.toFixed(0)}%</span> of income last month</>
        )}
      </div>

      <div style={{ display:'flex', alignItems:'center', gap: 10, marginTop: 14 }}>
        <div style={{ display:'flex', flexDirection:'column', gap: 2, flexShrink: 0 }}>
          <span style={{ fontFamily: FONTS.mono, fontSize: 9, letterSpacing: 1, textTransform:'uppercase', color: theme.textMute }}>In</span>
          <span style={{ fontFamily: FONTS.mono, fontSize: 12, color: theme.positive, fontVariantNumeric:'tabular-nums' }}>
            {hideValue ? '•••' : `+${fmtAED(inTotal, { compact: true })}`}
          </span>
        </div>
        <div style={{ flex: 1, position: 'relative', height: H, borderRadius: H/2, background: theme.surface3, overflow: 'hidden' }}>
          <div style={{ position:'absolute', left: 0, top: 0, bottom: 0, width: `${outPct}%`, background: theme.textDim, opacity: 0.55 }}/>
          <div style={{ position:'absolute', left: `${outPct}%`, top: 0, bottom: 0, right: 0, background: accent }}/>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap: 2, flexShrink: 0, textAlign: 'right' }}>
          <span style={{ fontFamily: FONTS.mono, fontSize: 9, letterSpacing: 1, textTransform:'uppercase', color: theme.textMute }}>Out</span>
          <span style={{ fontFamily: FONTS.mono, fontSize: 12, color: theme.text, fontVariantNumeric:'tabular-nums' }}>
            {hideValue ? '•••' : `−${fmtAED(outOnly, { compact: true })}`}
          </span>
        </div>
      </div>
    </button>
  );
}

Object.assign(window, { HomeScreen, CashFlowHook, PeriodToggle });
